# 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< 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:

• Just got the solution. It turns out you can change values in Numpy using slicing. All I had to do was: clusterMask[clusterH - 2*S:clusterH + 2*S, clusterW - 2*S : clusterW + 2*S] = 1 Commented Nov 1, 2018 at 8:23
• If you've come up with a solution, it can be helpful to other that you write an answer to your own question detailing your solution. Also, slicing is definitely the way to go when using numpy.
– maxb
Commented Nov 1, 2018 at 8:25
• The NumPy indexing documentation is a good place to start. Commented Nov 1, 2018 at 11:15
• Welcome to Code Review. The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
– Zeta
Commented Nov 2, 2018 at 10:58

clusterMask[clusterH - 2*S : clusterH + 2*S, clusterW - 2*S : clusterW + 2*S] = 1