Skip to content
Advertisement

(Linux) Determine Percentage of Different Colors in Image

How can I calculate the percentage of RGB values in an image using Linux?

I’ve done some research and it appears that C# and Python may be the way to go.

Advertisement

Answer

Let ImageMagick generate a histogram for you showing how many pixels there are of each colour, So, say you have have an image called image.jpg, or image.png, like this:

enter image description here

Then you would do this at the Terminal/Command Prompt/shell:

convert image.jpg -colorspace RGB -format %c histogram:info:- | sort -nr

which would give you this list of how often each colour occurs in the image

200614: (255,255,255) #FFFFFF rgb(255,255,255)
  4758: (253,253,218) #FDFDDA rgb(253,253,218)
  4312: (250,250,229) #FAFAE5 rgb(250,250,229)
  1821: (235,237,242) #EBEDF2 rgb(235,237,242)
  1776: (212,214,226) #D4D6E2 rgb(212,214,226)
  1739: (188,190,216) #BCBED8 rgb(188,190,216)
  1372: (  8,  9, 58) #08093A rgb(8,9,58)
  1330: (  6,  6, 38) #060626 rgb(6,6,38)
  1327: (231,231,226) #E7E7E2 rgb(231,231,226)
  1265: (194,196,218) #C2C4DA rgb(194,196,218)
  1244: (  9, 10, 65) #090A41 rgb(9,10,65)
  1164: (200,202,224) #C8CAE0 rgb(200,202,224)
  1132: (  6,  7, 44) #06072C rgb(6,7,44)
  1074: ( 14, 16,115) #0E1073 rgb(14,16,115)
  1050: (  4,  5, 27) #04051B rgb(4,5,27)
  1048: ( 11, 13, 91) #0B0D5B rgb(11,13,91)

I have sorted it so the most common colours are listed first – you can see there are 200,614 white pixels for example.

To calculate percentages, you will need the total number of pixels in the image, so run this:

identify image.jpg
image.jpg JPEG GIF 480x640 480x640+0+0 8-bit sRGB 256c 99.7KB 0.000u 0:00.000

So there are 480×640 pixels in the image, or 307,200 in total. I’ll leave you to work out that means 65.3% are white:-)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement