Skip to main content
 首页 » 编程设计

Python:二进制二维数组中的轮廓

2025年02月15日14powertoolsteam

我想以最简单的方式(无需对图像边界进行百万次检查)从二进制二维数组中获取轮廓,其中 n 个像素的宽度进入正区域。

例子:

img = np.array([ 
               [0, 0, 0, 1, 1, 1, 1, 1, 0], 
               [0, 1, 1, 1, 1, 1, 1, 1, 1], 
               [0, 1, 1, 1, 0, 0, 0, 0, 0], 
               ]) 

用于调用例如宽度 = 1。如果 img[i,j]==1 和任何邻居 (img[i+1,j], img[i-1,j], img[i,j-1], img[ i,j+1]) 为 0.

contour1 = get_countor(img, width = 1) 
contour1 = ([ 
               [0, 0, 0, 1, 0, 0, 0, 1, 0], 
               [0, 1, 1, 0, 1, 1, 1, 1, 1], 
               [0, 1, 0, 1, 0, 0, 0, 0, 0], 
            ]) 

或调用例如width = 2。所有从 width = 1 开始的像素都是正的,以及那些满足 img[i, j] == 1 并且距离 2 个索引(欧几里德距离)的像素存在一个值为 0 的像素。

contour2 = get_countor(img, width = 2) 
contour2 = ([ 
               [0, 0, 0, 1, 1, 1, 1, 1, 0], 
               [0, 1, 1, 1, 1, 1, 1, 1, 1], 
               [0, 1, 1, 1, 0, 0, 0, 0, 0], 
            ])  

感谢您的帮助。

请您参考如下方法:

不是这个问题的确切答案,而是分享一种在图像中绘制轮廓的简单方法;对于那些正在寻找的人。

from PIL import Image 
from PIL import ImageFilter 
import numpy as np 
 
 
def draw_contour(img, mask, contour_width, contour_color): 
    """Draw contour on a pillow image from a numpy 2D mask.""" 
    contour = Image.fromarray(mask) 
    contour = contour.resize(img.size) 
    contour = contour.filter(ImageFilter.FIND_EDGES) 
    contour = np.array(contour) 
 
    # make sure borders are not drawn 
    contour[[0, -1], :] = 0 
    contour[:, [0, -1]] = 0 
 
    # use a gaussian to define the contour width 
    radius = contour_width / 10 
    contour = Image.fromarray(contour) 
    contour = contour.filter(ImageFilter.GaussianBlur(radius=radius)) 
    contour = np.array(contour) > 0 
    contour = np.dstack((contour, contour, contour)) 
 
    # color the contour 
    ret = np.array(img) * np.invert(contour) 
    if contour_color != 'black': 
        color = Image.new(img.mode, img.size, contour_color) 
        ret += np.array(color) * contour 
 
    return Image.fromarray(ret) 

检查此测试输出:

我在为此 PR 工作时编写了这个解决方案.