Home > Software design >  Python - partially cover up image
Python - partially cover up image

Time:06-16

I need to black out part of the image. to do so I tried this code:

img2[0:0, 640:150] = [0, 0, 0]
img2[0:490, 640:640] = [0, 0, 0]

but it does not seem to be working. The image is a numpy array.

So my questions are:

  1. why does my image img2 look the same before and after the execution of these rows?
  2. I need to black out everything except a rectangle. i wanted to do so by drawing 4 rectangles on the outside. can this also be done by saying one time what I do NOT want to blacken? so basically the inverse of the range?

CodePudding user response:

I think, You need to know about slicing (link_1, link_2). If you select correct slicing only one assignment with 0 is enough.

>>> img_arr = np.random.rand(5,3,3)
>>> img_arr[1:3, 0:2, 0:3] = 0
# Or
>>> img_arr[1:3, :2, :] = 0
>>> img_arr
array([[[0.19946098, 0.42062458, 0.51795564],
        [0.0957362 , 0.26306843, 0.24824746],
        [0.63398966, 0.44752899, 0.37449257]],

       [[0.        , 0.        , 0.        ],
        [0.        , 0.        , 0.        ],
        [0.49413734, 0.07294475, 0.8341346 ]],

       [[0.        , 0.        , 0.        ],
        [0.        , 0.        , 0.        ],
        [0.18410631, 0.77498275, 0.42724167]],

       [[0.60114116, 0.73999382, 0.76348436],
        [0.49114468, 0.18131404, 0.01817003],
        [0.51479338, 0.41674903, 0.80151682]],

       [[0.67634706, 0.56007131, 0.68486408],
        [0.35607505, 0.51342861, 0.75062432],
        [0.44943936, 0.10768226, 0.62945455]]])
  • Related