颜色识别算法
发布时间: 2022-12-13 16:08:26
① 用python写识别图片主要颜色的程序
#-*-coding:utf-8-*-
importcolorsys
defget_dominant_color(image):
#颜色模式转换,以便输出rgb颜色值
image=image.convert('RGBA')
#生成缩略图,减少计算量,减小cpu压力
image.thumbnail((200,200))
max_score=None
dominant_color=None
forcount,(r,g,b,a)inimage.getcolors(image.size[0]*image.size[1]):
#跳过纯黑色
ifa==0:
continue
saturation=colorsys.rgb_to_hsv(r/255.0,g/255.0,b/255.0)[1]
y=min(abs(r*2104+g*4130+b*802+4096+131072)>>13,235)
y=(y-16.0)/(235-16)
#忽略高亮色
ify>0.9:
continue
#Calculatethescore,.
#Add0.1tothesaturationsowedon'tcompletelyignoregrayscale
#,butstillgivethemalow
#weight.
score=(saturation+0.1)*count
ifscore>max_score:
max_score=score
dominant_color=(r,g,b)
returndominant_color
if__name__=="__main__":
fromPILimportImage
importos
path=r'.\pics\'
fp=open('file_color.txt','w')
forfilenameinos.listdir(path):
printpath+filename
try:
color=get_dominant_color(Image.open(path+filename))
fp.write('Thecolorof'+filename+'is'+str(color)+' ')
except:
print"Thisfileformatisnotsupport"
fp.close()
pics文件夹和python程序在一个目录下,产生的文件名file_color.txt也在这个目录下。
看看能否帮到你
热点内容