HSV RGB计算图片亮度

HSV与RGB转换计算亮度

在这里插入图片描述

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)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值