从函数传递和接收图像

Passing and Receiving Images from Function

我正在创建一个函数(在 Python 中)expects/receives 多张人脸 [=18] 的单个图像 =],以及 returns 多个较小的图像 (每个人脸一张图像)。我可以在函数内部执行 cv2.imshow 并看到预期的较小图像,但是当我尝试从函数外部执行 cv2.imshow 时,它不起作用(无法看到较小的图像,并得到一个 TypeError 代替)。希望得到一些指导。

def stills(user_image):

    #sub_frames = []
    fqp_image_src = (user_image)
    raw_pic = cv2.imread(fqp_image_src)
    mpic = cv2.resize(raw_pic,(0,0), fx=0.30, fy=0.30)
    mpic_rgb = cv2.cvtColor(mpic, cv2.COLOR_BGR2RGB)
    face_boxes = haar_cascade_face.detectMultiScale(mpic_rgb, scaleFactor = 1.2, minNeighbors = 5)
    count = int(len(face_boxes))
    for i in range(count):
        face_box = face_boxes[i]
        final = cv2.rectangle(mpic, (face_box[0], face_box[1]), ((face_box[0]+face_box[2]),(face_box[1]+face_box[3])), (0,255,0),2)
        sub_frame = final[face_box[1]:(face_box[1]+face_box[3]), face_box[0]:(face_box[0]+face_box[2])]
        #sub_frames.append(sub_frame)
        cv2.imshow('frame', sub_frame)      # this works
        cv2.waitKey()
    return (sub_frame, final)

# calling the function
something = stills("abc.jpg")
cv2.imshow('frame',something)               # this does not work
cv2.waitKey()

类型错误:参数 'mat'

应为 cv::UMat

这将达到您的预期,只是进行了一些简化并提供了完整的文件路径 . 一个关键错误是给 detectMultiScale 一张彩色图像,输入应该有 1 维,带有亮度(灰度)。

为了在方框中显示带有人脸的彩色图像,需要将图像的副本转换为 gar 比例并进行检测,给出坐标以在彩色图像中绘制。

import cv2
import os

# Take as a global the dir in witch is this file
PATH = os.path.dirname(os.path.abspath(__file__))

haar_cascade_face = cv2.CascadeClassifier(os.path.join(PATH, 'haarcascade_frontalface_alt.xml'))


def stills(user_image):
    image = os.path.join(PATH, user_image)
    image = cv2.imread(image)
    image = cv2.resize(image, (0, 0), fx=0.30, fy=0.30)

    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    face_boxes = haar_cascade_face.detectMultiScale(gray_image, scaleFactor=1.073, minNeighbors=8)

    final = image  # make the funtion alwais give a image
    sub_frames = []

    # Check if there are faces
    if len(face_boxes) > 0:
        for x, y, w, h in face_boxes:
            final = cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

            sub_frame = image[y:y+h, x:x+w]
            sub_frames.append([x, y, x+w, y+h])

            cv2.imshow('sub_frame', sub_frame)
            # cv2.waitKey() # No need to wait the user
    else:
        print('No faces found')

    return (sub_frames, final)


if __name__ == '__main__':
    fragments, final = stills("abc.jpg")
    cv2.imshow('frame', final)
    cv2.waitKey()