学习来自 如何使用 OpenCV Python 检测颜色
import cv2
import numpy as npdef red_hsv(img, save=False):lower_hsv1 = np.array([0, 175, 20])higher_hsv1 = np.array([10, 255, 255])lower_hsv2 = np.array([170, 175, 20])higer_hsv2 = np.array([10, 255, 255])mask1 = cv2.inRange(img, lower_hsv1, higher_hsv1)mask2 = cv2.inRange(img, lower_hsv2, higer_hsv2)if save:cv2.imwrite("red-mask-1.jpg", mask1)cv2.imwrite("red-mask-2.jpg", mask2)cv2.imwrite("red-mask.jpg", mask1+mask2)return mask1 + mask2def green_hsv(img, save=False):lower_hsv1 = np.array([40, 150, 20])higher_hsv1 = np.array([70, 255, 255])mask1 = cv2.inRange(img, lower_hsv1, higher_hsv1)if save:cv2.imwrite("green-mask-1.jpg", mask1)return mask1if __name__ == "__main__":bgr = cv2.imread("1.png")hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)cv2.imwrite("hsv.jpg", hsv)mask = red_hsv(hsv, save=True) + green_hsv(hsv, save=True)cv2.imwrite("mask.jpg", mask)result = cv2.bitwise_and(bgr, bgr, mask=mask)cv2.imshow("color detection", result)cv2.waitKey(0)cv2.destroyAllWindows()
转成 hsv 色域,来过滤掉相应的颜色
H 根据 x 轴取值,S 根据 y 轴取值,V 始终在 (20-255) 之间的范围内取值
bitwise_and,输出图像像素只有mask对应位置元素不为0的部分才输出,否则该位置像素的所有通道分量都设置为0
看看结果
输入图片
hsv
red-mask-1
red-mask-2
red-mask
green-mask-1
result