導航:首頁 > 編程語言 > pythongetcolors

pythongetcolors

發布時間:2023-01-04 08:25:07

『壹』 python的pil模塊怎麼判斷圖片是否相同

利用python的PIL模塊的強大的圖像處理功能就可以做到,下面上代碼:

import colorsys

def get_dominant_color(image):

#顏色模式轉換,以便輸出rgb顏色值
image = image.convert('RGBA')

#生成縮略圖,減少計算量,減小cpu壓力
image.thumbnail((200, 200))

max_score = None
dominant_color = None

for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
# 跳過純黑色
if a == 0:

『貳』 如何用python將文件夾中圖片根據顏色分類


本文實例講述了Python通過PIL獲取圖片主要顏色並和顏色庫進行對比的方法。分享給大家供大家參考。具體分析如下:

這段代碼主要用來從圖片提取其主要顏色,類似Goolge和Bai的圖片搜索時可以指定按照顏色搜索,所以我們先需要將每張圖片的主要顏色提取出來,然後將顏色劃分到與其最接近的顏色段上,然後就可以按照顏色搜索了。

在使用google或者搜圖的時候會發現有一個圖片顏色選項,感覺非常有意思,有人可能會想這肯定是人為的去劃分的,呵呵,有這種可能,但是估計人會累死,開個玩笑,當然是通過機器識別的,海量的圖片只有機器識別才能做到。

那用python能不能實現這種功能呢?答案是:能

利用python的PIL模塊的強大的圖像處理功能就可以做到,下面上代碼:

復制代碼代碼如下:

import colorsys
def get_dominant_color(image):
#顏色模式轉換,以便輸出rgb顏色值
image = image.convert('RGBA')
#生成縮略圖,減少計算量,減小cpu壓力
image.thumbnail((200, 200))
max_score = None
dominant_color = None
for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
# 跳過純黑色
if a == 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)
# 忽略高亮色
if y > 0.9:
continue
# Calculate the score, preferring highly saturated colors.
# Add 0.1 to the saturation so we don't completely ignore grayscale
# colors by multiplying the count by zero, but still give them a low
# weight.
score = (saturation + 0.1) * count
if score > max_score:
max_score = score
dominant_color = (r, g, b)
return dominant_color


使用方法:

from PIL import Image
print get_dominant_color(Image.open('logo.jpg'))

這樣就會返回一個rgb顏色,但是這個值是很精確的范圍,那我們如何實現網路圖片那樣的色域呢??

其實方法很簡單,r/g/b都是0-255的值,我們只要把這三個值分別劃分相等的區間,然後組合,取近似值。例如:劃分為0-127,和128-255,然後自由組合,可以出現八種組合,然後從中挑出比較有代表性的顏色即可。

當然我只是舉一個例子,你也可以劃分的更細,那樣顯示的顏色就會更准確~~大家趕快試試吧

『叄』 用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也在這個目錄下。

看看能否幫到你

『肆』 用python K值聚類識別圖片主要顏色的程序,演算法python代碼已經有了

難得被人求助一次, 這個必須回答一下. 不過你的需求確實沒有寫得太清楚. 根據k值演算法出來的是主要顏色有三個, 所以我把三個顏色都打在記事本里了. 如果和你的需求有誤, 請自行解決吧.


另外這里需要用到numpy的庫, 希望你裝了, 如果沒裝, 這個直接安裝也比較麻煩, 可以看一下portablepython的綠色版。


代碼如下:


#-*-coding:utf-8-*-
importImage
importrandom
importnumpy
classCluster(object):
def__init__(self):
self.pixels=[]
self.centroid=None
defaddPoint(self,pixel):
self.pixels.append(pixel)
defsetNewCentroid(self):
R=[colour[0]forcolourinself.pixels]
G=[colour[1]forcolourinself.pixels]
B=[colour[2]forcolourinself.pixels]
R=sum(R)/len(R)
G=sum(G)/len(G)
B=sum(B)/len(B)
self.centroid=(R,G,B)
self.pixels=[]
returnself.centroid
classKmeans(object):
def__init__(self,k=3,max_iterations=5,min_distance=5.0,size=200):
self.k=k
self.max_iterations=max_iterations
self.min_distance=min_distance
self.size=(size,size)
defrun(self,image):
self.image=image
self.image.thumbnail(self.size)
self.pixels=numpy.array(image.getdata(),dtype=numpy.uint8)
self.clusters=[Noneforiinrange(self.k)]
self.oldClusters=None
randomPixels=random.sample(self.pixels,self.k)
foridxinrange(self.k):
self.clusters[idx]=Cluster()
self.clusters[idx].centroid=randomPixels[idx]
iterations=0
whileself.shouldExit(iterations)isFalse:
self.oldClusters=[cluster.centroidforclusterinself.clusters]
printiterations
forpixelinself.pixels:
self.assignClusters(pixel)
forclusterinself.clusters:
cluster.setNewCentroid()
iterations+=1
return[cluster.centroidforclusterinself.clusters]
defassignClusters(self,pixel):
shortest=float('Inf')
forclusterinself.clusters:
distance=self.calcDistance(cluster.centroid,pixel)
ifdistance<shortest:
shortest=distance
nearest=cluster
nearest.addPoint(pixel)
defcalcDistance(self,a,b):
result=numpy.sqrt(sum((a-b)**2))
returnresult
defshouldExit(self,iterations):
ifself.oldClustersisNone:
returnFalse
foridxinrange(self.k):
dist=self.calcDistance(
numpy.array(self.clusters[idx].centroid),
numpy.array(self.oldClusters[idx])
)
ifdist<self.min_distance:
returnTrue
ifiterations<=self.max_iterations:
returnFalse
returnTrue
#############################################
#
defshowImage(self):
self.image.show()
defshowCentroidColours(self):
forclusterinself.clusters:
image=Image.new("RGB",(200,200),cluster.centroid)
image.show()
defshowClustering(self):
localPixels=[None]*len(self.image.getdata())
foridx,pixelinenumerate(self.pixels):
shortest=float('Inf')
forclusterinself.clusters:
distance=self.calcDistance(
cluster.centroid,
pixel
)
ifdistance<shortest:
shortest=distance
nearest=cluster
localPixels[idx]=nearest.centroid
w,h=self.image.size
localPixels=numpy.asarray(localPixels)
.astype('uint8')
.reshape((h,w,3))
colourMap=Image.fromarray(localPixels)
colourMap.show()

if__name__=="__main__":
fromPILimportImage
importos

k_image=Kmeans()
path=r'.\pics\'
fp=open('file_color.txt','w')
forfilenameinos.listdir(path):
printpath+filename
try:
color=k_image.run(Image.open(path+filename))
fp.write('Thecolorof'+filename+'is'+str(color)+' ')
except:
print"Thisfileformatisnotsupport"
fp.close()
閱讀全文

與pythongetcolors相關的資料

熱點內容
dvd光碟存儲漢子演算法 瀏覽:755
蘋果郵件無法連接伺服器地址 瀏覽:958
phpffmpeg轉碼 瀏覽:669
長沙好玩的解壓項目 瀏覽:140
專屬學情分析報告是什麼app 瀏覽:562
php工程部署 瀏覽:831
android全屏透明 瀏覽:730
阿里雲伺服器已開通怎麼辦 瀏覽:801
光遇為什麼登錄時伺服器已滿 瀏覽:300
PDF分析 瀏覽:482
h3c光纖全工半全工設置命令 瀏覽:140
公司法pdf下載 瀏覽:381
linuxmarkdown 瀏覽:349
華為手機怎麼多選文件夾 瀏覽:681
如何取消命令方塊指令 瀏覽:347
風翼app為什麼進不去了 瀏覽:776
im4java壓縮圖片 瀏覽:360
數據查詢網站源碼 瀏覽:148
伊克塞爾文檔怎麼進行加密 瀏覽:888
app轉賬是什麼 瀏覽:161