Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2649508
  • 博文数量: 105
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 960
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(105)

文章存档

2021年(33)

2020年(50)

2019年(22)

我的朋友

分类: Python/Ruby

2021-03-16 17:24:34

import time

import os

from PIL import Image

import cv2

import numpy as np

'''人为构造xml文件的格式'''

out0 ='''

    %(folder)s

    %(name)s

    %(path)s

    

        None

    

    

        %(width)d

        %(height)d

        3

    

    0

'''

out1 = '''    

        %(class)s

        Unspecified

        0

        0

        

            %(xmin)d

            %(ymin)d

            %(xmax)d

            %(ymax)d

        

    

'''

out2 = '''

'''

'''txtxml函数'''

def translate(fdir,lists):

    source = {}

    label = {}

    for jpg in lists:

        print(jpg)

        if jpg[-4:] == '.jpg':

            image= 货币代码cv2.imread(jpg)#路径不能有中文

            h,w,_ = image.shape #图片大小

#            cv2.imshow('1',image)

#            cv2.waitKey(1000)

#            cv2.destroyAllWindows()

            fxml = jpg.replace('.jpg','.xml')

            fxml = open(fxml, 'w');

            imgfile = jpg.split('/')[-1]

            source['name'] = imgfile

            source['path'] = jpg

            source['folder'] = os.path.basename(fdir)

            source['width'] = w

            source['height'] = h

            fxml.write(out0 % source)

            txt = jpg.replace('.jpg','.txt')

            lines = np.loadtxt(txt)#读入txt存为数组

            #print(type(lines))

            for box in lines:

                #print(box.shape)

                if box.shape != (5,):

                    box = lines                 

                '''txt上的第一列(类别)转成xml上的类别

                   我这里是labelimg123,对应txt上面的012'''

                label['class'] = str(int(box[0])+1) #类别索引从1开始

                '''txt上的数字(归一化)转成xml上框的坐标'''

                xmin = float(box[1] - 0.5*box[3])*w

                ymin = float(box[2] - 0.5*box[4])*h

                xmax = float(xmin + box[3]*w)

                ymax = float(ymin + box[4]*h)

                label['xmin'] = xmin

                label['ymin'] = ymin

                label['xmax'] = xmax

                label['ymax'] = ymax

                # if label['xmin']>=w or label['ymin']>=h or label['xmax']>=w or label['ymax']>=h:

                #     continue

                # if label['xmin']<0 or label['ymin']<0 or label['xmax']<0 or label['ymax']<0:

                #     continue

                fxml.write(out1 % label)

            fxml.write(out2)

if __name__ == '__main__':

    file_dir = 'G:/qing-litchi'#

    lists=[]

    for i in os.listdir(file_dir):

        if i[-3:]=='jpg':

            lists.append(file_dir+'/'+i)       

    #print(lists)

    translate(file_dir,lists)

    print('---------------Done!!!--------------')            

阅读(132) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~