如何使用文件中的列表边界框位置裁剪多幅图像(python)?

康熙

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

马克·谢切尔

这样的事情应该起作用。它假设一些事情:

  • CSV中的分隔符是分号,即 ;
  • 您的CSV文件称为 images.csv
  • 您想要将裁剪的图像输出到一个名为 output
  • 你有PIL /枕安装,但它可以很容易地适应使用pyvipsOpenCVskimage

#!/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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用边界框列表从图像中裁剪多个边界框

如何使用 Python 的 OpenCV 基于 Google Vision API 边界多归一化顶点裁剪图像

如何使用边界框坐标裁剪图像中的感兴趣区域?

从是整块数组的图像中裁剪边界框

如何在python opencv中简单裁剪边界框

从边界框裁剪 Tensorflow 图像

如何通过绘制边界框(或多边形)来裁剪图像中的多个对象?

如何使用Python在OpenCV中裁剪图像

裁剪图像后,如何找到新的边界框坐标?

语法错误-使用边界框坐标裁剪图像

如何在Python中裁剪和存储边界框图像区域?

如何基于Tensorflow.js中的边界框裁剪脸部?

如何从边界框裁剪图像并为每个框创建新图像

Python:沿边界从图像中裁剪出区域

如何在UIView中的不同位置为多幅图像提供图像动画?

如何从findContours裁剪边界框内的图像

使用openCV裁剪简单的边界框

如何使用Ghostscript裁剪特定页面的裁剪框数组来裁剪多页PDF

尝试确定图像中边界框的坐标并将其进一步裁剪

如何使用opencv python从底部裁剪图像

如何使用 Python PIL 或 CV 裁剪图像?

在彩色框中裁剪图像

检测图像中的文本位置并在Python中裁剪

在python中裁剪图像

如何裁剪多页(图像/扫描)pdf 文件(不会用 pdfcrop 裁剪)?

在Tensorflow Object Detection API中将图像裁剪到边界框

根据对象边界框裁剪旋转的图像-Matlab

Python-从边界框坐标列表创建形状文件

如何在图像的多个矩形边界框中应用阈值?