将图片名写入txt文件 & 根据txt文件中的图片名提取特定图像 & 将图片插入word

本文讲述3种方法,分别是:1. 将图片名写入txt文件;2. 根据txt文件中的图片名提取特定图像;3. 将图片插入word

  1. 将图片名写入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()
  1. 根据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)
  1. 将图片插入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.")

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值