0

I am trying to average the colours in an image, I have come up with the following script (from here):

scrip.rb:

require 'rmagick'
file = "./img.jpg"
img = Magick::Image.read(file).first
color = img.scale(1, 1).pixel_color(0,0)
p [color.red, color.green, color.blue] 

img.jpg:
enter image description here

BUT the RGB output is [31829, 30571, 27931].

Questions:

  1. Shouldn't the numbers be in the range of [0-255]?
  2. What am I doing wrong?
Community
  • 1
  • 1
dariush
  • 3,191
  • 3
  • 24
  • 43

2 Answers2

0

The reason for the odd output is due to the bit depth. As a previous answer states, "They are stored in a 'quantum depth' of 16-bits." This was an initial assumption, but by looking at previous answers, this makes more sense. In order to properly convert these numbers back to your typically desires [0-255] range, you must divide the values by 256.

Note: You can change the quantum depth during runtime. When reading the file, you should be able to use a block like shown in the following code.

img = Magick::Image.read(file){self.depth = 8}.first
Andrew Kulpa
  • 160
  • 6
0

What you have there is the red, green, and blue histogram values.

You need to divide by 256 in order to get each RGB value. In this case, the RGB values are:

require 'rmagick'
file = "./img.jpg"
img = Magick::Image.read(file).first
color = img.scale(1, 1).pixel_color(0,0)
p [color.red/256, color.green/256, color.blue/256]
  # => [124, 119, 109]

This blog post provides a more thorough explanation on how to analyse images with RMagick.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77