1.颜色空间转换
import cv2
img = cv2.imread('1.jpg')
# 转换为灰度图
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('img', img)
cv2.imshow('gray', img_gray)
cv2.waitKey(0)
cv2.cvtColor()用来进行颜色模型转换,参数 1 是要转换的图片,参数 2 是转换模式
2.视频中特定颜色物体追踪
import cv2
import numpy as np
def detect_white(image_path):
# 读取图像
image = cv2.imread(image_path)
# 将图像从RGB转换为HSV
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 定义白色在HSV颜色空间的阈值范围
lower_white = np.array([114, 36, 234], dtype=np.uint8)
upper_white = np.array([177 , 10 ,251], dtype=np.uint8)
# 应用阈值,提取白色区域
white_mask = cv2.inRange(hsv_image, lower_white, upper_white)
# 对提取的二值图像进行形态学操作,去除噪音
kernel = np.ones((5, 5), np.uint8)
white_mask = cv2.morphologyEx(white_mask, cv2.MORPH_OPEN, kernel)
# 在原始图像上标记白色区域
result = cv2.bitwise_and(image, image, mask=white_mask)
# 显示结果图像
cv2.imshow("Result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 调用函数进行白色区域识别
detect_white("2.jpg")
3.那蓝色的 HSV 值的上下限 lower 和 upper 范围是怎么得到的呢?
import cv2
import numpy as np
# img是你的BGR图像
img = cv2.imread('1111.png')
# 将BGR图像转换为HSV图像
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 获取H, S, V的最小值和最大值
min_h, max_h = np.min(hsv_img[:,:,0]), np.max(hsv_img[:,:,0])
min_s, max_s = np.min(hsv_img[:,:,1]), np.max(hsv_img[:,:,1])
min_v, max_v = np.min(hsv_img[:,:,2]), np.max(hsv_img[:,:,2])
print(min_h, max_h)
print(min_s, max_s)
print(min_v, max_v)
或者:
import cv2
img = cv2.imread('2.jpg')
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
def mouse_click(event, x, y, flags, para):
if event == cv2.EVENT_LBUTTONDOWN: # 左边鼠标点击
print('PIX:', x, y)
# print("BGR:", img[y, x])
# print("GRAY:", gray[y, x])
print("HSV:", hsv[y, x])
if __name__ == '__main__':
cv2.namedWindow("img")
cv2.setMouseCallback("img", mouse_click)
while True:
cv2.imshow('img', img)
if cv2.waitKey() == ord('q'):
break