python - 使用子进程 Popen 和 PIPE 在 python 中循环图像

标签 python subprocess imagemagick-identify

我有一个包含一堆图像的文件夹。我正在尝试编写一个 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 = [center x, center 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

最佳答案

每次迭代,您的命令都会被附加到。我怀疑你并不是真的想要那样。考虑一下代码的简化版本:

labels = 'LABELS'
srcdir = 'SRCDIR/'
in_metadata = {123: {labels:[1,2]}, 234: {labels:[2,3]}}
command = ['identify', '-format', '%[fx:w],%[fx:h]']

for img_id, img_dict in in_metadata.iteritems():
    command.append(srcdir + 'images/' + str(img_id) + '.jpg')
    print command

输出:

['identify', '-format', '%[fx:w],%[fx:h]', 'SRCDIR/images/234.jpg']
['identify', '-format', '%[fx:w],%[fx:h]', 'SRCDIR/images/234.jpg', 'SRCDIR/images/123.jpg']

您可能想要更像这样的东西:

base_command = ['identify', '-format', '%[fx:w],%[fx:h]']

for img_id, img_dict in in_metadata.iteritems():
    command = base_command + [srcdir + 'images/' + str(img_id) + '.jpg']
    ...

关于python - 使用子进程 Popen 和 PIPE 在 python 中循环图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41112334/

相关文章:

imagemagick - 提取图像的一部分进行识别

python - 获取当前网址

python - 操作系统如何处理 python 和 python 脚本的子进程......?

image-processing - ImageMagick 将 BMP 从 24 位转换为 16 位模式?

python - 如何使用 Python 子进程在 Windows 中进行搜索

python - 如何使用python保存内存、pid和进程

python - 无法在heroku上恢复postgres转储

python - 如何使用 Tableau 或 Excel 将数据时间转换为秒数

Python 混淆函数引用