最近在做人臉識別,需要對人臉數據集進行處理,對一張或批量圖像的人臉進行切割分離,並且另保存下來。受網上開源工具的啓發,在借鑑他人的基礎上進行了改進,使得更加方便實用。
以下代碼是改進版,分爲兩部分功能:
- 一張人臉圖片切割並顯示,不保存
- 一張/批量人臉圖像切割並保存
在這裏需要申明一下,尊重原著!(轉發需要標註一下原著信息)
原創版:
Author: coneypo
Blog: http://www.cnblogs.com/AdaminXie
GitHub: https://github.com/coneypo/Dlib_face_cut
改進版:
Improver: Cai_90hou
Blog: https://blog.csdn.net/qq_38677310/article/details/84702662
Github:
#crop_faces_show.py
import dlib # 人臉識別的庫dlib
import numpy as np # 數據處理的庫numpy
import cv2 # 圖像處理的庫OpenCv
# Dlib 正向人臉檢測器
detector = dlib.get_frontal_face_detector()
# 讀取圖像
path = "faces_for_test/"
img = cv2.imread(path+"test_faces_1.jpg")
# Dlib 檢測
dets = detector(img, 1)
print("檢測到的人臉數 / faces :", len(dets), "\n")
# 記錄人臉矩陣大小
height_max = 0
width_sum = 0
# 計算要生成的圖像 img_blank 大小
for k, d in enumerate(dets):
# 計算矩形大小
# (x,y), (寬度width, 高度height)
pos_start = tuple([d.left(), d.top()])
pos_end = tuple([d.right(), d.bottom()])
# 計算矩形框大小
height = d.bottom()-d.top()
width = d.right()-d.left()
# 處理寬度
width_sum += width
# 處理高度
if height > height_max:
height_max = height
else:
height_max = height_max
# 繪製用來顯示人臉的圖像的大小
print("窗口大小:"
, '\n', "高度 / height :", height_max
, '\n', "寬度 / width : ", width_sum)
# 生成用來顯示的圖像
img_blank = np.zeros((height_max, width_sum, 3), np.uint8)
# 記錄每次開始寫入人臉像素的寬度位置
blank_start = 0
# 將人臉填充到img_blank
for k, d in enumerate(dets):
height = d.bottom()-d.top()
width = d.right()-d.left()
# 填充
for i in range(height):
for j in range(width):
img_blank[i][blank_start+j] = img[d.top()+i][d.left()+j]
# 調整圖像
blank_start += width
cv2.namedWindow("img_faces", 0)
cv2.imshow("img_faces", img_blank)
cv2.waitKey(0)
#crop_faces_save.py
import dlib # 人臉識別的庫dlib
import numpy as np # 數據處理的庫numpy
import cv2 # 圖像處理的庫OpenCv
import os
#切割後的人臉序號,爲全局變量
image_num = 0
# Dlib 正向人臉檢測器
detector = dlib.get_frontal_face_detector()
# 讀取圖像的路徑
path_read = "faces_for_test/"
#img = cv2.imread(path_read+"test_faces_3.jpg")
# 用來存儲生成的單張人臉的路徑
path_save = "faces_separated/"
#將文件夾中待處理的圖片存於列表中
imgs_read = os.listdir(path_read) #源地址文件夾
imgs_write = os.listdir(path_save) #存儲地址文件夾
# Delete old images
def clear_images():
for img in imgs_write:
os.remove(path_save + img)
print("clean finish", '\n')
#處理一張圖片:
def cut_one_photo(img):
global image_num
# Dlib 檢測
faces = detector(img, 1)
print("人臉數:", len(faces))
for k, d in enumerate(faces):
# 計算矩形大小
# (x,y), (寬度width, 高度height)
pos_start = tuple([d.left(), d.top()])
pos_end = tuple([d.right(), d.bottom()])
# 計算矩形框大小
height = d.bottom()-d.top()
width = d.right()-d.left()
# 根據人臉大小生成空的圖像
img_blank = np.zeros((height, width, 3), np.uint8)
#複製人臉
for i in range(height):
for j in range(width):
img_blank[i][j] = img[d.top()+i][d.left()+j]
# cv2.imshow("face_"+str(k+1), img_blank)
# 保存在本地
#print("Save to:", path_save+"CWH"+str(image_num+1)+".jpg")
print("Save to:", "img_face" + str(image_num + 1) + ".jpg")
cv2.imwrite(path_save + "img_face" + str(image_num + 1) + ".jpg", img_blank)
image_num += 1
#批量處理圖片
def cut_batch_photoes():
clear_images() #清除原有圖片
for img in imgs_read:
try:
path = os.path.join(path_read, img)
image = cv2.imread(path)
cut_one_photo(image)
print('\n')
except:
continue
print('Successful operation!\n')
print('total number of faces: ', image_num)
def main():
# 批量處理圖片並保存
cut_batch_photoes()
if __name__ == '__main__':
main()