python - How to find the dominant color in images using Python?
问题描述
I am trying to find top 2 colors from my image to process them accordingly For example if image has blue and white i apply one rule, if it is green and red i apply some other rule.I am trying below code which work for some and not for all.
Main goal : every image has top 2 dominant visible color as shown below and i need to get those color.
Expected result :
image1 : blue and yellow shade
image2 : green shade and blue shade
code :
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))
For this image
I am getting most frequent is [ 1.84704063 1.59035213 252.29132127] (#0101c3bc)
As per this link https://www.w3schools.com/colors/colors_picker.asp?color=80ced6 It is detecting blue that is true.
For green image : instead of green shade it is detecting light pink
Detected coloe : most frequent is [142.17271615 234.99711606 144.77187718] (#c28ec3aac290)
this is wrong prediction
解决方案
该行似乎有错误
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
ashex()
返回您要查找的字符串,您只需将数字0x
放在开头即可。
推荐阅读
- css - 单击生物时,网站未在移动设备上加载
- javascript - string.length 实际上不是 JavaScript 中的方法吗?
- python-2.7 - Python 2.7 中的函数注释 - 重写 Python 3 以在 2.7 中工作
- json - 如何解决 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- mongodb - Docker一运行就退出
- python - 自动检测 Python 中的非确定性行为
- .net - 带有身份验证的 VB.Net HttpClient GET 请求
- node.js - nodejs中执行child_process.exec时,如何处理包含汉字的命令路径?
- ios - 无法使用 AVAudioEngine 录制
- php - while循环内的foreach循环只返回一个结果