opencv 颜色检测

来源:互联网 发布:新日铁软件 编辑:程序博客网 时间:2024/06/05 01:59

参考:
https://stackoverflow.com/questions/20912948/color-detection-using-opencv-python


1、检测蓝色

import cv2import numpy as npcap = cv2.VideoCapture("vtest.avi")while(1):    # Take each frame    _, frame = cap.read()    # Convert BGR to HSV    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)    # define range of blue color in HSV    lower_blue = np.array([110,50,50],np.uint8)    upper_blue = np.array([130,255,255],np.uint8)    # Threshold the HSV image to get only blue colors    mask = cv2.inRange(hsv, lower_blue, upper_blue)    # Bitwise-AND mask and original image    res = cv2.bitwise_and(frame,frame, mask= mask)    cv2.imshow('frame',frame)    cv2.imshow('mask',mask)    cv2.imshow('res',res)    k = cv2.waitKey(5) & 0xFF    if k == 27:        breakcv2.destroyAllWindows()

2、检测红色

import cv2import numpy as npcap = cv2.VideoCapture("vtest.avi")while(1):    # Take each frame    _, frame = cap.read()    # Convert BGR to HSV    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)    # define range of blue color in HSV    lower_red = np.array([170, 70, 50], np.uint8)    upper_red = np.array([180, 255, 255], np.uint8)    # lower_red=cv2.cvtColor(np.array([[lower_red]]),cv2.COLOR_HSV2BGR)    # upper_red = cv2.cvtColor(np.array([[upper_red]]), cv2.COLOR_HSV2BGR)    # Threshold the HSV image to get only red colors    mask = cv2.inRange(hsv, lower_red, upper_red)    # Bitwise-AND mask and original image    res = cv2.bitwise_and(frame,frame, mask= mask)    cv2.imshow('frame',frame)    cv2.imshow('mask',mask)    cv2.imshow('res',res)    k = cv2.waitKey(5) & 0xFF    if k == 27:        breakcv2.destroyAllWindows()
原创粉丝点击