How can I convert bounding box pixels of an image to white, and the background to black?

641 Views Asked by At

I have a set of images similar to this one: enter image description here

And for each image, I have a text file with bounding box regions expressed in normalized pixel values, YOLOv5 format (a text document with rows of type: class, x_center, y_center, width, height). Here's an example:

3 0.1661542727623449 0.6696164480452673 0.2951388888888889 0.300925925925926
3 0.41214353459362196 0.851908114711934 0.2719907407407405 0.2961837705761321

I'd like to obtain a new dataset of masked images, where the bounding box area from the original image gets converted into white pixels, and the rest gets converted into black pixels. This would be and example of the output image: enter image description here
I'm sure there is a way to do this in PIL (Pillow) in Python, but I just can't seem to find a way. Would somebody be able to help? Kindest thanks!

1

There are 1 best solutions below

0
Ema Ilic On

so here's the answer:

import os
import numpy as np
from PIL import Image 


label=open(os.path.join(labPath, filename), 'r')
lines=label.read().split('\n')
square=np.zeros((1152,1152))
for line in lines:
    if line!='':
      line=line.split() #line: class, x, y, w, h
      left=int((float(line[1])-0.5*float(line[3]))*1152 )
      bot=int((float(line[2])+0.5*float(line[4]))*1152)
      top=int(bot-float(line[4])*1152)
      right=int(left+float(line[3])*1152)
      square[top:bot, left:right]=255
square_img = Image.fromarray(square)
square_img=square_img.convert("L")

Let me know if you have any questions!