学习笔记1(OpenCVandPythonK-MeansColorClustering)颜⾊聚类OpenCV 和Python K-means 颜⾊聚类
想了很多天,打算还是重新学习⼀下opencv的图像处理(因为今天看了⼀段代码,有很多模糊的函数和⽤意),同时也在我的博客上记录下我的学习笔记。有不对的地⽅,看到了⿇烦留⾔指正,谢谢
最近在看Adrian Rosebrock的博客,我的英语不太好,所以看的很慢,以后的笔记也是看了他的博客所记录的
下⾯的代码可以看出来
# import the necessary packages
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import argparse
import utils
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image", required =True,help="Path to the image")
ap.add_argument("-c","--clusters", required =True,type=int,
help="# of clusters")
#我们所希望分成聚类的个数
args =vars(ap.parse_args())
# load the image and convert it from BGR to RGB so that
# we can dispaly it with matplotlib
image = cv2.imread(args["image"])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#我们从磁盘加载图像,然后将其从BGR转换为RGB。OpenCV将图像表⽰为多维NumPy数组。但是,这些图像是按BGR顺序存储的,⽽不是按RGB顺序存储的。为了解决这个问题,可以直接使⽤cvtcolor函数
# show our image
plt.figure()
plt.axis("off")
#表⽰关闭掉了x,y轴
plt.imshow(image)
#输出显⽰图像
我们将把MxN像素的图像作为数据点。为了做到这⼀点,我们需要重新塑造我们的图像的像素列表,⽽不是MxN矩阵的像素
image = shape((image.shape[0]* image.shape[1],3)
#将NumPy数组重新塑造为RGB像素的列表
现在数据点都准备好了,我们可以⽤k-means写这两⾏代码来到图像中最主要的颜⾊:
# cluster the pixel intensities
clt = KMeans(n_clusters = args["clusters"])
#提供了我们希望⽣成的聚类数量
clt.fit(image)
#⽤fit()的⽅法聚类我的像素列表
然⽽,为了显⽰图像中最主要的颜⾊,我们需要定义两个辅助函数。
import numpy as np
import cv2
def centroid_histogram(clt):
numLabels = np.arange(0,len(np.unique(clt.labels_))+1)
#k-means算法将图像中的每个像素分配给最近的集。
#获取集数量rectangle函数opencv
(hist, _)= np.histogram(clt.labels_, bins = numLabels)
#然后创建分配给每个集的像素数量的直⽅图。
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# return the histogram
return hist
第⼆个辅助函数为:
def plot_colors(hist, centroids):
# initialize the bar chart representing the relative frequency
# of each of the colors
bar = np.zeros((50,300,3), dtype ="uint8")
startX =0
# loop over the percentage of each cluster and the color of
# each cluster
for(percent, color)in zip(hist, centroids):
# plot the relative percentage of each cluster
endX = startX +(percent *300)
color.astype("uint8").tolist(),-1)
startX = endX
# return the bar chart
return bar
此⽅法只接受单个参数clt。这是我们在家谱本中创建的k-means集对象。下⾯为全部的代码:
# import the necessary packages
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import argparse
import cv2
import numpy as np
def centroid_histogram(clt):
# grab the number of different clusters and create a histogram
# based on the number of pixels assigned to each cluster
numLabels = np.arange(0,len(np.unique(clt.labels_))+1)
(hist, _)= np.histogram(clt.labels_, bins = numLabels)
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# return the histogram
return hist
def plot_colors(hist, centroids):
# initialize the bar chart representing the relative frequency
# of each of the colors
bar = np.zeros((50,300,3), dtype ="uint8")
startX =0
# loop over the percentage of each cluster and the color of
# each cluster
for(percent, color)in zip(hist, centroids):
# plot the relative percentage of each cluster
endX = startX +(percent *300)
color.astype("uint8").tolist(),-1)
startX = endX
# return the bar chart
return bar
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image", required =True,help="Path to the image") ap.add_argument("-c","--clusters", required =True,type=int,
help="# of clusters")
args =vars(ap.parse_args())
# load the image and convert it from BGR to RGB so that
# we can dispaly it with matplotlib
image = cv2.imread(args["image"])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# show our image
plt.figure()
plt.axis("off")
plt.imshow(image)
# reshape the image to be a list of pixels
image = shape((image.shape[0]* image.shape[1],3))
# cluster the pixel intensities
clt = KMeans(n_clusters = args["clusters"])
clt.fit(image)
# build a histogram of clusters and then create a figure
# representing the number of pixels labeled to each color
hist = centroid_histogram(clt)
bar = plot_colors(hist, clt.cluster_centers_)
# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
在运⾏的时候,可能会出现个别的包没有到,需要⾃⼰去下载
⽐如缺少module sklearn时,终端直接输⼊:
pip3 install sklearn
这样就可以了,⾄于运⾏时候,需要在终端进⾏调⽤可参照

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。