如何使用 Python 找到图像中的主色?
How to find the dominant color in images using Python?
我正在尝试从我的图像中找到前 2 种颜色以对它们进行相应处理
例如,如果图像有蓝色和白色,我应用一个规则,如果它是绿色和红色,我应用其他一些 rule.I 我正在尝试下面的代码,它适用于某些而不适用于所有。
主要目标:每个图像都有前 2 个主要可见颜色,如下所示,我需要获得这些颜色。
预期结果:
图片 1:蓝色和黄色阴影
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)
根据这个 link https://www.w3schools.com/colors/colors_picker.asp?color=80ced6 它正在检测蓝色是真的。
对于绿色图像:它检测的不是绿色阴影,而是浅粉色
检测到coloe: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()
returns 是您要查找的字符串,您只需删除 0x
开头的数字即可。
我正在尝试从我的图像中找到前 2 种颜色以对它们进行相应处理 例如,如果图像有蓝色和白色,我应用一个规则,如果它是绿色和红色,我应用其他一些 rule.I 我正在尝试下面的代码,它适用于某些而不适用于所有。
主要目标:每个图像都有前 2 个主要可见颜色,如下所示,我需要获得这些颜色。
预期结果:
图片 1:蓝色和黄色阴影
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)
根据这个 link https://www.w3schools.com/colors/colors_picker.asp?color=80ced6 它正在检测蓝色是真的。
对于绿色图像:它检测的不是绿色阴影,而是浅粉色
检测到coloe: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()
returns 是您要查找的字符串,您只需删除 0x
开头的数字即可。