使用 Python 和 OpenCV 进行图像聚类

人工智能等各类编程培训资料整理,所有资源无秘无压缩-购买会员

importnumpyasnp

importcv2

importmatplotlib.pyplotasplt

image=cv2.imread(/input/hillstation/hillstation.jpg)

plt.imshow(image)#originalimage

i=image.sum(axis=2)#converttheshapeofimagein2dimensions

i.shape

(183,275)

img=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)

plt.imshow(img)#converttheimageintoRGB

vector=img.reshape((-1,3))#convertthemXNX3imageintokX3matrixwherek=mXnandeachrowwillbeavectorin3dimensionsspace

vector

array([[55,61,111],

[55,61,111],

[55,61,113],

…,

[42,40,25],

[35,33,18],

[28,26,13]],dtype=uint8)

vector=np.float32(vector)#converttheuint8valuestofloatvalues.k-meansmethodtoopencv

vector

array([[55.,61.,111.],

[55.,61.,111.],

[55.,61.,113.],

…,

[42.,40.,25.],

[35.,33.,18.],

[28.,26.,13.]],dtype=float32)

#clusteringintomultiplelabelsasthepicturehasmultiplecolours.

c=(cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER,10,1.0)

#firstparameterisusedforstopthecriteriaiftheaccuracyisachieved

#secondparameterisusedforstopthealgorithmafterhespecifiednumberofiterations

#cistheiterationterminationprocess.Whentheiterationissatisfied,thealgorithmwillstop.

k=5#numberofclusters

attempts=10#numberoftimesthealgorithmisexecutedusingdifferentlabelings.

ret,label,center=cv2.kmeans(vector,k,None,c,attempts,cv2.KMEANS_PP_CENTERS)

#cv2.kmeans_pp_centersisusedtospecifyhowinitialcentersaretaken

center=np.uint8(center)

res=center[label.flatten()]#accessthelabeltoregeneratetheimage

im=res.reshape(img.shape)

#visualization

x=8

y=6

plt.figure(figsize=(x,y))

plt.subplot(1,2,1)

plt.imshow(img)

plt.title(originalimage)

plt.axis(False)

plt.subplot(1,2,2)

plt.imshow(im)

plt.title(Clusteredimage)

plt.axis(False)

(-0.5,274.5,182.5,-0.5)

原始图像与聚类图像

免责声明: 1、本站信息来自网络,版权争议与本站无关 2、本站所有主题由该帖子作者发表,该帖子作者与本站享有帖子相关版权 3、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者和本站的同意 4、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责 5、用户所发布的一切软件的解密分析文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。 6、您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 7、请支持正版软件、得到更好的正版服务。 8、如有侵权请立即告知本站,本站将及时予与删除 9、本站所发布的一切破解补丁、注册机和注册信息及软件的解密分析文章和视频仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。
600学习网 » 使用 Python 和 OpenCV 进行图像聚类