Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the average colour of an area in an image

Tags:

imagemagick

The goal is to lay a caption on top of an image and set the text colour to one that will contrast with the background it is positioned on top of. To that end, I wish to calculate the average colour of the area inside the red rectangles in the following images:

enter image description here

enter image description here

like image 761
waigani Avatar asked May 31 '12 00:05

waigani


People also ask

How do you calculate average hue?

How is average hue computed and reported? The average hue is calculated using mean of circular quantities. The standard way of computing the average cannot be used because hue is a periodic quantity (modulo 360). The ˉhr is then converted to degress using 180πˉhr(mod360).

How do you find the average color in Photoshop?

Filter > Blur > Average finds the average of all of the colors in an image (or in a selection) and fills the entire image (or selection) with that color.


3 Answers

Expanding on Bonzo’s answer. This is an example command

convert Y82IirS.jpg -resize 1x1 txt:

Result

# ImageMagick pixel enumeration: 1,1,255,srgb
0,0: (220,176, 44)  #DCB02C  srgb(220,176,44)

Average colour of an image

like image 86
Zombo Avatar answered Nov 17 '22 14:11

Zombo


I would crop to the area you are interested in then resize it to 1 pixel. Then get the value of that pixel.

like image 28
Bonzo Avatar answered Nov 17 '22 14:11

Bonzo


Here is a command that handles both cropping and color detection, and also produces output in a consistent R,G,B format:

 convert image.gif -crop 6x7+8+9 -resize 1x1\! -format "%[fx:int(255*r+.5)],%[fx:int(255*g+.5)],%[fx:int(255*b+.5)]" info:-

where, in 6x7+8+9 :

 6: image width (pixels)
 7: image height (pixels)
 8: x-coordinate of top left corner
 9: y-coordinate of top left corner

Returns

 176,191,67

Adapted from https://stackoverflow.com/a/25488429/3124680

like image 38
stuart Avatar answered Nov 17 '22 14:11

stuart