如何修复pycharm中的此错误? cv2.error:OpenCV(3.4.2)错误:(-215:断言失败)

时间:2019-04-13 15:48:49

标签: python opencv

我是python和opencv的新手,我想从输入图像中裁剪面部图像。我真的不知道哪里出了问题,有人可以帮助我修复它吗?

我认为输入图像的目录可能有问题。因此,我将所有的“ /”更改为“ \”,但这仍然不正确。此外,在此目录下,有许多子文件夹,并且在每个子文件夹中都有一些原始图像。

import cv2
import os


def fetch_face_pic(img,face_cascade):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize = (30, 30), flags = 0)

    for(x, y, w, h) in faces:
        crop = img[y:y+h, x:x+w]
    return crop


face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_defalut.xml')

#path_save = '/Users/oysdfx/Desktop/Face-anti-spoofing-master/crop/ImposterCrop'
path_read = '/Users/oysdfx/Desktop/Face-anti-spoofing-master/raw/ImposterRaw'

for file in os.listdir(path_read):
    pic = os.path.join(path_read, file)
    img = cv2.imread(pic)
    crop = fetch_face_pic(img, face_cascade)

    resized_img = cv2.resize(img, (64, 64), interpolation=cv2.INTER_CUBIC)
    cv2.imwrite(pic, resized_img)

实际上,我想从输入图像中裁剪出面孔,并将其保存在新文件夹中。我不知道该怎么实现。我运行这段代码,并得到如下错误:

Traceback (most recent call last):
  File "/Users/oysdfx/Desktop/Undergraduate_Thesis/Face_Anti-Spoofing/crop_face.py", line 86, in <module>
    crop = fetch_face_pic(img, face_cascade)
  File "/Users/oysdfx/Desktop/Undergraduate_Thesis/Face_Anti-Spoofing/crop_face.py", line 70, in fetch_face_pic
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(3.4.2) /opt/concourse/worker/volumes/live/9523d527-1b9e-48e0-7ed0-a36adde286f0/volume/opencv-suite_1535558719691/work/modules/imgproc/src/color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'CvtHelper'


Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

这与您的IDE PyCharm无关。您的图像路径可能是错误的。继续前进之前,请检查img是否为None。如果是这样,请打印路径(pic),您会发现它是错误的。

# [...]

for file in os.listdir(path_read):
    pic = os.path.join(path_read, file)
    img = cv2.imread(pic)
    if img is None:
        raise Exception('Invalid image: {}'.format(pic))
    crop = fetch_face_pic(img, face_cascade)

# [...]