大图裁剪小图同时裁剪annotation

import os
import sys
import argparse
import cv2 
import numpy as np
from PIL import Image, ImageDraw

import xml.dom.minidom
from xml.etree.ElementTree import ElementTree,Element,parse
from xml.dom import minidom
import xml.etree.ElementTree as ET
import xml.dom.minidom as DOC

#分割高分辨率图像成小图
#同时裁剪XML文件

small_img_w_length = 1500
small_img_h_length = 1500

img_height_overlap = 100
img_width_overlap = 100
#image_path = '/home/hs/important-demo/SKU110K/sku_test/retail_face_data/images/'
allPath = '/home/hs/data/data_jiaxingyili/goods/smalldeal'
old_img_path = allPath + '/img/'
old_xml_path = allPath + '/xml/'
new_img_path = allPath + '/imgC/'
new_xml_path = allPath + '/xmlC/'


# 从xml文件中提取bounding box信息, 格式为[[x_min, y_min, x_max, y_max, name]]
def parse_xml(image_file,y_start,y_end, x_start,x_end):
    '''
    输入:xml_path: xml的文件路径
    输出:从xml文件中提取bounding box信息, 格式为[[x_min, y_min, x_max, y_max, name]]
    '''
    xmls_list = os.listdir(old_xml_path)
    #nums = len(xmls_list)

    coords = list()
    #for i in range(nums):
    #xml_path = os.path.join(old_xml_path, image_file.replace('jpg', 'xml'))

    if image_file.split(".")[1] == 'png':
        xml_path = os.path.join(old_xml_path, image_file.replace('png', 'xml'))
    else:
        xml_path = os.path.join(old_xml_path, image_file.replace('jpg', 'xml'))

    root = ET.parse(xml_path).getroot()
    objects = root.findall('object')
    for obj in objects:
        bbox = obj.find('bndbox')
        name = obj.find('name').text
        xmin = int(float(bbox.find('xmin').text.strip()))
        ymin = int(float(bbox.find('ymin').text.strip()))
        xmax = int(float(bbox.find('xmax').text.strip()))
        ymax = int(float(bbox.find('ymax').text.strip()))
        if x_start <= xmin and xmax <= x_end and y_start <= ymin and ymax <= y_end and xmax >= x_start and ymax >= y_start and xmin <= x_end and ymin <= y_end :
            coords.append([xmin - x_start, ymin - y_start, xmax - x_start, ymax - y_start, name])
            continue

        if x_start <= xmin and xmax <= x_end and y_start >= ymin and ymax <= y_end and ymax >= y_start :
            coords.append([xmin - x_start, y_start - y_start, xmax - x_start, ymax - y_start, name]) 
            continue
        if x_start <= xmin and xmax >= x_end and y_start <= ymin and ymax <= y_end and xmin <= x_end :
            coords.append([xmin - x_start, ymin - y_start, x_end - x_start, ymax - y_start, name])
            continue
        if x_start <= xmin and xmax <= x_end and y_start <= ymin and ymax >= y_end and ymin <= y_end :
            coords.append([xmin - x_start, ymin - y_start, xmax - x_start, y_end - y_start, name])
            continue
        if x_start >= xmin and xmax <= x_end and y_start <= ymin and ymax <= y_end and xmax >= x_start :
            coords.append([x_start - x_start, ymin - y_start, xmax - x_start, ymax - y_start, name])
            continue

        if x_start >= xmin and xmax <= x_end and y_start >= ymin and ymax <= y_end and xmax >= x_start and ymax >= y_start :
            coords.append([x_start - x_start, y_start - y_start, xmax - x_start, ymax - y_start, name])
            continue
        if x_start <= xmin and xmax >= x_end and y_start >= ymin and ymax <= y_end and xmin <= x_end and ymax >= y_start :
            coords.append([xmin - x_start, y_start - y_start, x_end - x_start, ymax - y_start, name])
            continue
        if x_start <= xmin and xmax >= x_end and y_start <= ymin and ymax >= y_end and xmin <= x_end and y_end >= ymin :
            coords.append([xmin - x_start, ymin - y_start, x_end - x_start, y_end - y_start, name])
            continue
        if x_start >= xmin and xmax <= x_end and y_start <= ymin and ymax >= y_end and xmax >= x_start and y_end >=ymin :
            coords.append([x_start - x_start, ymin - y_start, xmax - x_start, y_end - y_start, name])
            continue

    return coords

