OpenCV: 改变颜色空间

	OpenCV中,对于颜色空间HSV,hue范围[0,179],saturation范围[0,255],value范围[0,255]
相对于BGR颜色空间而言,在HSV颜色空间中更容易呈现一种颜色,我们可以BGR转为HSV
后在HSV颜色空间中对图片做阈值以分离出特定颜色的目标对象.

OpenCV: 改变颜色空间_第1张图片
OpenCV: 改变颜色空间_第2张图片

H ∈ [0°, 360°], S ∈ [0, 1], V ∈ [0, 1], 色度(chroma) C = V x S, HSV -> RGB转换公式如下:

OpenCV: 改变颜色空间_第3张图片
为什么OpenCV使用BGR?请参考 https://learnopencv.com/why-does-opencv-use-bgr-color-format/

对于蓝色H = 240,那么H’ = 4,X = 0, 即R1,G1均为0,B1不为0
由于OpenCV中H∈[0, 179],即H = 120附近表示蓝色,以下代码可以从视频帧中分割出蓝色物体

import cv2 as cv
import numpy as np

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

你可能感兴趣的:(算法,opencv,计算机视觉,python)