Python 将不同尺寸的图片和xml标签等比例缩放到指定大小

该博客介绍了一个使用Python实现的脚本,用于将不同尺寸的图片和对应的XML标签文件等比例缩放至指定尺寸。脚本首先读取原文件夹中的图片和XML文件,然后根据目标尺寸计算缩放比例。对于图片,如果宽度或高度超过目标尺寸,按最长边等比例缩放;若小于目标尺寸,则保持原图不变。对于XML文件中的边界框坐标,同样按比例调整。最后,将处理后的图片和XML保存到新文件夹,并更新XML文件中的坐标信息。
摘要由CSDN通过智能技术生成

Python 将不同尺寸的图片和xml标签等比例缩放到指定大小

xml文件格式:
在这里插入图片描述

import os
import cv2
import numpy as np
import xml.etree.ElementTree as ET

path = r'C:\Users\1\Desktop\test\old'  # 原文件夹路径
newpath = r'C:\Users\1\Desktop\test\new'  # 新文件夹路径
c_w, c_h = 224, 224  # 目标图片的尺寸

def edit_xml(xml_file, ratio, i):
    all_xml_file = os.path.join(path, xml_file)
    tree = ET.parse(all_xml_file)
    objs = tree.findall('object')

    for obj in objs:
        obj_bnd = obj.find('bndbox')
        obj_bnd = obj.find('bndbox')
        obj_xmin = obj_bnd.find('xmin')
        obj_ymin = obj_bnd.find('ymin')
        obj_xmax = obj_bnd.find('xmax')
        obj_ymax = obj_bnd.find('ymax')
        xmin = float(obj_xmin.text)
        ymin = float(obj_ymin.text)
        xmax = float(obj_xmax.text)
        ymax = float(obj_ymax.text)
        obj_xmin.text = str(round(xmin * ratio))
        obj_ymin.text = str(round(ymin * ratio))
        obj_xmax.text = str(round(xmax * ratio))
        obj_ymax.text = str(round(ymax * ratio))

    newfile = os.path.join(newpath, '%05d' % (0 + i) + '.xml')
    tree.write(newfile, method='xml', encoding='utf-8')  # 更新xml文件


if __name__ == '__main__':
    files = os.listdir(path)  # 获取文件名列表
    i = 0
    for file in files:
        img_zeros = np.zeros((c_w, c_h, 3), np.uint8)  # 创建全黑的图像
        if file.endswith('.jpg'):
            imgName = os.path.join(path, file)  # 获取文件完整路径
            xml_file = file.replace('.jpg', '.xml')
            img = cv2.imread(imgName)  # 读图
            h, w, _ = img.shape  # 获取图像宽高
            # 缩放图像,宽高大于c_w的按长边等比例缩放,小于c_w的保持原图像大小:
            if max(w, h) > c_w:
                ratio = c_w / max(w, h)
                imgcrop = cv2.resize(img, (round(w * ratio), round(h * ratio)))
                # 将缩放后的图像复制进全黑图像里
                img_zeros[0:round(h * ratio), 0:round(w * ratio)] = imgcrop
                edit_xml(xml_file, ratio, i)
            else:
                img_zeros[0:h, 0:w] = img
                edit_xml(xml_file, 1, i)

            # 设置新的文件名:
            newName = os.path.join(newpath, '%05d' % (0 + i) + '.jpg')
            i += 1
            print(newName)
            cv2.imwrite(newName, img_zeros)  # 存储按新文件名命令的图片

参考链接:https://blog.csdn.net/qq_36563273/article/details/109580882

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值