整理旧照片时存在因为更换设备重命名以及手机随手拍的没有意义照片,排序整理时比较费劲,想着弄一个代码,通过重命名写上日期大小,是否有人脸等信息,进行预判。
近半年因生活与工作原因没有碰代码,太多东西都忘记了。
import os
import time
import cv2
import numpy as np
#根据文件路径反馈文件大小与创建日期
def file_stat(path):
path_stat = os.stat(path)
#时间格式转换
time_ymd = time.strftime("%Y%m%d%H%M%S",time.localtime(path_stat.st_mtime))
#print('文件:',path,'大小:',path_stat.st_size,'字节,文件创建时间:',time_ymd)
return time_ymd,round(path_stat.st_size/1024)
#人脸识别与眼睛识别
def Face_comparison(path):
#print('Face_comparison_path',path)
img = cv2.imdecode(np.fromfile(path, dtype=np.uint8),1)
#人脸
faceCascade = cv2.CascadeClassifier("C:/Users/HONOR/anaconda3/envs/pytorch/Library/etc/haarcascades/haarcascade_frontalface_default.xml")
#眼睛
faceCascade_eye = cv2.CascadeClassifier("C:/Users/HONOR/anaconda3/envs/pytorch/Library/etc/haarcascades/haarcascade_eye.xml")
faces = faceCascade.detectMultiScale(img,1.15)
faces_eye = faceCascade_eye.detectMultiScale(img,1.15)
#print('faces',len(faces),'faces_eye',len(faces_eye))
# if len(faces) == 0 and len(faces_eye) == 0:
# print('图片中无人脸识别信息',path)
# else:
# print('图片中有人脸识别信息',path)
#将人脸数与眼睛数返回
return len(faces),len(faces_eye)
#获取文件夹下
tuples = os.walk('D:\\家庭影像留念')
print('tuples',tuples)
hz_list =[]
i = 0
for tuple_os in tuples:
path_y = tuple_os[0]
for tuple_o in tuple_os:
for tuple_s in tuple_o:
tuple_text = os.path.splitext(tuple_s)
if tuple_text[1] != '':
hz_list.append(tuple_text[1].upper())
join_os = os.path.join(path_y,tuple_s)
file_time,file_size = file_stat(os.path.abspath(join_os))
if tuple_text[1].upper() in ('.JPG','.PNG','.JPEG'):
#照片的话识别人脸情况
faces,faces_eye = Face_comparison(join_os)
if faces > 0:
faces = 1
if faces_eye > 0:
faces_eye = 1
#faces, faces_eye = 1, 0
else:
faces, faces_eye = 0, 0
#print(join_os,file_time,file_size,faces, faces_eye)
#print(tuple_text[1].upper(),tuple_text[1].upper()[1:2])
new_name = tuple_text[1].upper()[1:2] +str(faces) + str(faces_eye) +'_'+ file_time + '_' + str(file_size) + tuple_text[1].upper()
#print('old',join_os,'new_name',path_y +'\\'+ new_name )
#文件重命名
if os.path.exists(join_os):
os.rename(join_os, path_y +'\\'+ new_name)
i += 1
#print(join_os,'重名',new_name)
else:
print(join_os, '文件未找到')
print('处理文件数:',i)
#计算共有多少个文件
print(len(hz_list))
for i in set(hz_list):
print(i,'文件个数:',hz_list.count(i))