顏色識別演算法
發布時間: 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也在這個目錄下。
看看能否幫到你
熱點內容