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

示例代码:

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

效果展示:

相关推荐
BK贝壳8 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
BD_Marathon12 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw12 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn13 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern0915 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_9679801116 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
databook18 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer19 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
2601_967980111 天前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
AI创界者1 天前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc