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

发布于:2025-02-10 ⋅ 阅读:(138) ⋅ 点赞:(0)

示例代码:

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')

 效果展示:


网站公告

今日签到

点亮在社区的每一天
去签到