51 lines
1.6 KiB
Python
51 lines
1.6 KiB
Python
|
# -*- coding:utf-8 -*-
|
||
|
# @Author len
|
||
|
# @Create 2023/11/21 21:16
|
||
|
|
||
|
import cv2
|
||
|
import numpy as np
|
||
|
|
||
|
# 读取图像
|
||
|
image_path = 'xdl/1.png' # 请替换为您图像的实际路径
|
||
|
image_bgr = cv2.imread(image_path)
|
||
|
|
||
|
# 检查图像是否成功加载
|
||
|
if image_bgr is not None:
|
||
|
# 将图像从 BGR 颜色空间转换到 LAB 颜色空间
|
||
|
image_lab = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2LAB)
|
||
|
|
||
|
# 定义红框区域的坐标 (x, y, width, height)
|
||
|
# 请用实际的红框坐标替换
|
||
|
x, y, w, h = 280, 340, 60, 60 # 替换为红框的实际坐标
|
||
|
|
||
|
# 裁剪 LAB 图像以获取红框内的区域
|
||
|
cropped_lab = image_lab[y:y+h, x:x+w]
|
||
|
|
||
|
# 计算裁剪区域的平均 LAB 值
|
||
|
avg_lab = np.mean(cropped_lab.reshape(-1, 3), axis=0)
|
||
|
|
||
|
# 定义阈值范围
|
||
|
threshold_range = 10
|
||
|
lower_red_threshold = np.clip(avg_lab - threshold_range, 0, 255)
|
||
|
upper_red_threshold = np.clip(avg_lab + threshold_range, 0, 255)
|
||
|
|
||
|
# 输出红色 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.rectangle(image_bgr, (x, y), (x + w, y + h), (0, 0, 255), 2)
|
||
|
|
||
|
# 显示图像
|
||
|
cv2.imshow('Image with Red Rectangle', image_bgr)
|
||
|
cv2.waitKey(0)
|
||
|
cv2.destroyAllWindows()
|
||
|
|
||
|
# 保存处理后的图像
|
||
|
cv2.imwrite("image_with_red_rectangle.jpg", image_bgr)
|
||
|
else:
|
||
|
print("图像无法加载。")
|