将图片名写入txt文件 & 根据txt文件中的图片名提取特定图像 & 将图片插入word
本文讲述3种方法,分别是:1. 将图片名写入txt文件;2. 根据txt文件中的图片名提取特定图像;3. 将图片插入word
- 将图片名写入txt文件(可将训练集、测试集中图片名分别记录在txt文件中)
import os
import random
imgpath = 'C:/Users/123/Desktop/111/1/'
txtsavepath = 'C:/Users/123/Desktop/111/5/'
imgtxt = open('C:/Users/123/Desktop/111/5/test.txt', 'w')
for img in os.listdir(imgpath ):
name = img[0:-4] + '\n'
imgtxt.write(name)
imgtxt.close()
- 根据txt文件中的图片名提取特定图像(可根据txt文件找到测试集所有图片)
import csv
import shutil
import os
target_path = 'C:/Users/123/Desktop/111/5/' #保存文件夹地址
original_path = 'C:/Users/123/Desktop/111/1/' #需查找图片的原始地址
with open('C:/Users/123/Desktop/111/5/test.txt',"rt", encoding="utf-8") as csvfile:
for row in csvfile:
row = row.strip('\n')+'.bmp'
if os.path.exists(target_path+row+'.bmp'):
print("已存在文件")
else:
full_path = original_path+row #还没有
shutil.move(full_path,target_path+row)
- 将图片插入word
from docx import Document
from docx.shared import Inches
import os
from PIL import Image
# 要插入的图片所在的文件夹
fold='C:/Users/123/Desktop/3/X4/'
# os.walk(fold)没有返回值,所以这么做显然没有结果,是错的
# pics=list(os.walk(fold)[3])
# # pics.pop()
# print(pics)
# pics是图片的名字
# root是string类型, dirs和pics是list类型
for root, dirs, pics in os.walk(fold):
doc=Document()
for i in range(0,len(pics)):
#不需要把文件后缀名去掉,后面的PIL库里的open可以直接识别出文件名后缀
# print(pics[i],'\n')
# pics[i] = os.path.splitext(pics[i])[0]
# print(pics[i], '\n')
#我前半部分的路径直接复制黏贴了,没用root和dirs
filepath = 'C:/Users/123/Desktop/3/X4/'+pics[i]
# filepath = root + '\\' + str(pics[i])
try:
doc.add_picture(filepath,width=Inches(1),height=Inches(1))
except Exception:
pic_tmp=Image.open(filepath)
# 如果格式有问题,就用save转换成默认的jpg格式
pic_tmp.save(pic_tmp)
# 把处理后的图片放进Document变量doc中
doc.add_picture(filepath, width=Inches(1),height=Inches(1))
# 把Document变量doc保存到指定路径的docx文件中
doc.save('C:/Users/123/Desktop/3/X4.docx')
#输出保存成功的标志
print("pic", i+1, "successfully added.")