Embedded_game/002_B_Car/获取颜色阈值LAB.py
2025-02-25 18:51:58 +08:00

74 lines
2.2 KiB
Python

# -*- coding:utf-8 -*-
# @Author len
# @Create 2023/11/21 21:16
import cv2
import numpy as np
# 读取图像
image_path =r"E:\imgs\4.jpg"
image_bgr = cv2.imread(image_path)
# 全局变量
roi = []
drawing = False
def draw_rectangle(event, x, y, flags, param):
global roi, drawing, image_bgr_copy
if event == cv2.EVENT_LBUTTONDOWN:
roi = [(x, y)]
drawing = True
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
image_bgr_copy = image_bgr.copy()
cv2.rectangle(image_bgr_copy, roi[0], (x, y), (0, 0, 255), 2)
cv2.imshow('Select ROI', image_bgr_copy)
elif event == cv2.EVENT_LBUTTONUP:
roi.append((x, y))
drawing = False
cv2.rectangle(image_bgr, roi[0], roi[1], (0, 0, 255), 2)
cv2.imshow('Select ROI', image_bgr)
# 检查图像是否成功加载
if image_bgr is not None:
image_bgr_copy = image_bgr.copy()
cv2.imshow('Select ROI', image_bgr_copy)
cv2.setMouseCallback('Select ROI', draw_rectangle)
while True:
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cv2.destroyAllWindows()
if len(roi) == 2:
x1, y1 = roi[0]
x2, y2 = roi[1]
x, y, w, h = min(x1, x2), min(y1, y2), abs(x2 - x1), abs(y2 - y1)
# 转换到 LAB 颜色空间
image_lab = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2LAB)
cropped_lab = image_lab[y:y+h, x:x+w]
# 计算裁剪区域的 LAB 颜色阈值下界和上界
lower_red_threshold = np.min(cropped_lab.reshape(-1, 3), axis=0)
upper_red_threshold = np.max(cropped_lab.reshape(-1, 3), axis=0)
# 输出红色 LAB 颜色阈值
lower = lower_red_threshold.astype(int)
upper = upper_red_threshold.astype(int)
print('红色的 LAB 颜色阈值下界:', lower)
print('红色的 LAB 颜色阈值上界:', upper)
print("{}, {}, {}, {}, {}, {}".format(lower[0], upper[0], lower[1], upper[1], lower[2], upper[2]))
# 保存处理后的图像
cv2.imwrite("image_with_red_rectangle.jpg", image_bgr)
else:
print("未正确标注区域。")
else:
print("图像无法加载。")