Python 从函数传递和接收图像
我正在用Python创建一个函数,该函数期望/接收其中多个人脸的单个图像,并返回多个较小的图像,每个人脸一个图像。我能够在函数内部执行cv2.imshow并看到预期的较小图像,但当我尝试从函数外部执行cv2.imshow时,它无法工作,无法看到较小的图像,而是出现TypeError。希望您能提供一些指导Python 从函数传递和接收图像,python,opencv3.0,Python,Opencv3.0,我正在用Python创建一个函数,该函数期望/接收其中多个人脸的单个图像,并返回多个较小的图像,每个人脸一个图像。我能够在函数内部执行cv2.imshow并看到预期的较小图像,但当我尝试从函数外部执行cv2.imshow时,它无法工作,无法看到较小的图像,而是出现TypeError。希望您能提供一些指导 def stills(user_image): #sub_frames = [] fqp_image_src = (user_image) raw_pic = cv2.
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()
TypeError:参数'mat'应为cv::UMat这将实现您所期望的,只是经过一些简化和完整的文件路径 . 其中一个关键错误是给检测多尺度彩色图像,输入应为一维,具有明亮的灰度 为了在方框中显示带有人脸的彩色图像,需要将图像的副本转换为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()
函数返回一个元组。试试这个:什么,@honglei