pyhton3 + opencv
HSV色彩空间特定颜色提取 inRange函数使用实例
代码如下:
import cv2 as cv
import numpy as np
def extrace_object_demo():
capture = cv.VideoCapture(0)
while(True):
ret, frame = capture.read()
if ret == False:
break;
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
lower_hsv = np.array([35, 43, 46])
upper_hsv = np.array([77, 255, 255])
mask = cv.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
dst = cv.bitwise_and(frame, frame, mask=mask)
cv.imshow("video", frame)
cv.imshow("mask", dst)
c = cv.waitKey(40)
if c == 27:
break
def extrace_object_demo2():
src = cv.imread("E:/opencv/sources/samples/data/opencv-logo.png")
hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV)
lower_hsv = np.array([35, 43, 46])
upper_hsv = np.array([77, 255, 255])
mask = cv.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
dst = cv.bitwise_and(src, src, mask=mask)
cv.imshow("video", src)
cv.imshow("mask", dst)
cv.waitKey(40)
def color_space_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("gray", gray)
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
cv.imshow("hsv", hsv)
yuv = cv.cvtColor(image, cv.COLOR_BGR2YUV)
cv.imshow("yuv", yuv)
Ycrcb = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)
cv.imshow("ycrcb", Ycrcb)
print("--------- Hello Python ---------")
extrace_object_demo2()
cv.waitKey(0)
cv.destroyAllWindows()
extrace_object_demo()函数是基于摄像头绿色实时提取
extrace_object_demo2()是基于图片绿色提取
执行extrace_object_demo()如图:
可以根据第一张图表格内容提取特定颜色
只需修改lower_hsv与upper_hsv的值就可以
lower_hsv = np.array([35, 43, 46])
upper_hsv = np.array([77, 255, 255])
通过这个技巧的学习,我们在以后应用中会方便很多
本试验应用图片源于OpenCV自带的地址如下:
opencv/sources/samples/data/opencv-logo.png
注:尽量背景位白色进行试验,效果会更好