python图像批量导入
Posted BHY_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python图像批量导入相关的知识,希望对你有一定的参考价值。
场景:以前的几千张旧照片,各种扩展名格式的,通过格式工厂统一转成jpg格式,然后通过python检查是否有拍摄日期,如果没有拍摄日期,则将文件的修改时间做为拍摄日期、GPS时间写入。如果文件名不是以IMG_开头的,则将文件重命名为IMG_修改时间,如果文件名冲突,则文件名后加序号。
# 导入pyexiv2包
from pyexiv2 import Image
import os
import time
#文件路径
file_path = r'D:\\654\\123'
def SetNewTime(filename):
absfile = file_path + "\\\\" + filename
modifydate=os.path.getmtime(absfile)
timeStruct = time.localtime(modifydate)
exif_dict =
exif_dict['Exif.GPSInfo.GPSDateStamp']=time.strftime('%Y:%m:%d',timeStruct)
exif_dict['Exif.GPSInfo.GPSTimeStamp']=time.strftime('%H/1 %M/1 %S/1',timeStruct)
exif_dict['Exif.Photo.DateTimeOriginal']=time.strftime('%Y:%m:%d %H:%M:%S',timeStruct)
exif_dict['Exif.Photo.DateTimeDigitized']=time.strftime('%Y:%m:%d %H:%M:%S',timeStruct)
exif_dict['Exif.Image.DateTime']=time.strftime('%Y:%m:%d %H:%M:%S',timeStruct)
img = Image(absfile)
img.modify_exif(exif_dict)
os.utime(absfile, (modifydate, modifydate))
print("GPSDateStamp:" + exif_dict['Exif.GPSInfo.GPSDateStamp'])
print("GPSTimeStamp:" + exif_dict['Exif.GPSInfo.GPSTimeStamp'])
print("DateTime:" + time.strftime('%Y-%m-%d %H:%M:%S',timeStruct))
print("FileName:" + absfile)
print("----------------------------------")
def SetNewFileName(filename):
head = filename[0:4]
if (head == "IMG_"): #图片名不能含有中文,否则打不开图片
return
absfile = file_path + "\\\\" + filename
modifydate = os.path.getmtime(absfile)
timeStruct = time.localtime(modifydate)
datestr = time.strftime('IMG_%Y%m%d_%H%M%S',timeStruct)
absdstfile = file_path + "\\\\" + datestr + ".jpg"
newdatestr = datestr
count = 0
while 1:
try:
res = os.rename(absfile, absdstfile)
print("rename filename from " + filename + " to " + newdatestr + ".jpg")
break
except BaseException:
# 存在同名文件则添加序号
print("try filename " + absdstfile + " error")
count = count + 1
newdatestr = datestr + "_" + str(count)
absdstfile = file_path + "\\\\" + newdatestr + ".jpg"
def main():
#提取文件中的所有文件生成一个列表
folders = os.listdir(file_path)
filecount = 0
for file in folders:
#判断文件后缀名是否为jpg
if(file.split('.')[-1]=='jpg'):
filecount = filecount + 1
print("num:" + str(filecount) + " current file : " + file)
try:
filename=file_path+"\\\\"+file
img = Image(filename)
takendate = img.read_exif()['Exif.Photo.DateTimeOriginal']
except BaseException:
#没有拍摄日期信息
SetNewTime(file)
SetNewFileName(file)
if __name__ == '__main__':
main()
以上是关于python图像批量导入的主要内容,如果未能解决你的问题,请参考以下文章