Opencv 批量裁剪图像 修改xml标签文件

# -*- coding: utf-8 -*-
import os
import cv2
import xml.etree.ElementTree as ET
from os import getcwd
import numpy as np


imgpath = r'.\images\'
new_img = r'.\images1\'
xml_path = r'.\Annotations\'
new_xml = r'.\Annotations1\'


def CropImage(imgpath, new_img, xml_path, new_xml):
    i = 0
    for file in os.listdir(imgpath):
        img = cv2.imread(os.path.join(imgpath, file))
        #print(file)
        h = img.shape[0]
        w = img.shape[1]
        #print(h, w)

        a = int(h - 0.4 * h)  # y strat 裁剪掉图片四分之一高度
        b = int(h)  # y end
        c = int(0)  # x start
        d = int(w)  # x end


        cropImg = img[a:b, c:d]
       
        
        # 保存新图片路径
        cv2.imwrite(new_img + '\\'+  file.split('.')[0] + ".jpg", cropImg) 
        

        cropImg_w = cropImg.shape[1]
        cropImg_h = cropImg.shape[0]
        # print(cropImg_w,cropImg_h)
        i += 1

        xml = file.split('.')[0] + '.xml'
        xml_path_1 = os.path.join(xml_path, xml)
        tree = ET.parse(xml_path_1)

        root = tree.getroot()

        for s in root.findall('size'):
            s_width = s.find('width')
            s_height = s.find('height')
            s_width.text = str(int(cropImg_w))
            s_height.text = str(int(cropImg_h))

        for obj in root.findall('object'):
            objectname = obj.find('name').text

            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')

            obj_xmin.text = str(int(obj_xmin.text) - c)
            obj_ymin.text = str(int(obj_ymin.text) - a)

            obj_xmax.text = str(int(obj_xmax.text) - c)
            obj_ymax.text = str(int(obj_ymax.text) - a)

            #print(obj_xmin, obj_ymin, obj_xmax, obj_ymax)
            print(i)

        tree.write(os.path.join(new_xml, xml))  # 处理结束后保存的路径
    print("total numbers:", i)


if __name__ == '__main__':
    CropImage(imgpath, new_img, xml_path, new_xml)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值