要在Python中对HSV颜色空间进行量化操作,可以采用以下步骤:
import cv2
import numpy as np
img = cv2.imread('image.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_purple = np.array([130,50,50])
upper_purple = np.array([170,255,255])
mask = cv2.inRange(hsv, lower_purple, upper_purple)
K=4
Z = hsv.reshape((-1,3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((hsv.shape))
上述代码中,我们将颜色聚类成了4个类别,即K=4。代码执行完毕后,res2就是量化后的图像。
cv2.imwrite('quantized_image.jpg', res2)
下面给出两个示例说明:
img = cv2.imread('image.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
K=2
Z = hsv.reshape((-1,3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((hsv.shape))
cv2.imwrite('quantized_image_2.jpg', res2)
img = cv2.imread('image.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_green = np.array([35,50,50])
upper_green = np.array([80,255,255])
mask = cv2.inRange(hsv, lower_green, upper_green)
K=5
Z = hsv.reshape((-1,3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((hsv.shape))
cv2.imwrite('quantized_image_5.jpg', res2)
通过以上攻略及示例,我们可以看到,量化HSV颜色空间的步骤较为简单,主要是颜色聚类的过程。同时,我们也可以实现参数化地进行颜色量化操作,以达到更好的效果。
本文链接:http://task.lmcjl.com/news/15068.html