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

如何访问图像中圆形ROI区域的内部及边缘像素?

圆形ROI像素提取解决方案

你之前考虑的圆方程(x - a)**2 + (y - b)**2 == r**2确实只能获取圆的边缘像素,要获取整个圆形区域内的所有像素,只需要将判断条件改为小于等于半径平方即可:(x - a)**2 + (y - b)**2 <= r**2。

你之前的实现只是将圆形绘制在可视化画布上,没有和图像像素矩阵做关联,所以无法直接提取对应像素,下面是两种可直接运行的实现方案:

方案1:Numpy掩码法(性能最优,适合圆形ROI场景)

直接基于坐标网格生成掩码,再通过掩码提取对应像素,代码示例:

import numpy as np
from matplotlib.pyplot import imread, imshow, show

# 读取图像和基础参数
img = imread('Model/m1.png') * 255
h, w = img.shape[:2]
center_x, center_y = 256, 256
radius = 150

# 生成坐标网格
y, x = np.ogrid[:h, :w]
# 计算每个点到圆心的距离平方,和半径平方比较避免开方运算
dist_from_center = (x - center_x)**2 + (y - center_y)**2
# 生成圆形区域掩码,ROI内为True,外为False
mask = dist_from_center <= radius **2

# 提取ROI内所有像素
roi_pixels = img[mask]
# 如果需要保留原图像尺寸,ROI外置0的话用下面的代码
# masked_img = np.where(mask, img, 0)

# 可视化验证
imshow(masked_img, cmap='gray')
show()
  • 如果你得到的ROI位置和你预期的圆形不匹配,只需要交换center_x和center_y的位置即可,这是因为部分场景下图像坐标的行/列和绘图坐标的x/y是反过来的。

方案2:Matplotlib路径判断法(扩展性强,适合后续替换为不规则ROI)

如果你后续需要处理的ROI不是标准圆形,可以用matplotlib自带的路径包含判断逻辑,适配任意你绘制的Patch形状:

import numpy as np
from matplotlib.pyplot import imread, subplots, imshow, show
from matplotlib.patches import Circle
from matplotlib.path import Path

img = imread('Model/m1.png') * 255
h, w = img.shape[:2]
center = (256, 256)
radius = 150

# 生成所有像素点的坐标列表
y, x = np.mgrid[:h, :w]
points = np.vstack((x.ravel(), y.ravel())).T

# 构建圆形路径
circle = Circle(center, radius)
path = circle.get_path()
# 做坐标变换匹配图像尺寸
transform = circle.get_patch_transform()
path = transform.transform_path(path)

# 生成掩码
mask = path.contains_points(points).reshape(h, w)

# 提取ROI像素
roi_pixels = img[mask]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:36:06