簡體   English   中英

如何在圖像分割中更改 kmeans 簇的顏色

[英]How can I change the color of kmeans clusters in image segmentation

我嘗試使用 kmeans 聚類執行圖像分割。

我想控制類的顏色。我該怎么做?

            # convert to np.float32
            Z = np.float32(Z)

            # define criteria, number of clusters(K) and apply kmeans()
            criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
            K = 2
            ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

            # Now convert back into uint8, and make original image
            center = np.uint8(center)
            res = center[label.flatten()]
            res2 = res.reshape((img.shape))

            #cv2.imshow('res2',res2)
            #cv2.waitKey(0)
            #cv2.destroyAllWindows()

            Image.fromarray(res2).save(f + 'kmeans.png', "png", quality=100)     
kmean()

我不知道你想用 2 個中心控制什么。
如果你想獲得二進制 map,你可以按照這里:

# convert to np.float32
Z = np.float32(Z)

# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 2
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# get the most popular color and specify it is black
black_color = np.argmax(np.bincount(label.flatten()))

# generate binary map with white color
center = np.ones((K,1), dtype = 'uint8') * 255
center[black_color] = [0]
res = center[label.flatten()]
res2 = res.reshape((image_text.shape[0], image_text.shape[1], 1))

return res2

你可以改變任何你想要的顏色,而不僅僅是白色和黑色。 希望能幫到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM