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

问题描述 投票:-2回答:1

我是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
python opencv
1个回答
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)

# [...]
© www.soinside.com 2019 - 2024. All rights reserved.