颜色空间转换, 从bgr到hsv
hsv_image = cv.cvtColor(image, cv.COLOR_BGR2HSV)
用inRange函数提取指定颜色范围,其余置为(0)黑,这里对hsv来处理
mask = cv.inRange(hsv_image, lowerb=lower_hsv, upperb=upper_hsv)
import cv2 as cv
import numpy as np
# 颜色空间转换, 从bgr到gray, hsv, yuv, ycrcb
def color_space_convert(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)
# bgr 转 hsv
def bgr_convert_hsv():
print("请输入blue, green, red : ", end='')
blue, green, red = map(int, input().split())
color = np.array([[[blue, green, red]]], dtype=np.uint8)
hsv_color = cv.cvtColor(color, cv.COLOR_BGR2HSV)
hue = hsv_color[0][0][0]
print("Lower bound is :"),
print("[" + str(hue - 10) + ", 100, 100]\n")
print("Upper bound is :"),
print("[" + str(hue + 10) + ", 255, 255]")
# 从视频中提取指定颜色范围,并将其置为白,其余置为黑
def extract_object_demo():
capture = cv.VideoCapture("./images/3.mp4")
while True:
ret, frame = capture.read()
if not ret:
break
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
lower_hsv = np.array([37, 43, 46])
upper_hsv = np.array([77, 255, 255])
# 用inRange函数提取指定颜色范围,其余置为(0)黑,这里对hsv来处理
mask = cv.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
cv.imshow("video", frame)
cv.imshow("mask", mask)
c = cv.waitKey(40)
if c == 27:
break
# 对图片三个通道颜色提取并放在三张图片中
def channel_split_merge(image):
b, g, r = cv.split(image)
# print(b.shape) --> (1334, 750)
cv.imshow("blue", b)
cv.imshow("green", g)
cv.imshow("red", r)
changed_image = image.copy()
changed_image[:, :, 2] = 0 # 将r通道颜色全部置为0
cv.imshow("changed_image", changed_image)
merge_image = cv.merge([b, g, r])
cv.imshow("merge_image", merge_image)
if __name__ == "__main__":
image = cv.imread("./images/CrystalLiu1.jpg")
cv.namedWindow("image", cv.WINDOW_AUTOSIZE)
cv.imshow("image", image)
bgr_convert_hsv()
# channel_split_merge(image)
# color_space_convert(image)
# extract_object_demo()
cv.waitKey(0)
cv.destroyAllWindows()
channel_split_merge(image)
color_space_convert(image)
extract_object_demo()