近期收到了電子工業出版社贈送的一本網絡安全書籍《python黑帽子》,書中一共24個實驗,今天復現第11個實驗(人臉識別),我的測試環境是mbp電腦+conda開發環境。這個實驗是緊接著上一個流量圖片還原的,而流量圖片還原可以接在中間人攻擊上,這樣就可以嗅探到目標正在浏覽什麼內容,比如說色情網站,從而為社會工程學欺詐勒索創造突破口~
1、先去網上隨便搜索若干張人臉圖片,本來打算全部放美女圖,這裡致敬一下行業大佬 @腹黑、@kn1f3
2、下載必備的xml配置文件
wget https://eclecti.cc/files/2008/03/haarcascade_frontalface_alt.xml
3、在mbp上運行腳本
4、在faces文件夾中查看人臉結果
參考代碼:
# -*- coding: utf-8 -*-
# @Time : 2022/6/13 7:36 PM
# @Author : ailx10
# @File : detector.py
import cv2
import os
ROOT = "/Users/ailx10/py3hack/chapter4/picture"
FACES = "/Users/ailx10/py3hack/chapter4/faces"
TRAIN = "/Users/ailx10/py3hack/chapter4/training"
def detect(srcdir=ROOT,tgtdir=FACES,train_dir=TRAIN):
for fname in os.listdir(srcdir):
if not fname.upper().endswith(".JPG"):
continue
fullname = os.path.join(srcdir,fname)
newname = os.path.join(tgtdir,fname)
img = cv2.imread(fullname)
if img is None:
continue
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
training = os.path.join(train_dir,"haarcascade_frontalface_alt.xml")
cascade = cv2.CascadeClassifier(training)
rects = cascade.detectMultiScale(gray,1.3,5)
try:
if rects.any():
print("Got a face")
rects[:,2:] += rects[:,:2]
except AttributeError:
print(f"No face found in {fname}")
continue
for x1,y1,x2,y2 in rects:
cv2.rectangle(img,(x1,y1),(x2,y2),(127,255,0),2)
cv2.imwrite(newname,img)
if __name__ == "__main__":
detect()