You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python去除图像渐变?获取单一颜色黄色圆形

去除图像渐变,生成单一黄色圆形的解决方案

你用K-means没得到预期结果,大概率是因为全局聚类把背景色也包含进去了,没法精准锁定圆形区域的黄色。试试下面的方法,用OpenCV就能实现:

  • 先定位黄色圆形区域
    优先用霍夫圆检测锁定圆形的位置和半径,这样能精准只处理目标区域:

    import cv2
    import numpy as np
    
    # 读取图像
    img = cv2.imread("你的图片路径.png")
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 霍夫圆检测(参数可根据实际图像微调)
    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
    
    if circles is not None:
        circles = np.uint16(np.around(circles))
        # 取检测到的第一个圆形(如果只有一个的话)
        circle = circles[0, 0]
        center = (circle[0], circle[1])
        radius = circle[2]
    
  • 提取圆形内的主黄色
    做一个圆形掩码,只提取圆形区域的像素,再计算这个区域的平均颜色——这比全局K-means精准得多:

    # 创建圆形掩码
    mask = np.zeros(img.shape[:2], np.uint8)
    cv2.circle(mask, center, radius, 255, -1)
    # 提取圆形内的所有像素
    circle_pixels = img[mask == 255]
    # 计算区域内的平均黄色,作为填充色
    target_yellow = np.mean(circle_pixels, axis=0).astype(np.uint8)
    
  • 填充为单一黄色
    用计算好的黄色替换圆形内的所有像素:

    img[mask == 255] = target_yellow
    # 保存处理后的图像
    cv2.imwrite("单一黄色圆形.png", img)
    
  • 备选方案:颜色阈值法
    如果霍夫圆检测效果不好,直接用HSV颜色阈值提取黄色区域,再处理:

    hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # 黄色的HSV范围(可根据你的图像调整上下限)
    lower_yellow = np.array([20, 100, 100])
    upper_yellow = np.array([30, 255, 255])
    # 提取黄色掩码
    yellow_mask = cv2.inRange(hsv_img, lower_yellow, upper_yellow)
    # 形态学闭运算,消除掩码上的小缝隙
    kernel = np.ones((5,5), np.uint8)
    yellow_mask = cv2.morphologyEx(yellow_mask, cv2.MORPH_CLOSE, kernel)
    # 计算掩码内的平均黄色并填充
    target_yellow = np.mean(img[yellow_mask == 255], axis=0).astype(np.uint8)
    img[yellow_mask == 255] = target_yellow
    cv2.imwrite("结果图.png", img)
    

核心思路就是只针对圆形区域做颜色提取,而不是全局处理,这样就能避免K-means把背景色混进来的问题。

内容的提问来源于stack exchange,提问作者정성헌

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:45:27