Deem the lower part of an Image in PyTorch

I wish to deem a part of an image. Not completely black but just creating shadows in the lower regions.

You just have to bring the pixel values of the tensor that represents the image closer to zero. Something like this:

import torchvision
img = Image.open("cat.jpg").resize((224, 224))
img_tensor = torchvision.transforms.ToTensor()(img)
img_tensor[:, 180:, :] *= 0.75  # reduce the brightness of everything below pixel 180 by 25%
img_shaded = torchvision.transforms.ToPILImage()(img_tensor)

original:
image

after shading:
image

Wow, thanks a lot. This is exactly what I wanted.

What if I don’t always intend to use a straight line. E.g a wavy line or some sort of randomized line going from one point to another endpoint but not a straight line?

In that case you need to replace this with some fancier, custom logic:

img_tensor[:, 180:, :] *= 0.75  # reduce the brightness of everything below pixel 180 by 25%

It will come down to finding clever ways to parameterize the behavior you’d like without too much work. For example for a wavy line you might do:

img = Image.open("cat.jpg").resize((224, 224))
img_tensor = torchvision.transforms.ToTensor()(img)

period = 80
amplitude = 20

for n in range(224):
    i = amplitude * math.sin(n / (period / (2 * math.pi)))
    img_tensor[:, (180 + int(round(i))):, n] *= 0.75
img_shaded = torchvision.transforms.ToPILImage()(img_tensor)

image

1 Like

Thanks so very much Andrei. You’re such a gem. Everything is perfect the way I want it now. Thanks for your reply.

1 Like