Marking a rectangular region in a NumPy array as an image mask 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&lt; x &lt; x2 and y1 &lt; y &lt; 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 &lt;= clusterH + 2 * S and x &gt;= clusterH - 2*S and y &lt;= clusterW + 2*S and y &gt;= clusterW - 2*S:
            clusterMask[x][y] = 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