commit 32b1625fdef38f6ffb65216a589080d0e279f790 Author: karl Date: Sun Oct 31 23:49:04 2021 +0100 Add example code from StackOverflow this might be a good first approach. diff --git a/detect.py b/detect.py new file mode 100755 index 0000000..726a580 --- /dev/null +++ b/detect.py @@ -0,0 +1,46 @@ +# sample code from https://stackoverflow.com/questions/43111029/how-to-find-the-average-colour-of-an-image-in-python-with-opencv + +import matplotlib +matplotlib.use('TkAgg') + +import matplotlib.pyplot as plt +import cv2 +import numpy as np +from skimage import io + +img = io.imread('https://i.stack.imgur.com/DNM65.png')[:, :, :-1] + +# Average color +average = img.mean(axis=0).mean(axis=0) + +# Dominant color +pixels = np.float32(img.reshape(-1, 3)) + +n_colors = 5 +criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1) +flags = cv2.KMEANS_RANDOM_CENTERS + +_, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags) +_, counts = np.unique(labels, return_counts=True) + +dominant = palette[np.argmax(counts)] + +# Graph visualization +avg_patch = np.ones(shape=img.shape, dtype=np.uint8)*np.uint8(average) + +indices = np.argsort(counts)[::-1] +freqs = np.cumsum(np.hstack([[0], counts[indices]/float(counts.sum())])) +rows = np.int_(img.shape[0]*freqs) + +dom_patch = np.zeros(shape=img.shape, dtype=np.uint8) +for i in range(len(rows) - 1): + dom_patch[rows[i]:rows[i + 1], :, :] += np.uint8(palette[indices[i]]) + +fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12,6)) +ax0.imshow(avg_patch) +ax0.set_title('Average color') +ax0.axis('off') +ax1.imshow(dom_patch) +ax1.set_title('Dominant colors') +ax1.axis('off') +plt.show()