# -*- 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)
Opencv 批量裁剪图像 修改xml标签文件
于 2022-07-07 14:17:03 首次发布