python识别图片中指定颜色的图案并保存为图片

示例代码:

def chuli(color):
    import cv2
    import numpy as np

    # 定义颜色名称到HSV阈值范围的映射
    color_thresholds = {
        'red': ([0, 100, 100], [10, 255, 255], [160, 100, 100], [180, 255, 255]),
        'yellow': ([20, 100, 100], [30, 255, 255]),
        'blue': ([90, 100, 100], [130, 255, 255])
    }

    # 读取图片
    image = cv2.imread('captcha.png')

    # 将图片从BGR转换到HSV颜色空间
    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    # 获取用户输入的颜色名称
    color_name = color.lower()

    # 检查颜色名称是否在映射中
    if color_name in color_thresholds:
        # 获取该颜色的HSV阈值范围
        thresholds = color_thresholds[color_name]

        # 创建掩码
        mask = None
        for i in range(0, len(thresholds), 2):
            lower = np.array(thresholds[i])
            upper = np.array(thresholds[i + 1])
            mask_color = cv2.inRange(hsv_image, lower, upper)
            if mask is None:
                mask = mask_color
            else:
                mask = cv2.bitwise_or(mask, mask_color)

        # 对掩码进行膨胀和腐蚀
        mask = cv2.dilate(mask, None, iterations=2)
        mask = cv2.erode(mask, None, iterations=2)

        # 使用掩码提取原图中的颜色区域
        result = cv2.bitwise_and(image, image, mask=mask)

        # 保存结果为图片
        result_filename = 'detected.png'
        cv2.imwrite(result_filename, result)
        print(f"Result saved as {result_filename}")
    else:
        print("Invalid color name. Please choose from 'red', 'yellow', or 'blue'.")


chuli('blue')

 效果展示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

某公司摸鱼前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值