在下面的代码中,我尝试使用 CV2 输出单个人脸(从较大的图像裁剪):
def machine_pst():
mlimg = request.files.get("mlimg")
fname = mlimg.filename
filepath = "/home/assets/faces/"
mlimg.save(filepath + fname, overwrite = True)
full_path = filepath + fname
cascPath = "/home/assets/haarcascade_frontalface_default.xml"
detector = cv2.CascadeClassifier(cascPath)
faceSamples=[]
pilImage=Image.open(full_path).convert('L')
imageNp=np.array(pilImage,'uint8')
faces=detector.detectMultiScale(imageNp)
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
img = Image.fromarray(faceSamples[0], 'RGB')
cv2.imwrite("/home/assets/faces/read.png", img)
source = "/static/faces/read.png"
return template("home/machineout", source = source)
将源作为参数传递到 img src="{{source}}
如果我返回具有 3 张面孔的图像中的人脸长度,我会得到"3",所以这似乎工作得很好,如果我返回任何 faceSamples 索引(例如 faceSamples[0]),我也会收到返回的数据,但是当我尝试将该人脸样本转换为图像时使用......
img = Image.fromarray(faceSamples[0], 'RGB')
我收到一个值错误,指出"没有足够的图像数据"
我知道(从之前的答案中)检测MultiScale 返回矩形,而不是图像,但使用我的附加 Numpy 代码,情况仍然如此吗?我仍然不完全理解 faceSamples 数组返回的内容吗?这不能用最后一段代码直接变回RGB图像吗?
你的问题在这里:
pilImage=Image.open(full_path).convert('L')
imageNp=np.array(pilImage,'uint8')
也就是说,您将imageNp
转换为单通道灰色图像。那么这样做就没有什么意义了
img = Image.fromarray(faceSamples[0], 'RGB')
因为faceSamples[0]
也是灰色图像。
此外,就像@MarkSetchell的评论一样,您可以使用cv2.imread
和其他功能代替PIL
。它们与其他 openCV 函数更兼容。