import cv2 import numpy as np def face_detect_function(img): if len(img.shape) == 3: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) face_detect = cv2.CascadeClassifier( 'haarcascade_frontalface_default.xml') # 人脸识别分类器 face = face_detect.detectMultiScale(img) for x, y, w, h in face: cv2.rectangle(img, (x, y, w, h), color=(0, 0, 255), thickness=2) return img def removeBG(img, back): imgt = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) back = cv2.resize(back, (imgt.shape[1], imgt.shape[0])) if len(back.shape) == 3: back = cv2.cvtColor(back, cv2.COLOR_RGB2GRAY) bgModel = cv2.createBackgroundSubtractorMOG2(0, 50) img = cv2.bilateralFilter(img, 5, 50, 100) # smoothing filter fgmask = bgModel.apply(img, learningRate=0.01) kernel = np.ones((3, 3), np.uint8) fgmask = cv2.erode(fgmask, kernel, iterations=1) img = cv2.bitwise_and(img, img, mask=fgmask) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.GaussianBlur(gray, (41, 41), 0) _, img = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (17, 17), (-1, -1)) img = cv2.dilate(img, kernel, iterations=5) result = imgt & img img = ~img result = (back & img) + result result = cv2.GaussianBlur(result, (5, 5), 0) return result