opencv有超150种颜色空间转换,在这里我们主要介绍2种经常用到的颜色空间转换(RGB->GRAY, RGB->HSV)。
HVS色相取值范围[0, 179],亮度取值范围[0, 255],饱和度取值范围[0, 255],不同的软件取值范围可能不一样。
查询opencv支持哪些颜色转换类型,可以使用以下方法。
import cv2 as cv
flags = [i for i in dir(cv) if i.startswith('COLOR_')]
print( flags )
以下为转换代码:
import numpy as np
import cv2 as cv
img = cv.imread('./img/frame.jpg')
gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
cv.imshow('img', img)
cv.imshow('gray', gray)
cv.waitKey(0)
cv.destroyAllWindows()
以下为通过RGB转HSV实现简单目标追踪(通过颜色来追踪)代码示例:
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()
查找RGB对应的HSV值,以下是代码示例:
import numpy as np
import cv2 as cv
green = np.uint8([[[0,255,0 ]]])
hsv_green = cv.cvtColor(green,cv.COLOR_BGR2HSV)
print( hsv_green )