赞
踩
import base64 import cv2 def FaceFind(imgPath: str) -> list: image = cv2.imread(imgPath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # https://github.com/opencv/opencv/tree/4.x/data/haarcascades face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.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) # ret, buffer = cv2.imencode('.jpg', image) # if ret: # # 转base64 # base64_data = base64.b64encode(buffer).decode('utf-8') # print(base64_data) def main(): # 图片路径 ImagePath = "img_4.png" # 马赛克应用的区域 BoxList = FaceFind(ImagePath) if len(BoxList) > 0: ApplyMosaic(ImagePath, BoxList) else: print("没有识别到人脸,不做处理") if __name__ == '__main__': main()
效果:
2.用训练好的开源的模型(yolov)
地址:yolov8-face-landmarks-opencv-dnn
def FaceFindForYolov(ImagePath): # Initialize YOLOv8_face object detector face_detector = YOLOv8_face("weights/yolov8n-face.onnx", conf_thres=0.45, iou_thres=0.5) fqa = face_quality_assessment("weights/face-quality-assessment.onnx") if isinstance(ImagePath, str): srcimg = cv2.imread(ImagePath) else: srcimg = ImagePath # Detect Objects # boxes 人脸坐标 boxes, scores, classids, kpts = face_detector.detect(srcimg) return boxes def MosaicImage(urls): res = [] for url in urls: response = GetUrlImage(url) if response.status_code == 200 and len(response.content) > 0: image = cv2.imdecode(np.frombuffer(response.content, np.uint8), 1) # BoxList = FaceFind(image) # BoxList = FaceFindForBaidu(response.content) BoxList = FaceFindForYolov(image) if len(BoxList) > 0: handleUrl = ApplyMosaic(image, BoxList, url) res.append({"code": 1, "handleUrl": handleUrl, "msg": ""}) else: u_logger.logger.error("没有识别到人脸,不做处理:" + url) res.append({"code": 0, "handleUrl": "", "msg": "没有识别到人脸,不做处理"}) else: u_logger.logger.error("请求图片错误:" + url) res.append({"code": 0, "handleUrl": "", "msg": "请求图片错误"}) return res if __name__ == '__main__': res = MosaicImage([ "https://img2.baidu.com/it/u=1503000758,3469202397&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1067"]) print(res)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。