`
import os
if __name__ == '__main__':
filenames=os.listdir(r'D:\naizhang')
i=2304
for f in filenames:
if(f[-4:]=='.jpg'):
print(f)
os.rename('D:\naizhang\'+f,'D:\naizhang\'+str(i)+".jpg")
os.rename('D:\naizhang\' + f[:-4]+'.txt', 'D:\naizhang\' + str(i) + ".txt")
i=i+1
import cv2
import os
workdir='D:\naizhang\'
savedir='D:\ss\'
def cut_one_image(img_path, txt_path,j):
# 读取txt文件信息
def read_list(txt_path):
pos = []
with open(txt_path, 'r') as file_to_read:
while True:
lines = file_to_read.readline() # 整行读取数据
if not lines:
break
pass
# 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
p_tmp = [float(i) for i in lines.split(' ')]
pos.append(p_tmp) # 添加新读取的数据
# Efield.append(E_tmp)
pass
return pos
# txt转换为box
def convert(size, box):
xmin = (box[1] - box[3] / 2.) * size[1]
xmax = (box[1] + box[3] / 2.) * size[1]
ymin = (box[2] - box[4] / 2.) * size[0]
ymax = (box[2] + box[4] / 2.) * size[0]
box = (int(xmin), int(ymin), int(xmax), int(ymax),box[0])
return box
image = cv2.imread(img_path)
pos = read_list(txt_path)
for i in range(len(pos)):
box = convert(image.shape, pos[i])
image = cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 1)
save_path = str(int(box[4]))+'_'+str(j)+'_' + str(i) + '.jpg'
print(savedir+save_path)
img = image[box[1]:box[3], box[0]:box[2]]
cv2.imwrite(savedir+save_path, img)
if __name__ == '__main__':
for i in range(2304,2400):
cut_one_image(workdir+str(i)+'.jpg',workdir+str(i)+'.txt',i)



