利用python实现将文件夹中的已经标注好的大图片的宽和高分别裁剪一半生成四张新图片和四份新的XML标注文件并且将新的图片和标注文件保存到新的文件夹中
时间: 2023-02-25 21:42:19 浏览: 80
下面是一个实现该需求的代码示例:
```python
import os
import cv2
import xml.etree.ElementTree as ET
def crop_image(image_path, xml_path, save_path):
# 读取图片
img = cv2.imread(image_path)
height, width, _ = img.shape
# 读取xml文件并获取标注信息
tree = ET.parse(xml_path)
root = tree.getroot()
for obj in root.iter("object"):
xmin = int(obj.find("bndbox/xmin").text)
ymin = int(obj.find("bndbox/ymin").text)
xmax = int(obj.find("bndbox/xmax").text)
ymax = int(obj.find("bndbox/ymax").text)
# 裁剪图片并保存
crop_img1 = img[0:height//2, 0:width//2]
cv2.imwrite(os.path.join(save_path, "1.jpg"), crop_img1)
# 更新标注信息并保存新的xml文件
for obj in root.iter("object"):
xmin = int(obj.find("bndbox/xmin").text)
ymin = int(obj.find("bndbox/ymin").text)
xmax = int(obj.find("bndbox/xmax").text)
ymax = int(obj.find("bndbox/ymax").text)
obj.find("bndbox/xmin").text = str(xmin//2)
obj.find("bndbox/ymin").text = str(ymin//2)
obj.find("bndbox/xmax").text = str(xmax//2)
obj.find("bndbox/ymax").text = str(ymax//2)
tree.write(os.path.join(save_path, "1.xml"))
crop_img2 = img[0:height//2, width//2:width]
cv2.imwrite(os.path.join(save_path, "2.jpg"), crop_img2)
for obj in root.iter("object"):
xmin = int(obj.find("bndbox/xmin").text)
ymin = int(obj.find("bndbox/ymin").text)
xmax = int(obj.find("bndbox/xmax").text)
ymax = int(obj.find("bndbox/ymax").text)
obj.find("bndbox/xmin").text = str(xmin + width//2)
obj.find("bndbox/xmax").text = str(xmax + width//2)
tree.write(os.path.join(save_path, "2
阅读全文