Is there an efficient way to create an RMagick image from the data in a 2D NArray (a Ruby class that's supposed to be more efficient than regular arrays), or are the two libraries just incompatible in their data types?
The following code works, but it does it the hard way: converting data types pixel by pixel with nested do-loops. As far as I can tell, this gives me a lot of extra work and none of the advantages of NArray. It runs slower than molasses in January:
def LineaProcessor.createImage(dataArray, width, height, filename)
image = Magick::Image.new width, height
# scale pixel values from 0..256*255 (the RMagick pixel uses 16 bits)
scaling = 65280/dataArray.max
# set each pixel...I couldn't find any easy way to convert array types
width.times do |x|
height.times do |y|
g = dataArray[x+y*width]*scaling
pixel = Magick::Pixel.new(g, g, g,0)
image.pixel_color x, y, pixel
end
end
image
end
Here is some code I used to do this for greyscale only, and seems relatively quick:
The key methods to read up on are
Magick::Image#import_pixels,Magick::Image#export_pixelsandNArray.castIt should be possible to do something similar channel-by-channel to deal with colour images. There is no fundamental reason why you have to use floats, I just wanted the format for my purpose (input to neural net)