如何在python中循环绘制draw.rectangle?

2024-09-27 19:23:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从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作为坐标来在图像上绘制框

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


Tags: 文件imageimportjsonpilobjectstypewidth
1条回答
网友
1楼 · 发布于 2024-09-27 19:23:25

您必须纠正在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) 

相关问题 更多 >

    热门问题