代码
解释都在注释里啦
import cv2 as cv
import numpy as nm
#调用转换函数实现图像色彩空间转换
def colorSpace(img):
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # 将RGB转换为GRAY
cv.imshow("gray", gray)
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) # 将RGB转换为HSV
cv.imshow("hsv", hsv)
yuv = cv.cvtColor(img, cv.COLOR_BGR2YUV) # 将RGB转换为YUV
cv.imshow("yuv", yuv)
def testColorSpace():
src = cv.imread("me.jpg")
cv.namedWindow("Before", cv.WINDOW_NORMAL)
cv.imshow("Before", src)
colorSpace(src)
cv.waitKey(0)
cv.destroyAllWindows()
#色彩空间转换,利用inrange函数过滤视频中的颜色,实现跟踪某一颜色
def traceColor():
cap=cv.VideoCapture("you.mp4")
while True:
ret, frame = cap.read()
if ret==False:
print("Wrong")
break
else:
hsv=cv.cvtColor(frame,cv.COLOR_BGR2HSV)
# 转换色彩空间为hsv
hsvLow = nm.array([26, 43, 26])
# 设置过滤的颜色的低值
hsvHigh = nm.array([34, 255, 255])
# 设置过滤的颜色的高值
change = cv.inRange(hsv, hsvLow, hsvHigh)
# 节图像颜色信息(H)、饱和度(S)、亮度(V)区间
cv.imshow("Before",frame)
cv.imshow("After",change)
if cv.waitKey(50) & 0xFF==ord("r"):
cv.destroyAllWindows()
break
#通道分离、合并,修改某一通道
def operate(img):
#通道分离
b,g,r=cv.split(img)
cv.imshow("blue",b)
cv.imshow("green",g)
cv.imshow("red",r)
#通道合并
gather=cv.merge([b,g,r])
cv.imshow("merge",gather)
#修改通道值
img[:,:,1]=100
cv.imshow("single",img)
def testOperate():
src = cv.imread("me.jpg")
cv.namedWindow("Before", cv.WINDOW_NORMAL)
cv.imshow("Before", src)
operate(src)
cv.waitKey(0)
cv.destroyAllWindows()
testColorSpace()
testOperate()