J.Doe
J.Doe

Reputation: 17

how to loop through draw.rectangle in pillow python?

I want to retrieve face coordinates from a JSON file that looks like this:

#Beginning PART OF JSON FILE
{
    "image": {
        "height": 2160,
        "orientation": 1,
        "width": 3840
    },
    "objects": [
        {
            "boundingBox": {
                "height": 1152,
                "width": 1048,
                "x": 0,
                "y": 977
            },
            "type": "person"
        },
        {
            "boundingBox": {
                "height": 1305,
                "width": 486,
                "x": 1096,
                "y": 852
            },
            "type": "person"
        },...
....

PYTHON CODE:

import PIL
import json
from PIL import Image, ImageDraw

with open('facecoordinates.json','r') as f:
    data = json.load(f)

height = d["objects"] [0] ["boundingBox"] ["height"]
width = d["objects"] [0] ["boundingBox"] ["width"]
xx = d["objects"] [0] ["boundingBox"] ["x"]
yy = d["objects"] [0] ["boundingBox"] ["y"]

image = Image.open('vlcsnap.png')


imgcp = image.copy()
imgcp_draw = ImageDraw.Draw(imgcp)


imgcp_draw.rectangle([xx,yy,(width+xx),(yy+height)], fill = None, outline = "red")

imgcp.save('DC1.jpg')
imgcp.show()

I managed to pull the first coordinates from the JSON file and map the face but i want to know how to loop through and pass all face-coordinates to draw boxes in image.

i am trying to loop through them to Pillow.DRAW.RECTANGLE as coordinates to draw the box on image.

i have been struggling to get past the loops and its always wrong. any suggestions?

Upvotes: 0

Views: 2593

Answers (1)

ParthS007
ParthS007

Reputation: 2689

You have to correct the way how you are putting in coordinates in Pillow.DRAW.RECTANGLE.

Your code will look like this:

list=data['objects']

# After following Mark's edit

coords_list = [] 
for i in list: 
   coords = [] 
   coords.append(i['boundingBox']['x']) 
   coords.append(i['boundingBox']['y']) 
   coords.append(i['boundingBox']['x'] + i['boundingBox']['width']) 
   coords.append(i['boundingBox']['y'] + i['boundingBox']['height']) 
   coords_list.append(coords) 

image = Image.open('vlcsnap.png')
imgcp = image.copy()
imgcp_draw = ImageDraw.Draw(imgcp)

for coord in  coords_list:
     imgcp_draw.rectangle(coord, fill = None, outline = "red")

imgcp.save('DC1.jpg')
imgcp.show()

Edited by Mark Setchell beyond this point

The draw() functions take x0,y0,x1,y1 rather than a width and height so you need code more like this.

coords_list = [] 
for i in list: 
   coords = [] 
   coords.append(i['boundingBox']['x']) 
   coords.append(i['boundingBox']['y']) 
   coords.append(i['boundingBox']['x'] + i['boundingBox']['width']) 
   coords.append(i['boundingBox']['y'] + i['boundingBox']['height']) 
   coords_list.append(coords) 

Upvotes: 2

Related Questions