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

寻求图像单颜色连续区域坐标提取算法实现方案

图像同色连续区域坐标提取的现成实现方案

你要的功能完全可以用成熟的计算机视觉库实现,不用从零编写连通区域分析算法,下面是两种常用的可行方案:

方案一:使用OpenCV(适合处理复杂图像/需要更多视觉功能的场景)

OpenCV内置了连通区域分析的函数,能高效识别图像中同色的连续区域并提取坐标:

import cv2
import numpy as np

def get_contiguous_color_coords(image_path, target_color):
    # 读取图像并转换为RGB格式(OpenCV默认读取为BGR)
    img = cv2.imread(image_path)
    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    # 创建掩码:将匹配目标颜色的像素标记为255,其余为0
    mask = np.all(img_rgb == target_color, axis=-1).astype(np.uint8) * 255
    
    # 提取连通区域(connectivity=8表示8邻域连通,可改为4使用4邻域)
    num_labels, labels, _, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
    
    coords_list = []
    # 跳过背景标签(标签0),遍历每个连通区域
    for label in range(1, num_labels):
        # 获取当前区域所有像素的坐标
        y_coords, x_coords = np.where(labels == label)
        # 转换为(x,y)格式的坐标对列表
        region_coords = list(zip(x_coords, y_coords))
        coords_list.append(region_coords)
    
    return coords_list

# 使用示例
if __name__ == "__main__":
    target_red = (255, 0, 0)  # 目标颜色:RGB格式的红色
    all_regions = get_contiguous_color_coords("test.png", target_red)
    # 输出每个区域的像素数量
    for idx, region in enumerate(all_regions):
        print(f"第{idx+1}个连续区域包含{len(region)}个像素")

方案二:使用Pillow + SciPy(轻量依赖,适合简单场景)

如果只需要基础的连通区域提取,可以用Pillow处理图像,结合SciPy的label函数实现:

from PIL import Image
import numpy as np
from scipy.ndimage import label

def get_contiguous_color_coords_pillow(image_path, target_color):
    # 读取图像并转为RGB格式
    img = Image.open(image_path).convert("RGB")
    img_array = np.array(img)
    
    # 创建匹配目标颜色的布尔掩码
    mask = np.all(img_array == target_color, axis=-1)
    
    # 标记所有连通区域
    labeled_regions, num_regions = label(mask)
    
    coords_list = []
    for region_id in range(1, num_regions + 1):
        # 获取当前区域的所有像素坐标
        y_coords, x_coords = np.where(labeled_regions == region_id)
        region_coords = list(zip(x_coords, y_coords))
        coords_list.append(region_coords)
    
    return coords_list

# 使用示例
if __name__ == "__main__":
    target_green = (0, 255, 0)  # 目标颜色:RGB格式的绿色
    all_regions = get_contiguous_color_coords_pillow("test.png", target_green)
    for idx, region in enumerate(all_regions):
        print(f"第{idx+1}个连续区域包含{len(region)}个像素")

注意事项

  • 目标颜色需使用RGB格式(比如红色是(255,0,0)),如果图像有透明度通道(RGBA),需要调整掩码的判断逻辑,加入alpha通道的匹配
  • connectivity参数(仅OpenCV方案):设为4表示只识别上下左右相邻的像素为连续,设为8则包含对角线相邻的像素,可根据需求调整
  • 坐标格式:上述代码返回的是(x,y),对应图像的列和行,若需要(y,x)格式,直接调换x_coords和y_coords的顺序即可

内容的提问来源于stack exchange,提问作者polarka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 21:37:24