1 回答
TA贡献1830条经验 获得超9个赞
我们可以通过以下方式实现。让我们首先创建一个虚拟数据框。
import pandas as pd
import random
info = {
'image_id': ['01', '01', '01', '02', '04', '04'],
'x':random.sample(range(500, 600), 6),
'y':random.sample(range(200, 500), 6),
'w':random.sample(range(200, 300), 6),
'h':random.sample(range(400, 600), 6),
'x_center':random.sample(range(250, 460), 6),
'y_center':random.sample(range(250, 460), 6),
'img_height':random.sample(range(2100, 3000), 6),
'img_width':random.sample(range(1100, 4000), 6),
'labels':[0,0,0,1,2,2]
}
df = pd.DataFrame(data=info)
df.head()
--------------------------
image_id x y w h x_center y_center img_height img_width labels
0 01 561 435 290 449 303 318 2105 2806 0
1 01 583 447 265 427 394 421 2338 2047 0
2 01 520 417 262 592 429 395 2947 3388 0
3 02 516 415 214 470 455 319 2649 1594 1
4 04 522 386 204 514 343 394 2847 1770 2
接下来,我们将获取groupyby图像ID并迭代每一行。
df_image_id = df.groupby('image_id') # group by id
for _ , row in df_image_id:
for _ , each in row.iterrows(): # iterate each samples within same id
img_w = each['img_width']
img_h = each['img_height']
content = [
each['labels'],
each['x_center']/each['img_width'],
each['y_center']/each['img_height'],
each['w']/each['img_width'],
each['h']/each['img_height']
]
id = each['image_id']
with open(f'{id}.txt', 'a') as f1:
f1.write(" ".join(str(x) for x in content)+ '\n')
添加回答
举报