当前位置: 首页 > article >正文

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

 效果展示:


http://www.kler.cn/a/504556.html

相关文章:

  • JS-Web API-day02
  • sql报错非法的字符校对Illegal mix of collations
  • Vue2+OpenLayers点聚合功能实现(提供Gitee源码)
  • FPGA 21 ,深入理解 Verilog 中的基数,以及二进制数与十进制数之间的关系( Verilog中的基数 )
  • 【Pandas】pandas Series rsub
  • 【python】OpenCV—Local Translation Warps
  • 国内源快速在线安装qt5.15以上版本。(10min安装好)(图文教程)
  • 【大数据】机器学习-----线性模型
  • 训练一只AI:深度学习在自然语言处理中的应用
  • RuoYi-Vue-Plus 加入 GitCode:驱动多租户后台管理创新发展
  • 58_Redis性能测试
  • OpenAI Whisper:语音识别技术的革新者—深入架构与参数
  • Linux是个什么玩意
  • OmniAudio-2.6B 简介与音频转文本实践
  • PHP民宿酒店预订系统小程序源码
  • 查看nginx已安装的模块
  • Python使用socket实现简易的http服务
  • C++复习
  • 17_Redis管道技术
  • 如何保证光谱相机的稳定性和可靠性