如何使用文件中的列表边界框位置裁剪多幅图像(python)? [英] How to crop multi images use list bounding box position in the file (python)?

查看:343
本文介绍了如何使用文件中的列表边界框位置裁剪多幅图像(python)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个images.jpg数据集,而一个csv文件具有将框位置限制在顶部,左侧,右侧,底部的值.我使用ubuntu OS和python语言.

I have a dataset of images.jpg and a file csv has values bounding box position is top, left, right, bottom. I use ubuntu OS and the python language.

推荐答案

类似的东西应该可以工作.它假设了一些事情:

Something like this should work. It assumes a few things:

  • 您的CSV分隔符为分号,即;
  • 您的CSV文件称为images.csv
  • 您希望将裁剪后的图像输出到名为output
  • 的子目录
  • 您已安装了PIL/Pillow,但可以很容易地将其修改为使用pyvipsOpenCVskimage
  • that the separator in your CSV is a semi-colon, i.e. ;
  • that your CSV file is called images.csv
  • that you want the cropped images output to a sub-directory called output
  • that you have PIL/Pillow installed, though it could easily be adapted to use pyvips, OpenCV, skimage
#!/usr/bin/env python3

import os
import re
import csv
import json
from PIL import Image

def cropImage(filename,coords):
    """Crop image specified by filename to coordinates specified."""
    print(f"DEBUG: cropImage({filename},{coords})")

    # Open image and get height and width
    im = Image.open(filename)
    w, h = im.width, im.height

    # Work out crop coordinates, top, left, bottom, right
    l = int(coords['left']  * w)
    r = int(coords['right'] * w)
    t = int(coords['top']   * h)
    b = int(coords['bottom']* h)

    # Crop and save
    im = im.crop((l,t,r,b))
    im.save("output/" + filename)
    return

# Create output directory if not existing
if not os.path.exists('output'):
    os.makedirs('output')

# Process CSV file - expected format
# heading;heading
# 00000001.jpg?sr.dw=700;{'right': 0.9, 'bottom': 0.8, 'top': 0.1, 'left': 0.2}
# 00000002.jpg?sr.dw=700;{'right': 0.96, 'bottom': 0.86, 'top': 0.2, 'left': 0.25}

with open('images.csv') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=';')
    for row in csv_reader:
        fieldA, fieldB = row[:2]

        # Ignore header lines
        if not "jpg" in fieldA:
            continue

        # Strip trailing rubbish off filename
        filename = re.sub("\?.*","",fieldA)
        print(f"DEBUG: filename={filename}")

        # Replace single quotes in JSON with double quotes
        JSON = fieldB.replace("'",'"')
        print(f"DEBUG: JSON={JSON}")
        coords = json.loads(JSON)
        print(f"DEBUG: coords={coords}")

        cropImage(filename, coords)

这篇关于如何使用文件中的列表边界框位置裁剪多幅图像(python)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