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)
原始图像与聚类图像