什么是色彩空间
https://zhuanlan.zhihu.com/p/28741691(参考知乎专栏)
常见的色彩空间
- RGB
- HSV
- HIS
- YCrCb
- YUV
代码层面的知识点
色彩空间相互转换(RGB HSV YUV常用)
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)
学会使用inRange
应用:提取视频中特定颜色的物品(追踪有颜色的对象)
首先提取一段视频
def extract_object_demo(): capture = cv.VideoCapture("H:\coding\python_opencv_tutorial_codes\practice\lisa.mp4") while(True): ret, frame = capture.read() if ret == False: break cv.imshow("video", frame) c = cv.waitKey(50) if c == 27: break
hsv二值化(找黄颜色)
def extract_object_demo(): capture = cv.VideoCapture("H:\coding\python_opencv_tutorial_codes\practice\lisa.mp4") while(True): ret, frame = capture.read() if ret == False: break hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV) lower_hsv = np.array([26, 43, 46]) higer_hsv = np.array([34, 255, 255]) mask = cv.inRange(hsv, lower_hsv, higer_hsv)#得到二值图像 cv.imshow("video", frame) cv.imshow("mask", mask) c = cv.waitKey(50) if c == 27: break
通道的分离与合并
b, g, r = cv.split(src)#三通道分离 cv.imshow("blue", b) cv.imshow("green", g) cv.imshow("red", r) src[:,:,2] = 0 src = cv.merge([b, g, r])#三通道合并 cv.imshow("changed image", src)
本章内容完整代码
import cv2 as cv import numpy as np def extract_object_demo(): capture = cv.VideoCapture("H:\coding\python_opencv_tutorial_codes\practice\lisa.mp4") while(True): ret, frame = capture.read() if ret == False: break hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV) lower_hsv = np.array([26, 43, 46]) higer_hsv = np.array([34, 255, 255]) mask = cv.inRange(hsv, lower_hsv, higer_hsv)#得到二值图像 cv.imshow("video", frame) cv.imshow("mask", mask) c = cv.waitKey(50) if c == 27: break 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---------") src = cv.imread("H:\coding\python_opencv_tutorial_codes\practice\krystal.jpg") cv.namedWindow("input image", cv.WINDOW_AUTOSIZE) cv.imshow("input image", src) b, g, r = cv.split(src)#三通道分离 cv.imshow("blue", b) cv.imshow("green", g) cv.imshow("red", r) src[:,:,2] = 0 src = cv.merge([b, g, r])#三通道合并 cv.imshow("changed image", src) #print(type(src)) #color_space_demo(src) #extract_object_demo() cv.waitKey(0) cv.destroyAllWindows()