将需要提取的圖檔放在第一個檔案夾中
将需要生成的圖檔放在第二個檔案夾中
調整好路徑,直接運作即可
import cv2
import os
if __name__ == '__main__':
# print('catching your face and writting into disk...')
# read_directory("0/",100,"1/")
# read_directory('getTrainData', 0, 'C:/Users/Administrator/Desktop/x/no6/lufei2/X', 100)
# getTrainData('getTrainData', 0, './face_dataset/1/', 10)
directory_name=r"D:\pyproject\project1\BASfigure\1"
path_name=r"D:\pyproject\project1\BASfigure\0\0"
max_num=10
num = 0#記錄圖檔數量
for filename in os.listdir(directory_name):
# print(filename) # 僅僅是為了測試
img = cv2.imread(directory_name + "/" + filename)
#####顯示圖檔#######
# print(img)
# cv2.imshow(filename, img)
cap = cv2.imread(directory_name)
classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')
color = (0, 255, 0)
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰階化
faceRects = classifier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
# faceRects = cv2.re
# print(faceRects)
# print(len(faceRects))
if len(faceRects)>0:
for faceRect in faceRects:
x, y, w, h = faceRect
image_name = '%s%d.jpg' % (path_name, num) # 這裡為每個捕捉到的圖檔進行命名,每個圖檔按數字遞增命名。
image = img[y:y + h, x:x + w] # 将目前幀含人臉部分儲存為圖檔
image=cv2.resize(image,(128,128),interpolation = cv2.INTER_AREA)
# image_name2=(path_name + "/" +image_name)
# print(image_name)
# print(image)
cv2.imwrite(image_name, image)
# print(image_name)
# print(image)
num += 1
print(num)
# if num > max_num: # 如果超過指定最大儲存數量退出循環
# break
# cv2.rectangle(img, (x, y), (x + w, y + h), color, 2) # 畫出矩形框
# font = cv2.FONT_HERSHEY_SIMPLEX # 擷取内置字型
# cv2.putText(img, ('%d' % num), (x + 30, y + 30), font, 1, (255, 0, 255),
# 4) # 調用函數,對人臉坐标位置,添加一個(x+30,y+30)的矩形框用于顯示目前捕捉到了多少人臉圖檔
#
# # cv2.rectangle(img, (x, y), (x + w, y + h), color, 2) # 畫出矩形框
# if num>max_num:
# break
#
# # cv2.imshow(filename, img)
# c=cv2.waitKey(10)
# if c & 0xFF == ord('q'):
# break
# cv2.destroyAllWindows()