#将bounding box信息写入xml文件中, bouding box格式为[[x_min, y_min, x_max, y_max, name]]
def generate_xml(img_name,coords,img_size,out_root_path):
    '''
    输入:
        img_name:图片名称,如a.jpg
        coords:坐标list,格式为[[x_min, y_min, x_max, y_max, name]],name为概况的标注
        img_size:图像的大小,格式为[h,w,c]
        out_root_path: xml文件输出的根路径
    '''
    doc = DOC.Document()  # 创建DOM文档对象

    annotation = doc.createElement('annotation')
    doc.appendChild(annotation)

    title = doc.createElement('folder')
    title_text = doc.createTextNode('Tianchi')
    title.appendChild(title_text)
    annotation.appendChild(title)

    title = doc.createElement('filename')
    title_text = doc.createTextNode(img_name)
    title.appendChild(title_text)
    annotation.appendChild(title)

    source = doc.createElement('source')
    annotation.appendChild(source)

    title = doc.createElement('database')
    title_text = doc.createTextNode('The Tianchi Database')
    title.appendChild(title_text)
    source.appendChild(title)

    title = doc.createElement('annotation')
    title_text = doc.createTextNode('Tianchi')
    title.appendChild(title_text)
    source.appendChild(title)

    size = doc.createElement('size')
    annotation.appendChild(size)

    title = doc.createElement('width')
    title_text = doc.createTextNode(str(img_size[1]))
    title.appendChild(title_text)
    size.appendChild(title)

    title = doc.createElement('height')
    title_text = doc.createTextNode(str(img_size[0]))
    title.appendChild(title_text)
    size.appendChild(title)

    title = doc.createElement('depth')
    title_text = doc.createTextNode(str(img_size[2]))
    title.appendChild(title_text)
    size.appendChild(title)

    for coord in coords:

        object = doc.createElement('object')
        annotation.appendChild(object)

        title = doc.createElement('name')
        title_text = doc.createTextNode(coord[4])
        title.appendChild(title_text)
        object.appendChild(title)

        pose = doc.createElement('pose')
        pose.appendChild(doc.createTextNode('Unspecified'))
        object.appendChild(pose)
        truncated = doc.createElement('truncated')
        truncated.appendChild(doc.createTextNode('1'))
        object.appendChild(truncated)
        difficult = doc.createElement('difficult')
        difficult.appendChild(doc.createTextNode('0'))
        object.appendChild(difficult)

        bndbox = doc.createElement('bndbox')
        object.appendChild(bndbox)
        title = doc.createElement('xmin')
        title_text = doc.createTextNode(str(int(float(coord[0]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)
        title = doc.createElement('ymin')
        title_text = doc.createTextNode(str(int(float(coord[1]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)
        title = doc.createElement('xmax')
        title_text = doc.createTextNode(str(int(float(coord[2]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)
        title = doc.createElement('ymax')
        title_text = doc.createTextNode(str(int(float(coord[3]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)

    # 将DOM对象doc写入文件
    img_name = img_name.split('/')[-1]
    print(img_name)
    f = open(os.path.join(out_root_path, img_name[:-4]+'.xml'),'w')
    f.write(doc.toprettyxml(indent = ''))
    f.close()
#计算一张整图分割成小图的数量(x与y方向)
def get_groups(len_of_img, overlap, small_img_w_length):
    length = small_img_w_length - overlap

    if len_of_img % length < overlap:
        last_one = 0
    else:
        last_one = 1

    return int(len_of_img / length) + last_one

def split_image(image_file):
    img = cv2.imread(os.path.join(old_img_path,image_file))
    img_height, img_width, _ = img.shape
    print("img_height: {}".format(img_height))
    print("img_width: {}".format(img_width))

    y_groups = get_groups(img_height, img_height_overlap, small_img_w_length)
    x_groups = get_groups(img_width, img_width_overlap, small_img_w_length)

    #sImageInfo = []
    img_size = list()
    for x in range(x_groups):
        for y in range(y_groups):
            if x == x_groups or y == y_groups: continue

            y_start = y * (small_img_h_length - img_height_overlap)
            
            if y == y_groups - 1:
                y_end = img_height
            else:
                y_end = y_start + small_img_h_length
            
            x_start = x * (small_img_w_length - img_width_overlap)
            
            if x == x_groups - 1:
                x_end = img_width
            else:
                x_end = x_start + small_img_w_length

            
            small_img = img[y_start:y_end, x_start:x_end]
            img_file_name = '{}{}_{}_{}'.format(new_img_path,x,y,image_file)

            print("img_file_name:",img_file_name)
            # 从xml文件中提取bounding box信息, 格式为[[x_min, y_min, x_max, y_max, name]]
            coords = parse_xml(image_file,y_start,y_end,x_start,x_end)
            #img_size:图像的大小,格式为[h,w,c]
            img_size =[y_end - y_start,x_end - x_start,3]
            generate_xml(img_file_name,coords,img_size,new_xml_path)

            cv2.imwrite(img_file_name, small_img)
            #sImageInfo.append((x_start, x_end, y_start, y_end, img_file_name))

    #return sImageInfo

def create_dir_not_exist(path):
    if not os.path.exists(path):
        os.mkdir(path)

if __name__ == '__main__':

    im_names = []
    create_dir_not_exist(new_img_path)
    create_dir_not_exist(new_xml_path)

    for filename in os.listdir(os.path.join(old_img_path, '')):
        if filename.endswith(".jpg") or filename.endswith(".JPG")or filename.endswith(".png"):
            im_names.append(filename)
    print(im_names)

    for image_file in im_names:
        # Split to small images
        try:
            split_info = split_image(image_file)
        except Exception as e:
            pass
        continue
上一篇:java汉字转拼音和获取汉语拼音首字母


下一篇:Springboot-微服务-微服务组件之服务管理-服务熔断雪崩-Hystrix-服务熔断