目錄
系統總體
思路
- 選擇分類文件夾
- 選擇要分類的已知人物圖片
- 爲分類人物命名新文件夾
- 將人物圖片與要分類文件夾下的每張圖進行比對
- 比對成功將圖片移入分類人物文件夾
- 容錯設置(暫時想到的錯誤已經進行處理,未發現的錯誤會寫入error.txt文件裏)
整體代碼
# #!/usr/bin/env python
# # -*- coding: utf-8 -*-
# # @Time : 2020/02/23 20:21
# # @Author : Cxk
# # @File : face_info.py
import face_recognition
import os
import shutil
from tkinter import *
from tkinter.messagebox import *
from tkinter import filedialog
import threading
def recognition(known_image,unknown_image):
try:
results=[]
face_encoding = face_recognition.face_encodings(known_image)[0]
# print("face_encoding :{}".format(unknown_face_encoding))
#獲取每個圖像文件中每個面部的面部編碼
#由於每個圖像中可能有多個面,所以返回一個編碼列表。
unknown_face=face_recognition.face_encodings(unknown_image)
for i in range(len(unknown_face)):
known_faces = [face_encoding]
# #結果是True/false的數組,未知面孔known_faces陣列中的任何人相匹配的結果
results = face_recognition.compare_faces(known_faces, unknown_face[i])
# print(results)
if results[0]==True:
break
else:
continue
return results
except Exception as e:
cuowu="shibie "+str(e)
with open('error.txt','a') as file_handle: # .txt可以不自己新建,代碼會自動新建
file_handle.write(cuowu) # 寫入
file_handle.write('\n')
def cxk(path,path2,image):
#已知人物的圖片
known_image = face_recognition.load_image_file(image)
# unknow_image = face_recognition.load_image_file("0.jpg")
# print(shibie(know_image,unknow_image))
# path=os.getcwd()+"\未知"
# path2=os.getcwd()+"\陳赫"
old_name=os.listdir(path)
for i in old_name:
try:
name =os.path.join(path,i)
unknown_image = face_recognition.load_image_file(name)
if recognition(known_image,unknown_image)[0]==True:
shutil.move(name, path2)
else:
pass
except Exception as e:
cuowu="cxk "+str(e)
with open('error.txt','a') as file_handle: # .txt可以不自己新建,代碼會自動新建
file_handle.write(cuowu) # 寫入
file_handle.write('\n')
class Rootpage(object):
def __init__(self, master=None):
self.root = master
winWidth = 400
winHeight = 400
screenWidth = self.root.winfo_screenwidth()
screenHeight = self.root.winfo_screenheight()
x = int((screenWidth - winWidth) / 2)
y = int((screenHeight - winHeight) / 2)
# 設置窗口初始位置在屏幕居中
self.root.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
# 設置窗口圖標
# root.iconbitmap("./image/icon.ico")
# 設置窗口寬高固定
self.root.resizable(0, 0)
self.name = StringVar()
self.Folderpath=""
self.Filepath=""
self.createPage()
def createPage(self):
Label(root,font=("微軟雅黑", 20),text="").pack()
Label(root,font=("微軟雅黑", 20),text="").pack()
Button(root,text='選擇文件夾', bd =5,command=self.open_fold).pack()
Button(root,text='選擇圖片', bd =5,command=self.open_file).pack()
Label(root,font=("微軟雅黑", 20),text="請輸入該人物名稱").pack()
entry=Entry(root,font="Helvetica 13 bold", bd =5,width=8,textvariable=self.name).pack()
Button(root,text='開啓分類', bd =5,command=self.fun).pack()
def open_fold(self):
self.Folderpath = filedialog.askdirectory() #獲得選擇好的文件夾
old_name=os.listdir(self.Folderpath)
if old_name==[]:
showinfo(title='錯誤', message='你所選擇的文件夾爲空,請重新選擇!')
else:
Label(root,font=("微軟雅黑", 10),text=self.Folderpath).pack()
def open_file(self):
self.Filepath = filedialog.askopenfilename() #獲得選擇好的文件
try:
known_image = face_recognition.load_image_file(self.Filepath)
face_encoding = face_recognition.face_encodings(known_image)[0]
except:
showinfo(title='錯誤', message='你所選擇的圖片無人臉信息,請重新選擇!')
else:
Label(root,font=("微軟雅黑", 10),text=self.Filepath).pack()
def start(self):
name=self.name.get()
if name=="" or self.Folderpath=="" or self.Filepath=="":
showinfo(title='錯誤', message='請檢查是否選擇文件夾或者圖片又或者名字是否爲空!')
else:
showinfo(title='提示', message='後臺分類已開始\n請稍等,完成後將會有提示!')
path2=os.path.abspath(os.path.join(self.Folderpath,".."))#返回上一目錄
path2=path2+"\%s"%name
if not os.path.exists(path2):#判斷一個目錄是否存在
os.makedirs(path2)
cxk(self.Folderpath,path2,self.Filepath)
os.startfile(path2)
showinfo(title='提示', message='分類已完成,已爲你打開該人物文件夾!')
def fun(self):
th=threading.Thread(target=self.start)
th.setDaemon(True)#守護線程
th.start()
if __name__ == "__main__":
root = Tk()
root.title('依據人臉分類圖片')
Rootpage(root)
root.mainloop()
附帶一鍵百度關鍵詞圖片下載(源碼忘了在那本書上的了)
圖片下載模塊忘了在那本書看到的了,有知道的說一下我備註一下作者,文件批量重命名自個加的,可以直接加在spidler函數內的,沒去整了。
# -*- coding:utf-8 -*-
import requests,os #首先導入庫
import re
#設置默認配置
MaxSearchPage = 20 # 收索頁數
CurrentPage = 0 # 當前正在搜索的頁數
NeedSave = 0 # 是否需要儲存
folder_path = ''#文件保存位置
#圖片鏈接正則和下一頁的鏈接正則
def imageFiler(content):# 通過正則獲取當前頁面的圖片地址數組
return re.findall('"objURL":"(.*?)"',content,re.S)
def nextSource(content): # 通過正則獲取下一頁的網址
next = re.findall('<div id="page">.*<a href="(.*?)" class="n">',content,re.S)[0]
return next
#爬蟲主體
def spidler(source):
content = requests.get(source).text # 通過鏈接獲取內容
imageArr = imageFiler(content) # 獲取圖片數組
global CurrentPage
for imageUrl in imageArr:
global NeedSave
if NeedSave: # 如果需要保存圖片則下載圖片,否則不下載圖片
global DefaultPath
try:
# 下載圖片並設置超時時間,如果圖片地址錯誤就不繼續等待了
picture = requests.get(imageUrl,timeout=10)
except:
continue
# 創建圖片保存的路徑
imageUrl = imageUrl.replace('/','').replace(':','').replace('?','')
pictureSavePath = imageUrl
fp = open(os.path.join(folder_path,pictureSavePath),'wb') # 以寫入二進制的方式打開文件
fp.write(picture.content)
fp.close()
global MaxSearchPage
if CurrentPage <= MaxSearchPage: #繼續下一頁爬取
if nextSource(content):
CurrentPage += 1
# 爬取完畢後通過下一頁地址繼續爬取
spidler("http://image.baidu.com" + nextSource(content))
#爬蟲的開啓方法
def beginSearch(key,page):
"""
page搜索頁面,數字上加兩頁就是實際搜索頁面,列如page=-1,實際搜索頁面爲一頁
"""
global MaxSearchPage,NeedSave,folder_path
MaxSearchPage = page
NeedSave = 1 #是否保存,值0不保存,1保存
folder_path=key+"/"
if os.path.exists(folder_path) == False:
os.makedirs(folder_path)
StartSource = "http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=" + str(key) + "&ct=201326592&v=flip" # 分析鏈接可以得到,替換其`word`值後面的數據來搜索關鍵詞
spidler(StartSource)
print("完成!")
def rename(name):
"""
# beginSearch("周冬雨",-1)
# 1.os.name——判斷現在正在實用的平臺,Windows 返回 ‘nt'; Linux ...
# 2.os.getcwd()——得到當前工作的目錄。
# 3.os.remove()——刪除指定文件
# 4.os.rmdir()——刪除指定目錄 刪除文件夾,不好演示,自己試一下
# 5.os.mkdir()——創建目錄 就是在指定目錄新建一個文件夾
"""
beginSearch(name,-1)#下載圖片
path=os.getcwd()+"\%s"%name
old_name=os.listdir(path)
# print(old_name)
new_name=[]
j=0
for i in old_name:
new_name.append(str(j))
j+=1
# print(new_name)
for x, y in zip(old_name, new_name):
os.renames(path+"\%s"%x,path+"\%s.jpg"%y)
print("已改名!")
a=os.listdir(path)
print(a)
rename("周冬雨")
總結
- face_recognition有自帶的文件夾分類的,此次屬於重複造輪子,算是個人界面版
- 很多細節已經有註釋
- 還有我不是標題黨,哈哈哈,做這個還真是爲了整理跟女朋友這幾年的照片。
- 對了,我女票是周冬雨。
- 其餘不多說了,有興趣探討的留言或私信,博客只是用來記錄,以後不會花太多時間在分享細節上