I'm currently working on creating a mask for an image. I have initialized a two-dimensional numpy zeros array. I now want to replace the values of the mask corresponding to pixels following some conditions such as x1< x < x2 and y1 < y < y2 (where x and y are the coordinates of the pixels) to 1.
Is there an easier way to do it (maybe through slicing) without looping through the mask like below
clusterMask = np.zeros((h, w))
for x in range(h):
for y in range(w):
if x <= clusterH + 2 * S and x >= clusterH - 2*S and y <= clusterW + 2*S and y >= clusterW - 2*S:
clusterMask[x][y] = 1
1 Answer 1
It turns out that Numpy has various nifty ways of indexing. I found that my question can be solved by
clusterMask[clusterH - 2*S : clusterH + 2*S, clusterW - 2*S : clusterW + 2*S] = 1
As given in one of the comments, this link contains all information regarding numpy indexing: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
-
\$\begingroup\$ This does the opposite of your original code: it marks the interior of the rectangular region, rather than the exterior. Also, be careful with the upper bounds: Python uses inclusive-exclusive ranges. \$\endgroup\$200_success– 200_success2018年11月02日 19:44:39 +00:00Commented Nov 2, 2018 at 19:44
clusterMask[clusterH - 2*S:clusterH + 2*S, clusterW - 2*S : clusterW + 2*S] = 1
\$\endgroup\$