utilize python, according to txt File to read a specific image in the specified directory ( Read txt An image of the name appears in the file ), Copy and change the image name .
read()、readline()、readlines() Three differences : Reference resources python in read() readline() as well as readlines() difference - You know
- read() Read the entire file every time , It usually reads the contents of the file into a string variable , in other words .read() The content of the makefile is a string type .
- readline() One line per read file , It's usually a line that is read and put into a string variable , return str type .
- readlines() Read the entire contents of the file on a line at a time , Put the read in a list , return list type .
txt Image name in file & Image name under the original directory file :
train.txt: train_0.png, train_1.png, train_2.png, train_3.png, ……
label Folder ( original ):0.png, 1.png, 2.png, 3.png, 4.png, 5.png,……( Numerous )
label2 Folder ( Generate ):train_0.png, train_1.png, train_2.png, train_3.png, ……( part )
# -*- coding: UTF-8 -*-
#!/usr/bin/env python
import re
from PIL import Image
import numpy as np
import os
data = []
path1=r'F:\all_date\WHU\train.txt' # txt File path
path_img1=r'F:\all_date\WHU\label' # Original image file path
path_img2=r'F:\all_date\WHU\label2' # Save image new path
with open(path1,'r') as fr:
data = fr.readlines()
data = ''.join(data).strip('\n').splitlines()
# ''.join() list To str
# s.strip(rm) Delete s At the beginning and end of rm character
# .splitlines() Returns a string to a list
# print(data)
for name in data:
name1=name.split('_')[1]
path_old=os.path.join(path_img1,name1)
path_new=os.path.join(path_img2,name)
im=Image.open(path_old)
im.save(path_new)
im.close()