问题描述
def get_area(center_x: int,center_y: int,mask: np.ndarray) -> int:
if mask[center_x][center_y] != 255:
return -1
return ...
现在我得到了上面的这个函数,它接收 x 和 y 的值,并找到与该像素相连的像素数,值为 255。
现在让我们说,我有一个简单的 np.ndarray,如下所示:
[
[255,255,255],[255,[ 0,0],255]
]
如果我将 255 的中心像素作为输入,我尝试构建的函数的输出将是 5,因为有 4 个相邻像素是 255。
我可以同时使用 opencv
和 numpy
,但更可取的是 np
。
解决方法
from PIL import Image
import numpy as np
from scipy import ndimage
imgMtx = [
[255,255,255],[255,[ 0,0],255]
]
img = Image.fromarray(np.asarray(imgMtx))
blobs = np.asarray(img) > 125
labels,nlabels = ndimage.label(blobs)
unique,counts = np.unique(labels,return_counts=True)
,
import numpy as np
def get_area(center_x: int,center_y: int,mask: np.ndarray) -> int:
"""
Basic flood-fill area calculation on the mask using Breadth First Search
"""
area = 0
moves = [(1,1),(0,(1,0),(-1,-1),-1)]
if mask[center_x][center_y] != 255:
return -1
visited = [[False for _ in range(mask.shape[0])] for _ in range(mask.shape[1])]
q = deque()
q.append((center_x,center_y))
visited[center_x][center_y] = True
while q:
x,y = q.popleft()
for move in moves:
if (x + move[0] >= mask.shape[0] or y + move[1] >= mask.shape[1] or
x + move[0] < 0 or y + move[1] < 0):
continue
if mask[x + move[0]][y + move[1]] == 255 and not visited[x + move[0]][y + move[1]]:
area += 1
q.append((x + move[0],y + move[1]))
visited[x + move[0]][y + move[1]] = True
return area
决定自己编写一个答案,并对提供的掩码进行广度优先搜索洪水填充算法。