
import cv2
import numpy as np
def get_max_brightness_hsv(image_path):
"""使用HSV色彩空间的V通道获取最大亮度"""
try:
# 读取图片
image = cv2.imread(image_path)
if image is None:
print(f"无法读取图片: {image_path}")
return None
# 转换为HSV色彩空间
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 提取V通道(亮度通道)并找到最大值
v_channel = hsv_image[:, :, 2]
max_brightness = np.max(v_channel)
return max_brightness
except Exception as e:
print(f"HSV方法处理出错: {str(e)}")
return None
def get_max_brightness_rgb(image_path):
"""使用RGB转亮度公式计算最大亮度 (L = 0.299*R + 0.587*G + 0.114*B)"""
try:
# 读取图片(OpenCV默认读取为BGR格式)
image = cv2.imread(image_path)
if image is None:
print(f"无法读取图片: {image_path}")
return None
# 将BGR转换为RGB
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 分离R、G、B通道并转换为float类型
r_channel = rgb_image[:, :, 0].astype(np.float32)
g_channel = rgb_image[:, :, 1].astype(np.float32)
b_channel = rgb_image[:, :, 2].astype(np.float32)
# 应用亮度公式计算
luminance = 0.299 * r_channel + 0.587 * g_channel + 0.114 * b_channel
# 找到最大亮度值并转换为整数
max_brightness = np.max(luminance).astype(np.uint8)
return max_brightness
except Exception as e:
print(f"RGB公式法处理出错: {str(e)}")
return None
def compare_brightness_methods(image_path):
"""比较两种方法计算的最大亮度值"""
hsv_brightness = get_max_brightness_hsv(image_path)
rgb_brightness = get_max_brightness_rgb(image_path)
print("\n图片最大亮度计算结果:")
if hsv_brightness is not None:
print(f"HSV V通道法: {hsv_brightness} (范围0-255)")
if rgb_brightness is not None:
print(f"RGB公式法 (ITU-R BT.601): {rgb_brightness} (范围0-255)")
# 计算两种方法的差异
if hsv_brightness is not None and rgb_brightness is not None:
diff = abs(hsv_brightness - rgb_brightness)
print(f"两种方法结果差异: {diff}")
if __name__ == "__main__":
# 替换为你的图片路径
image_path = "2.png"
# 执行对比计算
compare_brightness_methods(image_path)