Home > Back-end >  Reconstructing image from mask coordinates
Reconstructing image from mask coordinates

Time:07-29

I have a Boolean mask (i.e. mask1) in a Numpy array. Its shape its as follows:

enter image description here

Then, I have the following code to extract the x and y coordinates of all the pixels within that mask

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 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.

enter image description here

Can anyone see what I am doing wrong?

Thanks heaps!

CodePudding user response:

Your mistake is using a double loop, which combines all X values to all Y values and creates non-existing points.

E.g. from the two points (a, b) and (c, d), you would set (a, b), (c, b), (a, d), (c, d).

In addition, this is terribly slow: from N points you create N² of them.

CodePudding user response:

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:

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
  • Related