首页 > 解决方案 > 如何计算给定二维数组上的轮廓(内部值,外部 0)像素?

问题描述

我有以下任务要解决。我有一个图像(numpy 数组),其中不是主要对象的所有内容都是 0,并且主要对象周围都有一些像素数(让我们将它们全部设置为 1)。

我只想数红色方块

我需要的是获取该对象的轮廓上所有像素的数量(以 1 为值的红色方块)。对象可以有不同的形式。有没有办法实现它?

OBS:目标是有一种能够适应图形形状的方法,因为它可以同时在多个图像上运行。

标签: pythonnumpymultidimensional-array

解决方案


这很有趣,我为您提供了一个优雅的解决方案。

由于我们同意轮廓被定义为大于np.array并且0至少有 1 个值为0数组,当然...)

import numpy as np 

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


def get_contour(two_d_arr):
    contour_pxs = 0
    # Iterate of np:
    for i, row in enumerate(two_d_arr):
        for j, pixel in enumerate(row):
            # Check neighbors
            up = two_d_arr[i-1][j] == 0 if i > 0 else True
            down = two_d_arr[i+1][j] == 0 if i < len(image_pxs)-1 else True
            left = two_d_arr[i][j-1] == 0 if j > 0 else True
            right = two_d_arr[i][j+1] == 0 if j < len(row)-1 else True
            # Count distinct neighbors (empty / not empty)
            sub_contour = len(list(set([up, down, left, right])))
            # If at least 1 neighbor is empty and current value > 0 it is the contour
            if sub_contour > 1 and pixel > 0:
                # Add the number of pixels in i, j
                contour_pxs += pixel
    return contour_pxs
            
print(get_contour(image_pxs))

输出当然是8:

8
[Finished in 97ms]

推荐阅读