简体   繁体   English

将 CV2 Numpy 数组转换为 RGB 图像时出现“图像数据不足”错误

[英]"Not Enough Image Data" Error when Converting CV2 Numpy Array into RGB Image

In the code below, I am attempting to output a single face (cropped from a larger image) with CV2:在下面的代码中,我试图用 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)

With source being passed as a parameter into img src="{{source}}source作为参数传递给 img src="{{source}}

If I return the length of faces in an image with 3 faces, I get "3", so that seems to work nicely and if I return any index of faceSamples (eg faceSamples[0]), I get data returned as well, but when I try to turn that face sample into an image using ...如果我返回一张有 3 张脸的图像中的人脸长度,我会得到“3”,所以这似乎工作得很好,如果我返回 faceSamples 的任何索引(例如 faceSamples[0]),我也会得到返回的数据,但是当我尝试使用 ...

img = Image.fromarray(faceSamples[0], 'RGB')

I get a ValueError that there is "not enough image data"我收到“没有足够的图像数据”的 ValueError

I understand (from a previous answer) that detectMultiScale returns rectangles, not images, but with my additional Numpy code, is that still the case?我知道(从之前的答案中)detectMultiScale 返回矩形,而不是图像,但是使用我的附加 Numpy 代码,情况仍然如此吗? Am I still not fully understanding what the faceSamples array is returning?我还没有完全理解 faceSamples 数组返回的内容吗? Can this not be directly turned back into an RGB image with the last snippet of code?这不能用最后一段代码直接变回RGB图像吗?

Your problem is here:你的问题在这里:

pilImage=Image.open(full_path).convert('L')
imageNp=np.array(pilImage,'uint8')

That is, you converted imageNp into a single channel, gray image.也就是说,您将imageNp转换为单通道灰度图像。 Then it makes little sense to do那么这样做毫无意义

img = Image.fromarray(faceSamples[0], 'RGB')

as faceSamples[0] is also a gray image.因为faceSamples[0]也是一个灰度图像。

Also, like @MarkSetchell's comment, you can use cv2.imread and other functions instead of PIL .另外,就像@MarkSetchell 的评论一样,您可以使用cv2.imread和其他函数代替PIL They are more compatible with other openCV functions.它们与其他 openCV 函数更兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM