本文目錄一覽:
- 1、用python寫識別圖片主要顏色的程序
- 2、如何用python將文件夾中圖片根據顏色分類
- 3、怎樣使用Python圖像處理
- 4、opencv對圖像的顏色識別問題,要用python2實現
- 5、用python K值聚類識別圖片主要顏色的程序,算法python代碼已經有了
- 6、提取HSV顏色特徵,並計算維數的熵,最後保存特徵和熵,形式:圖像名、特徵和熵,用python實現,怎麼實現
用python寫識別圖片主要顏色的程序
# -*- coding: utf-8 -*-
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
if __name__==”__main__”:
from PIL import Image
import os
path = r’.\\pics\\’
fp = open(‘file_color.txt’,’w’)
for filename in os.listdir(path):
print path+filename
try:
color = get_dominant_color(Image.open(path+filename))
fp.write(‘The color of ‘+filename+’ is ‘+str(color)+’\n’)
except:
print “This file format is not support”
fp.close()
pics文件夾和python程序在一個目錄下,產生的文件名file_color.txt也在這個目錄下。
看看能否幫到你
如何用python將文件夾中圖片根據顏色分類
本文實例講述了Python通過PIL獲取圖片主要顏色並和顏色庫進行對比的方法。分享給大家供大家參考。具體分析如下:
這段代碼主要用來從圖片提取其主要顏色,類似Goolge和Baidu的圖片搜索時可以指定按照顏色搜索,所以我們先需要將每張圖片的主要顏色提取出來,然後將顏色劃分到與其最接近的顏色段上,然後就可以按照顏色搜索了。
在使用google或者baidu搜圖的時候會發現有一個圖片顏色選項,感覺非常有意思,有人可能會想這肯定是人為的去劃分的,呵呵,有這種可能,但是估計人會累死,開個玩笑,當然是通過機器識別的,海量的圖片只有機器識別才能做到。
那用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圖像處理
Python圖像處理是一種簡單易學,功能強大的解釋型編程語言,它有簡潔明了的語法,高效率的高層數據結構,能夠簡單而有效地實現面向對象編程,下文進行對Python圖像處理進行說明。
當然,首先要感謝“戀花蝶”,是他的文章“用Python圖像處理 ” 幫我堅定了用Python和PIL解決問題的想法,對於PIL的一些介紹和基本操作,可以看看這篇文章。我這裡主要是介紹點我在使用過程中的經驗。
PIL可以對圖像的顏色進行轉換,並支持諸如24位彩色、8位灰度圖和二值圖等模式,簡單的轉換可以通過Image.convert(mode)函數完 成,其中mode表示輸出的顏色模式。例如”L”表示灰度,”1”表示二值圖模式等。
但是利用convert函數將灰度圖轉換為二值圖時,是採用固定的閾 值127來實現的,即灰度高於127的像素值為1,而灰度低於127的像素值為0。為了能夠通過自定義的閾值實現灰度圖到二值圖的轉換,就要用到 Image.point函數。
深度剖析Python語法功能
深度說明Python應用程序特點
對Python數據庫進行學習研究
Python開發人員對Python經驗之談
對Python動態類型語言解析
Image.point函數有多種形式,這裡只討論Image.point(table, mode),利用該函數可以通過查表的方式實現像素顏色的模式轉換。其中table為顏色轉換過程中的映射表,每個顏色通道應當有256個元素,而 mode表示所輸出的顏色模式,同樣的,”L”表示灰度,”1”表示二值圖模式。
可見,轉換過程的關鍵在於設計映射表,如果只是需要一個簡單的箝位值,可以將table中高於或低於箝位值的元素分別設為1與0。當然,由於這裡的table並沒有什麼特殊要求,所以可以通過對元素的特殊設定實現(0, 255)範圍內,任意需要的一對一映射關係。
示例代碼如下:
import Image # load a color image im = Image.open(”fun.jpg”) # convert to grey level image Lim = im.convert(”L”) Lim.save(”fun_Level.jpg”) # setup a converting table with constant threshold threshold = 80 table = [] for i in range(256): if i threshold: table.append(0) else: table.append(1) # convert to binary image by the table bim = Lim.point(table, ”1”) bim.save(”fun_binary.jpg”)
IT部分通常要完成的任務相當繁重但支撐這些工作的資源卻很少,這已經成為公開的秘密。任何承諾提高編碼效率、降低軟件總成本的IT解決方案都應該進行 周到的考慮。Python圖像處理所具有的一個顯著優勢就是可以在企業的軟件創建和維護階段節約大量資金,而這兩個階段的軟件成本佔到了軟件整個生命周期中總成本 的50%到95%。
Python清晰可讀的語法使得軟件代碼具有異乎尋常的易讀性,甚至對那些不是最初接觸和開發原始項目的程序員都 能具有這樣的強烈感覺。雖然某些程序員反對在Python代碼中大量使用空格。
不過,幾乎人人都承認Python圖像處理的可讀性遠勝於C或者Java,後兩 者都採用了專門的字符標記代碼塊結構、循環、函數以及其他編程結構的開始和結束。提倡Python的人還宣稱,採用這些字符可能會產生顯著的編程風格差 異,使得那些負責維護代碼的人遭遇代碼可讀性方面的困難。轉載
opencv對圖像的顏色識別問題,要用python2實現
我沒用過Python的Opencv的庫,只是用過Python的Image的庫;Image庫已經可以結果這個問題了
我試着做一下:你先得安裝PIL庫
得到rgb三個通道,然後轉到HSV通道,其中H表示0-255的顏色,V表示強度,你大概先知道紫色的範圍是多少
from PIL import Image
import colorsys
def CalculateH(img):
if len(img.getbands()) == 4:
ir,ig,ib,ia = img.split()
else:
ir, ig, ib = img.split()
Hdat = []
Sdat = []
Vdat = []
for rd,gn,bl in zip(ir.getdata(),ig.getdata(),ib.getdata()):
h,l,s = colorsys.rgb_to_hsv(rd/255.,gn/255.,bl/255.)
Hdat.append(h)
Sdat.append(l)
Vdat.append(s)
meanV = mean(Vdat)
return Hdat, meanV
def myreadim(filename):
im = Image.open(filename)
H,V = CalculateH(im)
後面我就懶得寫了,應該思路都清楚了吧,要轉到其他的顏色通道上,不要在rgb通道上
用python K值聚類識別圖片主要顏色的程序,算法python代碼已經有了
難得被人求助一次, 這個必須回答一下. 不過你的需求確實沒有寫得太清楚. 根據k值算法出來的是主要顏色有三個, 所以我把三個顏色都打在記事本里了. 如果和你的需求有誤, 請自行解決吧.
另外這裡需要用到numpy的庫, 希望你裝了, 如果沒裝, 這個直接安裝也比較麻煩, 可以看一下portablepython的綠色版。
代碼如下:
# -*- coding: utf-8 -*-
import Image
import random
import numpy
class Cluster(object):
def __init__(self):
self.pixels = []
self.centroid = None
def addPoint(self, pixel):
self.pixels.append(pixel)
def setNewCentroid(self):
R = [colour[0] for colour in self.pixels]
G = [colour[1] for colour in self.pixels]
B = [colour[2] for colour in self.pixels]
R = sum(R) / len(R)
G = sum(G) / len(G)
B = sum(B) / len(B)
self.centroid = (R, G, B)
self.pixels = []
return self.centroid
class Kmeans(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)
def run(self, image):
self.image = image
self.image.thumbnail(self.size)
self.pixels = numpy.array(image.getdata(), dtype=numpy.uint8)
self.clusters = [None for i in range(self.k)]
self.oldClusters = None
randomPixels = random.sample(self.pixels, self.k)
for idx in range(self.k):
self.clusters[idx] = Cluster()
self.clusters[idx].centroid = randomPixels[idx]
iterations = 0
while self.shouldExit(iterations) is False:
self.oldClusters = [cluster.centroid for cluster in self.clusters]
print iterations
for pixel in self.pixels:
self.assignClusters(pixel)
for cluster in self.clusters:
cluster.setNewCentroid()
iterations += 1
return [cluster.centroid for cluster in self.clusters]
def assignClusters(self, pixel):
shortest = float(‘Inf’)
for cluster in self.clusters:
distance = self.calcDistance(cluster.centroid, pixel)
if distance shortest:
shortest = distance
nearest = cluster
nearest.addPoint(pixel)
def calcDistance(self, a, b):
result = numpy.sqrt(sum((a – b) ** 2))
return result
def shouldExit(self, iterations):
if self.oldClusters is None:
return False
for idx in range(self.k):
dist = self.calcDistance(
numpy.array(self.clusters[idx].centroid),
numpy.array(self.oldClusters[idx])
)
if dist self.min_distance:
return True
if iterations = self.max_iterations:
return False
return True
# ############################################
# The remaining methods are used for debugging
def showImage(self):
self.image.show()
def showCentroidColours(self):
for cluster in self.clusters:
image = Image.new(“RGB”, (200, 200), cluster.centroid)
image.show()
def showClustering(self):
localPixels = [None] * len(self.image.getdata())
for idx, pixel in enumerate(self.pixels):
shortest = float(‘Inf’)
for cluster in self.clusters:
distance = self.calcDistance(
cluster.centroid,
pixel
)
if distance 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__”:
from PIL import Image
import os
k_image=Kmeans()
path = r’.\\pics\\’
fp = open(‘file_color.txt’,’w’)
for filename in os.listdir(path):
print path+filename
try:
color = k_image.run(Image.open(path+filename))
fp.write(‘The color of ‘+filename+’ is ‘+str(color)+’\n’)
except:
print “This file format is not support”
fp.close()
提取HSV顏色特徵,並計算維數的熵,最後保存特徵和熵,形式:圖像名、特徵和熵,用python實現,怎麼實現
可以使用Python版的opencv 來實現。
現讀取圖片:
import cv2
import numpy as np
from matplotlib import pyplot as plt
image=cv2.imread(‘./src/q5.png’)
HSV=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
計算熵
img = np.array(HSV)
for i in range(len(img)):
for j in range(len(img[i])):
val = img[i][j]
tmp[val] = float(tmp[val] + 1)
k = float(k + 1)
for i in range(len(tmp)):
tmp[i] = float(tmp[i] / k)
for i in range(len(tmp)):
if(tmp[i] == 0):
res = res
else:
res = float(res – tmp[i] * (math.log(tmp[i]) / math.log(2.0)))
保存:
HSV圖形可以直接存儲,特徵可以存xml中~
cv2.imwrite(“具體路徑”,HSV)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/186643.html