我有一个包含一堆图像的文件夹。我正在尝试编写一个 python 脚本,它将遍历每个图像并返回宽度/高度,然后将其附加到我的字典中。我的字典的简化版本如下所示:
in_metadata = {123: {labels:[1,2]}, 234: {labels:[2,3]}}
我想要的是这个:
in_metadata = {123: {'labels':[1,2], 'bbox':[320,240,640,480]}, 234: {'labels':[2,3], 'bbox':[320,206,640,412]}, ...}
其中 bbox = [中心 x,中心 y,w,h]
当代码进入循环的第一次迭代时,我得到:
stdout = '640,480'
这是我所期望的。但是,第二次通过循环我得到:
stdout = '640,480640,412'
第一个宽度和高度值不会被刷新。这是我的代码:
command = ['identify', '-format', '%[fx:w],%[fx:h]']
for img_id, img_dict in in_metadata.iteritems():
if 'bbox' in img_dict:
continue
command.append(srcdir + 'images/' + str(img_id) + '.jpg')
p = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if len(stderr) != 0:
continue
w, h = map(int, stdout.split(','))
img_dict['bbox'] = [int(w / 2), int(h / 2), w, h]
stdout.flush()
我已经疯狂地试图让它工作(p.wait、stdout.flush 等),但缓冲区似乎不想为空。我知道这很简单,我错过了什么?
谢谢。
我在 Ubuntu 16.04 上使用 python 2.7.12