Oct-04-2023, 11:06 AM
(This post was last modified: Oct-04-2023, 07:33 PM by deanhystad.)
I think that should work, but it can be simplified. Compute the ratio of pixels that are the most common color. Compare ratio to a threshold.
from PIL import Image import numpy as np def primary_color_ratio(image): """Return ratio of pixels that are the "background" color.""" pixels = np.array(image.getdata()) _, counts = np.unique(pixels, axis=0, return_counts=True) return max(counts) / (max(len(pixels), 1) print(primary_color_ratio(Image.new("RGB", (10, 10), (255, 0, 0)))) print(primary_color_ratio(Image.open("test.jpg")))
Output:1.0
0.032