opencv人脸打马赛克

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)
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值