【发布时间】:2016-09-11 19:54:50
【问题描述】:
我正在尝试应用 opencv 中的 kmeans,以便在 HSV 颜色空间中分割图像。
def leftOffset(src, p_countours):
height, width, size = src.shape
p_width = width/p_countours
o_left = src[0:height, 0:p_width]
HSV_img = cv2.cvtColor(o_left, cv2.COLOR_BGR2HSV)
hue = HSV_img[0]
hue = np.float32(HSV_img)
# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# Set flags (Just to avoid line break in the code)
flags = cv2.KMEANS_RANDOM_CENTERS
# Apply KMeans
compactness,labels,centers = cv2.kmeans(hue,2,criteria,10,flags)
centers = np.uint8(centers)
res = centers[labels.flatten()]
res2 = res.reshape((hue.shape))
cv2.imshow("o_left", hue)
cv2.waitKey(0)
我现在可以将 kmeans 算法应用于 K=2 的 HSVImage[0],如何根据结果获得类似阈值的图像?
谢谢
为了澄清问题: 我有基于颜色的验证码,我想分割每个数字。
我将使用k-means方法找出主色并分割里面的数字。
【问题讨论】:
-
我可能不完全理解这个问题。能否请您附上一张图片来澄清一下?
-
@tfv 我添加了 2 张测试图片
-
你用的是什么版本的opencv?
-
2.4.8 @YonatanSimson
-
那么我下面答案中的代码应该适合你