python - 如何计算给定二维数组上的轮廓(内部值,外部 0)像素?
问题描述
我有以下任务要解决。我有一个图像(numpy 数组),其中不是主要对象的所有内容都是 0,并且主要对象周围都有一些像素数(让我们将它们全部设置为 1)。
我需要的是获取该对象的轮廓上所有像素的数量(以 1 为值的红色方块)。对象可以有不同的形式。有没有办法实现它?
OBS:目标是有一种能够适应图形形状的方法,因为它可以同时在多个图像上运行。
解决方案
这很有趣,我为您提供了一个优雅的解决方案。
由于我们同意轮廓被定义为大于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]
推荐阅读
- php - 如何使用正则表达式处理长文本?
- python - 通过python获取分割wav音频文件中的频率值(hz)
- c++ - 如何正确使用 intptr 将 char* 值从 c++ DLL 返回到 Vb.net
- windows - 从 Ubuntu VM 访问主机 url
- bash - 无法遍历存储在变量中的路径中的目录
- javascript - React 中的普通 ES6 类
- google-bigquery - 从 bigquery 数组中获取所有长度为 3 的窗口
- elixir - Edeliver Phoenix 发布失败
- scala - Scala 类型等价性检查单例类型
- javascript - 在页面加载时获取图像