遇到一个任务,需要在图像中标出36个矩形框,已知矩形框左上角和右下角的坐标,利用PIL库实现在图像中圈出框的位置。
首先,我选取的图像为
我需要在图像中框出的坐标为(左上角 右下角)
[[222.62515 255.67302 364.9839 340.89417 ]
[ 81.09717 211.92442 458.08273 335.30966 ]
[223.8965 221.82928 289.1028 340.34943 ]
[145.72527 151.60167 206.56865 182.57814 ]
[ 0. 0. 313.1137 244.14508 ]
[301.40558 223.47641 350.72885 271.7093 ]
[149.84697 0. 499.328 280.79437 ]
[229.55548 233.5783 273.51645 281.11407 ]
[284.68933 210.46474 385.0869 334.42242 ]
[114.93104 124.10687 246.40085 230.782 ]
[299.55258 262.35834 357.8653 327.06494 ]
[223.62141 121.755974 306.98068 227.7105 ]
[230.7523 262.90985 286.9603 320.20798 ]
[374.15836 257.33618 410.55496 331.22174 ]
[ 79.30069 115.852234 150.07416 160.16025 ]
[146.27014 252.23901 169.67923 338.7798 ]
[141.68521 110.24527 228.17725 185.29054 ]
[ 47.393333 96.72547 225.1996 253.92085 ]
[ 88.86558 143.17523 147.57951 186.42058 ]
[ 0. 130.42508 499.328 375.248 ]
[ 67.63028 114.51107 158.26865 240.4122 ]
[234.58888 174.8945 357.91595 348.22275 ]
[324.6474 272.78333 350.9239 331.56766 ]
[ 0. 76.21229 365.80353 375.248 ]
[307.68857 257.4475 349.86548 332.42242 ]
[ 88.78306 135.11284 150.01582 194.94719 ]
[ 54.832615 98.842514 336.01965 234.40646 ]
[119.728134 90.25731 304.00183 245.01398 ]
[ 0. 304.77158 462.94046 375.248 ]
[268.06873 283.13705 289.35077 332.36084 ]
[297.36404 264.90875 324.0649 331.03558 ]
[147.1366 143.77739 201.88997 212.323 ]
[353.94962 0. 499.328 276.7343 ]
[234.43933 121.998 298.59018 154.05264 ]
[ 50.72607 110.42905 108.768776 233.0775 ]
[136.28668 134.76195 227.3687 235.19699 ]]
实现代码如下:
from PIL import ImageDraw,Image
box_root_path = r'C:\Users\pc\Desktop\coco caption\f30kbbox\bu_box\98.npy' #存有矩形框坐标的文件
path = r'G:\网盘下载\flickr30k-images\1028982826.jpg' # 图像文件
image = Image.open(path) # 打开一张图片
draw = ImageDraw.Draw(image)
img_boxes = np.load(box_root_path) # 加载需要画出的矩形框坐标信息
#不同颜色框,让每个框更容易在图片中分辨
color = [(0,0,0),(255,255,0),(25,25,112),(255,0,0),(0,0,255)]
i=0
for box in img_boxes:
x1,y1,x2,y2 = box
if i==5:
i=0
draw.rectangle([x1,y1,x2,y2], outline=color[i])
i=i+1
image.show()