Как обрезать несколько изображений, используя положение ограничивающего прямоугольника в файле (python)? - PullRequest
1 голос
/ 26 сентября 2019

У меня есть набор данных images.jpg, и файл csv имеет значения, ограничивающие прямоугольник: top, left, right, bottom.Я использую Ubuntu OS и язык Python.

Пример моих данных:

image_id    bounding_box

001693884030.jpg?sr.dw=700   {'right': 0.6571428571428571, 'bottom': 0.9285714285714286, 'top': 0.38095238095238093, 'left': 0.3142857142857143}
001693884003.jpg?sr.dw=700   {'right': 0.6428571428571429, 'bottom': 0.9761904761904762, 'top': 0.38095238095238093, 'left': 0.22857142857142856}
001735837028.jpg?sr.dw=700   {'right': 0.68, 'bottom': 0.9, 'top': 0.4, 'left': 0.34}
001740301012.jpg?sr.dw=700   {'right': 0.6142857142857143, 'bottom': 0.9523809523809523, 'top': 0.38095238095238093, 'left': 0.35714285714285715}

1 Ответ

0 голосов
/ 26 сентября 2019

Нечто подобное должно работать.Предполагается несколько вещей:

  • , что разделитель в вашем CSV является точкой с запятой, т.е. ;
  • , что ваш файл CSV называется images.csv
  • что вы хотите, чтобы обрезанные изображения выводились в подкаталог с именем output
  • , в котором установлена ​​PIL / Pillow, хотя его можно легко адаптировать для использования 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)
...