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
  • \$\begingroup\$ 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 \$\endgroup\$
    – Htnamus
    Commented Nov 1, 2018 at 8:23
  • 4
    \$\begingroup\$ 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. \$\endgroup\$
    – maxb
    Commented Nov 1, 2018 at 8:25
  • \$\begingroup\$ The NumPy indexing documentation is a good place to start. \$\endgroup\$ Commented Nov 1, 2018 at 11:15
  • \$\begingroup\$ 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. \$\endgroup\$
    – Zeta
    Commented Nov 2, 2018 at 10:58

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\$ Commented Nov 2, 2018 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.