代码如下:
# -*- coding: UTF-8 -*-
from PIL import Image
import os
def get_filelist(path):
Filelist = []
for home, dirs, files in os.walk(path):
for filename in files:
# 文件名列表,包含完整路径
if "txt" in filename:
Filelist.append(os.path.join(home, filename))
# # 文件名列表,只包含文件名
# Filelist.append( filename)
return Filelist
if __name__ == "__main__":
# 先读标签文件,找到对应的图片文件,从标签中读取中心点(x,y)和宽高 w、h,通过图片宽高计算四个顶点坐标
# top = height * (y - h/2); bottom =height * ( y + h/2); left = width * (x - w/2); right = width * (x + w/2)
# x1(left, top),x2(right, top), x3(right, bottom),x4(left, bottom)
filePath = './text_src'
# 指定保存的文件夹
outputPath = './text_dst'
# 获得文件夹下所有文件
# filePath = './imgs/' # 只能获取当前路径下的文件,不能递归
# filenames = os.listdir(filePath)
Filelist = get_filelist(filePath)
print(len(Filelist))
# 迭代所有图片
for filename in Filelist:
print(filename)
imgfilename = filename.replace(".txt", ".jpg")
# 读取图像 标签
im = Image.open(imgfilename)
(width, height) = im.size
# 保存
output_path = filename.replace(filePath, outputPath)
outputdir = output_path.rsplit('\\', 1)[0]
if not os.path.exists(outputdir):
os.makedirs(outputdir)
file_lineinfo = open(output_path, 'w', encoding='utf-8')
f = open(filename, encoding='utf-8-sig')
x_1 = y_1 = x_2 = y_2 = x_3 = y_3 = x_4 = y_4 = 0
x = y = w = h = 0
left = right = top = bottom = 0
for line in f.readlines():
print(line)
data = line.replace('\n', '')
substr = data.split(' ')
x = float(substr[1])
y = float(substr[2])
w = float(substr[3])
h = float(substr[4])
left = int(width * (x - w/2))
right = int(width * (x + w/2))
top = int(height * (y - h/2))
bottom = int(height * (y + h/2))
x_1 = left
y_1 = top
x_2 = right
y_2 = top
x_3 = right
y_3 = bottom
x_4 = left
y_4 = bottom
# content = substr[8]
line_info = [str(x_1), ',', str(y_1), ',', str(x_2), ',', str(y_2), ',', str(x_3), ',', str(y_3), ',', str(x_4), ',', str(y_4), ',', "location", '\n']
#line_info = [str(label), x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4, '\n']
file_lineinfo.writelines(line_info)
f.close()
#line_info = [label, ' ', x_1, ' ', y_1, ' ', x_2, ' ', y_2, ' ', x_3, ' ', y_3, ' ', x_4, ' ', y_4, '\n']
file_lineinfo.close()
注意的地方:递归创建多级目录
1. os.mknod
os.mknod用于直接创建一个文件,一般会在此之前判断文件是否存在。
参考:https://www.cnblogs.com/jhao/p/7243043.html
import os
file = "text.txt"
# 判断文件是否存在,不存在则创建
if not os.path.exists(file):
os.mknod(file)
2. open
open(“test.txt”,w),直接打开一个文件,如果文件不存在则创建文件。
open("test.txt",w)
创建目录
有两种方法创建目录,一种是只有子目录不存在的时候创建,另一种是只要有目录不存在就会相应的递归的创建目录。
1. os.mkdir
os.mkdir(path) 创建目录
import os
# 创建的目录
path = "E:/ly/ly"
if not os.path.exists(path):
os.mkdir(path)
这种情况下第一个ly目录必须存在,第二个目录不存在则会创建第二个目录ly。
2. os.makedirs
os.makedirs() 用于递归创建目录。
import os
# 创建的目录
path = "E:/ly/ly"
if not os.path.exists(path):
os.makedirs(path)
运行结果:
这种情况下,只要目录路径下有不存在的目录,就会创建该目录,然后递归的创建文件目录。