Defining a foreground color in Python

I have about 3,000 images and 13 different colors (the background of most of these images is white). If the primary color of the image is one of these 13 different colors, I would like them to be connected.

I saw similar questions, such as python Image Color Definition , that are asking for an average color algorithm. I copied a lot of this code using the Python image and histogram library, and got it to work, but I believe that it is not too reliable for determining the primary colors.

Any ideas? Or libraries that could solve this problem?

Thanks in advance!

: EDIT: Thank you guys, you pretty much all said the same thing to create β€œbuckets” and increase the number of buckets with each nearest pixel in the image. I seem to get a lot of images that return White or Beige, which is also the background on most of these images. Is there any way around or ignoring the background?

Thanks again.

+7
source share
3 answers

You can use the getcolors function to get a list of all the colors in the image. It returns a list of tuples in the form:

(N, COLOR) 

where N is the number of times the color COLOR occurs in the image. To get the maximum color, you can pass a list to the max function:

 >>> from PIL import Image >>> im = Image.open("test.jpg") >>> max(im.getcolors(im.size[0]*im.size[1])) (183, (255, 79, 79)) 

Note that I passed im.size[0]*im.size[1] to the getcolors function, because this is the maximum value of maxcolors (see docs for more details).

+9
source

Personally, I would divide the color space into 8-16 primary colors, then for each pixel I would increase the nearest color bucket by one. At the end of the color, the bucket color with the most pixels wins.

Basically, consider median, not average. You really only care about the colors in the image, while averaging colors usually gives you a whole new color.

+2
source

Since you are trying to match a small number of pre-existing colors, you can try a different approach. Check each image for all the colors and see which one is the closest.

Regarding compliance, I would start by resizing each image to a smaller size to reduce the amount of work that you will do for each; our perception of the color of the image is not too dependent on the amount of detail. For each pixel in the smaller image, find which of the 13 colors is the closest. If it is within a certain threshold, align the counter for that color. After all, which of 13 has the highest score is the winner.

+1
source

All Articles