用叠加图像替换cv2人脸检测照片

Replacing cv2 face detection photo with overlayed image

我已经使用 cv2 从上传的图像中检测到我的眼睛,但我想在 cv2 检测到我的脸的地方粘贴一张图像。 View cv2 eye detection photo output here

但是我不想输出我眼睛周围的 cv2 矩形,而是想用图像替换它。 有没有办法将图像粘贴到 cv2 检测到我眼睛的位置?

我的python脚本

import os
import numpy as np
import cv2
from os.path import join, dirname, realpath
from flask import Flask, render_template, request, redirect, url_for, abort
from werkzeug.utils import secure_filename

def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save('new.png')
   
    face_cascade = cv2.CascadeClassifier('/haarcascade_eye.xml')
    eye_cascade = cv2.CascadeClassifier('/haarcascade_eye.xml')

    img = cv2.imread('new.png')
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
         cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
         roi_gray = gray[y:y+h, x:x+w]
         roi_color = img[y:y+h, x:x+w]
         eyes = eye_cascade.detectMultiScale(roi_gray)
         for (ex,ey,ew,eh) in eyes:
             cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
    cv2.imwrite("out.png", img)

请记住上面的脚本会产生这个 photo output。我想删除矩形并使用 cv2 将图像粘贴到 cv2 检测到我的眼睛的位置。

我认为这就是您要找的:

import os
import numpy as np
import cv2
from os.path import join, dirname, realpath

def upload_files():
   
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

    img = cv2.imread('face.jpg')
    img_to_place = cv2.imread('img.png')

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    gray_to_place = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    img_h, img_w = gray.shape
    img_to_place_h, img_to_place_w = gray_to_place.shape

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            resized_img = cv2.resize(img_to_place, (eh, ew), interpolation = cv2.INTER_AREA)
            resized_img_h, resized_img_w, _ = resized_img.shape

            roi_color[ey:ey+resized_img_h, ex:ex+resized_img_w, :] = resized_img

    cv2.imwrite('out.png', img)

upload_files()

基本上,您加载要放在眼睛中的图像,将其调整为 ROI 大小,然后将其放在矩形所在的坐标中。

示例: