[英]How to find the dominant color in images using Python?
我正在尝试从图像中找到前2种颜色以进行相应的处理,例如,如果图像具有蓝色和白色,则应用一条规则,如果是绿色和红色,则应用其他规则。不适合所有人。
主要目标:每个图像都具有如下所示的前2种主要可见颜色,我需要获取这些颜色。
预期结果 :
image1:蓝色和黄色阴影
image2:绿色和蓝色阴影
代码:
from PIL import Image
import numpy as np
import scipy
import scipy.misc
import scipy.cluster
NUM_CLUSTERS = 5
print('reading image')
im = Image.open("captcha_green.jpg") # optional, to reduce time
ar = np.asarray(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)
print('find clus')
codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
print ('cluster centres:\n', codes)
vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes
counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences
index_max = scipy.argmax(counts) # find most frequent
peak = codes[index_max]
colour = ''.join(chr(int(c)) for c in peak).encode("utf-8").hex()
print ('most frequent is %s (#%s)' % (peak, colour))
对于这张图片
我最常frequent is [ 1.84704063 1.59035213 252.29132127] (#0101c3bc)
按照此链接https://www.w3schools.com/colors/colors_picker.asp?color=80ced6它检测到的是蓝色。
对于绿色图像:检测到浅粉红色而不是绿色阴影
检测到的可乐: most frequent is [142.17271615 234.99711606 144.77187718] (#c28ec3aac290)
这是错误的预测
该行似乎有错误
colour = ''.join(chr(int(c)) for c in peak).encode("utf-8").hex()
尝试添加这个
for i in peak:
print(hex(int(i)))
它将打印正确的十六进制字符。
尝试以下行:
colour = ''.join([hex(int(c))[2:].zfill(2) for c in peak])
不需要chr
因为hex()
返回了您要查找的字符串,您只需要删除0x
放置0x
的数字即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.