简体   繁体   English

从掩码坐标重建图像

[英]Reconstructing image from mask coordinates

I have a Boolean mask (ie mask1) in a Numpy array.我在 Numpy 阵列中有一个 Boolean 掩码(即 mask1)。 Its shape its as follows:它的形状如下:

在此处输入图像描述

Then, I have the following code to extract the x and y coordinates of all the pixels within that mask然后,我有以下代码来提取该掩码内所有像素的 x 和 y 坐标

xy_coords = np.flip(np.column_stack(np.where(mask1 > 0)), axis=1)#getting coordinates of pixels within the mask

For my application, I need to reconstruct a new image using these coordinates (so the new image has to have the shape of the mask).对于我的应用程序,我需要使用这些坐标重建新图像(因此新图像必须具有蒙版的形状)。 I thought that this could be done with a simple for loop as follows:我认为这可以通过一个简单的 for 循环来完成,如下所示:

for y in xy_coords[:,0]:
 for x in xy_coords[:,1]:
     new_image[x][y] = 1 #(or any other value)

However, the reconstructed new_image has a square shape and not the shape of the original mask.但是,重建后的 new_image 是方形的,而不是原始掩码的形状。

在此处输入图像描述

Can anyone see what I am doing wrong and help me on what should I do?谁能看到我做错了什么并帮助我该怎么做?

Thanks heaps!多谢!

Your mistake is using a double loop, which combines all X values to all Y values and creates non-existing points.您的错误是使用双循环,它将所有 X 值组合到所有 Y 值并创建不存在的点。

Eg from the two points (a, b) and (c, d), you would set (a, b), (c, b), (a, d), (c, d).例如,从 (a, b) 和 (c, d) 两点,您将设置 (a, b), (c, b), (a, d), (c, d)。

In addition, this is terribly slow: from N points you create N² of them.此外,这非常慢:从 N 个点创建 N² 个。

What you did wrong, that was explained in the other answer.你做错了什么,这在另一个答案中得到了解释。

What to do instead : work with a mask, not with a list of points该怎么做:使用蒙版,不是点列表

new_image[mask1 > 0] = 1

Or if you must work with a list of (x,y) points, then at least do this:或者,如果您必须使用 (x,y) 点列表,那么至少要这样做:

for (x,y) in xy_coords:
    new_image[y,x] = 1

Or even more succinctly:或者更简洁:

(i,j) = np.where(mask1 > 0)
new_image[i,j] = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM