6

I am using rmagick to deal with getting a each single pixel of a bitmap. I need to get the values of colors in depth of 8 (256 colors), but unfortunately when i use pixel.[color] (pixel. red for example), i am getting them in depth of 16. It is happening even after i used image.quantize(256).

Here is the code:

require 'RMagick'
include Magick

image = ImageList.new("image.bmp")
image3 = image.quantize(number_colors = 256)
puts image3.number_colors

image2 = Image.new(image.columns, image.rows)

(0..image.columns).each do |x|
    (0..image.rows).each do |y|
        pixel = image3.pixel_color(x, y)

    print pixel.red
    print ", "
    print pixel.green
    print ", "
    print pixel.blue
    print "\n"

    image2.pixel_color(x, y, pixel)
    end
end

What should I to get just values of 0..255?

Michal
  • 459
  • 2
  • 7
  • 25
  • Already discussed here: http://stackoverflow.com/questions/6499161/pixel-rgb-with-imagemagick-and-rails – gnuf Nov 15 '12 at 02:57

1 Answers1

4

They are stored in a 'quantum depth' of 16-bits. You can rebuild the library to change this. Or you can simply divide each value by 257.

There's a function called MagickExportImagePixels which can get you the 8-bit pixel data that you want. Whenever you perform a transformation etc on an image it will get converted back to 16-bit pixels.

Bert
  • 2,134
  • 19
  • 19
  • Because 256 * 255 = 65280. 257 * 255 = 65535, therefore giving you the full range when converting 16 bit to 8 bit – Bert Apr 10 '15 at 00:28
  • You forgot about flooring. Your *257 * 255 = 65535* proves, that only one of 65536 colors would be converted to 255 -- all lower would be 254. The proper convertion to one-byte data is right shift by 8 bits, i.e. division by 256. – Nakilon Apr 10 '15 at 01:21
  • You can argue this with the ImageMagick developers if you want. That's what they have suggested. – Bert Apr 11 '15 at 17:44
  • 1
    I do not see any ImageMagick developer here. While it is enough to be modern 10-years old kid to know math enough to agree with me. – Nakilon Apr 12 '15 at 01:33
  • I did some experiments dividing by both 256 and 257 truncate to the same values. In either case, I get a 0-255 number that matches exactly what my image editing program describes as the pixel values. – Josh Rosen Mar 09 '19 at 08:28