如何最好地遍历蒙版2D阵列

时间:2018-10-22 16:05:01

标签: python arrays 2d mask

这里的主要目标是图像处理:检测给定jpg图像中的边缘和颜色。

我根据这篇文章的最高答案做了一个蒙版的2D数组: https://stackoverflow.com/a/38194016/9700646

所以我有以下内容,应该将2D数组中的所有0都屏蔽掉:

color_matrix[~np.array(0)]

我不确定该如何循环。有人有主意吗?

最终,我需要通过遍历两个2D蒙版数组来开发第三个矩阵。

这里有一些代码可以让您了解我到目前为止的情况:

这是我制作“ edge_matrix”的第一步。最后我也要掩盖它。 “ color_matrix”是通过类似的过程制成的。

def edge_matrix(canny_pic):
#edge_matrix = [[0 for x in range(RESOLUTION_WIDTH)] for y in range(RESOLUTION_HEIGHT)]
edge_matrix = np.zeros((RESOLUTION_HEIGHT,RESOLUTION_WIDTH,1),dtype  = "uint8")
# get Canny pic
img = canny_pic #the first element of canny_pic is the picture, the others are the upper and lowers

# make matrix of edges
for i in range(RESOLUTION_HEIGHT):
    for j in range(RESOLUTION_WIDTH):
        #print(i,j)
        color = img[i,j]
        edge_matrix[i,j]=(color[0] or color[1] or color[2] ) and 1

return edge_matrix

然后,我想通过边缘矩阵对这些矩阵进行组合,然后说:每当有边缘(a 1)时,请检查color_matrix中该像素周围的10个空间,看看是否检测到颜色。如果是这样,请在Combined_matrix中将其标记为1。

def reduce_problem(color_mat, edge_mat): 
#this function will help reduce the number of location the object may be in by combining the colors and edges
#create a matrix to store the possible locations of the correct object.

#combined_matrix = [[0 for x in range(RESOLUTION_WIDTH)] for y in range(RESOLUTION_HEIGHT)] #same size as image. 1 = a spot with both edge and color; 0 = a spot without both 
combined_matrix = np.zeros((RESOLUTION_HEIGHT,RESOLUTION_WIDTH, 1), dtype = "float32")

for i in range(10,RESOLUTION_HEIGHT-11): #loop through color matrix
    for j in range(10,RESOLUTION_WIDTH-11):
        if  edge_mat[i,j] == 1:
            #if this edge matrix location has an edge(1), go to the color matrix and check the 10 spaces surrounding it in each direction for any color(1) value (in respect to the corresponding space)

            for k in range(i-10, i+10):
                #if k >= 0 and k < RESOLUTION_HEIGHT:
                for m in range(j-10, j+10):
                    #if m >= 0 and m < RESOLUTION_WIDTH:
                    if color_mat[k,m] ==1:
                        #print(k, m)
                        combined_matrix[i,j] += 1/441

这用于检测颜色和边缘。但这非常慢,并且对于实时检测对象太慢了。我希望使用掩码数组进行迭代将有助于加快该过程。

0 个答案:

没有答案