import cv2
def FaceFind(imgPath: str) -> list:
image = cv2.imread(imgPath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 返回人脸坐标列表
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 保存图片
# for (x, y, w, h) in faces:
# cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 3)
# cv2.imwrite('face.jpg', image)
return faces
def ApplyMosaic(ImagePath: str, BoxList: list):
# 加载原始图像
image = cv2.imread(ImagePath)
# 马赛克坐标
for box in BoxList:
(x, y, w, h) = box
# 从原始图片中获取马赛克图片位置
roi = image[y:y + h, x:x + w]
# 马赛克块大小 10x10
roi_small = cv2.resize(roi, (10, 10), interpolation=cv2.INTER_LINEAR)
roi_back = cv2.resize(roi_small, (w, h), interpolation=cv2.INTER_NEAREST)
image[y:y + h, x:x + w] = roi_back
cv2.imwrite('output_image.jpg', image)
def main():
# 图片路径
ImagePath = "img_2.png"
# 马赛克应用的区域
BoxList = FaceFind(ImagePath)
ApplyMosaic(ImagePath, BoxList)
if __name__ == '__main__':
main()
效果: