Batch indexing to avoid the loop

Hi, my post is closed, so I upload this again.
I want to set values inside bounding boxes to zero.
batch size is 256
Image size is 32,32,3
box components are [ymin,ymax,xmin,xmax]

My original code is below
img=torch.randn((256,3,32,32))
B=torch.rand((256,4))*32
B=B.type(torch.int32)
for i in range(256):
img[i,:,B[i,0]:B[i,1],B[i,2]:B[i,3]]=0

Is there any way to avoid for-loop?
Thanks

Hi Hwang!

Yes, you can use your bounding boxes, B, to build a mask tensor that
you then multiply onto img to zero out the values in the bounding boxes:

>>> import torch
>>> print (torch.__version__)
1.13.0
>>>
>>> _ = torch.manual_seed (2022)
>>>
>>> nBatch = 256
>>> nChannels = 3
>>> h = 32
>>> w = h
>>>
>>> img = torch.randn (nBatch, nChannels, h, w)
>>> B = torch.rand (nBatch, 4) * h
>>> B = B.type (torch.int32)
>>>
>>> imgB = img.clone()
>>>
>>> # loop version
>>> for  i in range (nBatch):
...     img[i, :, B[i, 0]:B[i, 1], B[i, 2]:B[i, 3]] = 0
...
>>> # loop-free mask version
>>> hMask = torch.logical_or (torch.arange (h).unsqueeze (0) < B[:, 0, None], torch.arange (h).unsqueeze (0) >= B[:, 1, None])
>>> wMask = torch.logical_or (torch.arange (w).unsqueeze (0) < B[:, 2, None], torch.arange (w).unsqueeze (0) >= B[:, 3, None])
>>> mask = torch.logical_or (hMask.unsqueeze (2), wMask.unsqueeze (1))
>>> imgB *= mask.unsqueeze (1)
>>>
>>> torch.equal (img, imgB)
True

Best.

K. Frank