gpt4 book ai didi

Python + OpenCV 使用 Kmeans 进行颜色分割

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:11 24 4
gpt4 key购买 nike

我正在尝试应用来自 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)

我现在可以对 K=2 的 HSVImage[0] 应用 kmeans 算法,如何根据结果得到像阈值一样的图像?

谢谢

澄清问题:我有基于颜色的验证码,我想分割每个数字。

图像就像6

1

我将使用 k-means 方法找出主色并分割其中的数字。

最佳答案

1) 如果您只需要找到主色,为什么不找到每个颜色 channel 的直方图呢?找到主要 channel 然后使用 otsu 仅分割该 channel ?例如,如果我只对色调设置阈值,我可以获得不错的结果。 K-means 对于这项任务来说可能有点矫枉过正:

import cv2
import numpy as np
import matplotlib.pylab as plt

## Simple Otsu over hue
six = cv2.imread('7zovC.jpg')

##convert to hsv
hsv = cv2.cvtColor(six, cv2.COLOR_BGR2HSV)
hue = hsv[:, :, 0]

binary_img = cv2.threshold(hue, 128, 255, cv2.THRESH_OTSU)

plt.figure()
plt.imshow(binary_img*255)
plt.show()

2) 为什么不使用所有 channel 进行聚类而不是仅使用色调?你需要的是聚类->颜色量化这个link应该有用。这是针对 opencv 版本 > 3.0.0

对于 python 2.4.11,cv2.kmeans 的界面略有不同,您可以改用它:

def color_quantize(img, K):
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)
ret, label, center = cv2.kmeans(Z, 2, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

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

label_img = label.reshape((img.shape[:2]))
return label_img, quantized_img



six = cv2.imread('7zovC.jpg')


##convert to hsv
hsv = cv2.cvtColor(six, cv2.COLOR_BGR2HSV)

K = 2
label_img, six_q = color_quantize(hsv, K)



plt.figure()
plt.imshow(label_img)

plt.show()

我的颜色量化结果并不令人印象深刻。

关于Python + OpenCV 使用 Kmeans 进行颜色分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37246918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com