如何在枕头蟒蛇中循环绘制矩形



我想从JSON文件中检索人脸坐标,该文件如下所示:

#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代码:

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()

我设法从JSON文件中提取了第一个坐标并映射了人脸,但我想知道如何循环并传递所有人脸坐标以绘制图像中的框。

我试图将它们循环到Pillow.DRAW.RECTANGLE作为坐标,在图像上绘制方框。

我一直在努力克服循环,但总是错的。有什么建议吗?

您必须纠正在Pillow.DRAW.RECTANGLE中输入坐标的方式。

您的代码将如下所示:

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()

由Mark Setchell编辑,超过此点

draw()函数采用x0,y0,x1,y1,而不是宽度和高度,因此您需要更像这样的代码。

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) 

最新更新