70 lines
1.8 KiB
Python
Executable File
70 lines
1.8 KiB
Python
Executable File
# 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('Agg')
|
|
|
|
import matplotlib.pyplot as plt
|
|
import cv2
|
|
import numpy as np
|
|
from skimage import io
|
|
import colorsys
|
|
import time
|
|
|
|
img_path = 'input.jpg'
|
|
|
|
from picamera import PiCamera
|
|
camera = PiCamera()
|
|
time.sleep(2) # wait for the camera to initialize
|
|
camera.capture(img_path)
|
|
|
|
|
|
# Read the result
|
|
img = io.imread(img_path)[:, :, :]
|
|
|
|
# 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]])
|
|
|
|
palette /= 255.0
|
|
|
|
def get_saturation(rgb_color):
|
|
return colorsys.rgb_to_hsv(*rgb_color)[1]
|
|
|
|
# Lid color is likely the color with the highest saturation
|
|
lid_color = max(palette, key=get_saturation)
|
|
|
|
fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(12,4))
|
|
ax0.imshow(img)
|
|
ax0.set_title('Input')
|
|
ax0.axis('off')
|
|
ax1.imshow(dom_patch)
|
|
ax1.set_title('Dominant colors')
|
|
ax1.axis('off')
|
|
ax2.add_patch(matplotlib.patches.Rectangle((0, 0), 200, 200, color=lid_color))
|
|
ax2.set_title('Probable Lid Color')
|
|
ax2.axis('off')
|
|
|
|
plt.savefig(img_path + "_result.png")
|