Opencv+Python HSV色彩空间

HSV

Opencv+Python HSV色彩空间_第1张图片  Opencv+Python HSV色彩空间_第2张图片

cv2.inRange(src, lowerb, upperb, dst)函数

import cv2
import numpy as np

cameraCapture = cv2.VideoCapture(0)

# ------------------------获取鼠标指令------------------------
clicked = False
def onMouse(event, x, y, flags, param):
    global clicked
    if event == cv2.EVENT_LBUTTONUP:
        clicked = True
cv2.namedWindow("MyWindow")  # 可以省略
cv2.setMouseCallback("MyWindow", onMouse)
# cv2.setMouseCallback()是等待获取鼠标输入
# cv2.waitKey()是等待获取键盘输入,单位毫秒,返回值为:-1(没有键盘按下)、ASCII码(键盘按下)

print("Showing camera feed. Click window or press any key to stop")

success, frame = cameraCapture.read()
frame = cv2.flip(frame, 1)  # 左右镜像,上下镜像(1和-1)

while success and cv2.waitKey(1) == -1 and not clicked:
# success==True可以读帧,延迟1ms若键盘无指令则继续下一帧操作,鼠标无指令

    cv2.imshow("MyWindow", frame)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)  # 将读取的BGR转换为HSV
    lower = np.array([35, 43, 46])  # 所要检测的像素范围
    upper = np.array([77, 255, 255])  # 此处检测绿色区域
    mask = cv2.inRange(hsv, lowerb=lower, upperb=upper)
    cv2.imshow("mask", mask)
    success, frame = cameraCapture.read()
    frame = cv2.flip(frame, 1)

cv2.destroyAllWindows()
cameraCapture.release()

检测示例:

Opencv+Python HSV色彩空间_第3张图片

你可能感兴趣的:(Opencv+Python)