【发布时间】:2019-03-19 01:34:09
【问题描述】:
我正在尝试使用阈值来分割颜色。但这不是行不通的。我如何在这张图片中分割红色和绿色。
谢谢
使用 Kmeans 后的这张图片
使用阈值分割后的图像
我的代码
import numpy as np
import cv2
img = cv2.imread('watermelon.jpg')
Z = img.reshape((-1,3))
# 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 = 4
ret,label,center=cv2.kmeans(Z,K, 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))
gray = cv2.cvtColor(res2,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
#segmentation
gray = cv2.cvtColor(res2,cv2.COLOR_BGR2GRAY)
ret, threshseg = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
cv2.imwrite('img_CV2_95.jpg',threshseg)
cv2.imwrite('img_CV2_94.jpg',res2)
cv2.imshow('threshseg',threshseg)
cv2.imshow('thresh',thresh)
cv2.imshow('res2',res2)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
【问题讨论】:
-
如果您附加未修改的输入图像,这将非常有用。 (我猜你还在使用 OpenCV 2.4.x,因为你调用
kmeans时只有 5 个参数?这也很有用。) -
将
label重新整形为与img相同的宽度/高度,然后使用inRange创建掩码,选择具有给定标签的所有像素。类似this...
标签: python-2.7 opencv