Ошибка неподдерживаемого типа изображения в детекторе dlib

У меня есть изображения в моей папке img / datasets / нейтральный, некоторые изображения серые, а некоторые - BGR, поэтому, когда я попытался определить лицевой ориентир с помощью dlib, я получил ошибку.

Ошибка обнаружения = детектор (изображение, 1)
RuntimeError: Неподдерживаемый тип изображения, должно быть 8-битное серое или изображение RGB.

Я думаю, что эта ошибка связана с тем, что некоторые изображения имеют оттенки серого, а другие - BGR. Я пытался использовать try and except, но это не сработало.

Как я могу убрать эту ошибку?

скрипт Python

emotions = ['neutral', 'sad', 'happy', 'anger']

data={}
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
clf = SVC(kernel='linear', probability=True, tol=1e-3)

def get_files(emotion):
    files = glob.glob('img\\datasets\\%s\\*' %emotion)
    random.shuffle(files)
    training = files[:int(len(files)*0.8)]
    prediction = files[-int(len(files)*0.2)]
    return training, prediction

def get_landmarks(image):
detections = detector(image, 1)
for k, d in enumerate(detections):  # For all detected face instances individually
    shape = predictor(image, d)  # Draw Facial Landmarks with the predictor class
    xlist = []
    ylist = []
    for i in range(1, 68):  # Store X and Y coordinates in two lists
        xlist.append(float(shape.part(i).x))
        ylist.append(float(shape.part(i).y))

    xmean = np.mean(xlist)
    ymean = np.mean(ylist)
    xcentral = [(x - xmean) for x in xlist]
    ycentral = [(y - ymean) for y in ylist]

    landmarks_vectorised = []
    for x, y, w, z in zip(xcentral, ycentral, xlist, ylist):
        landmarks_vectorised.append(w)
        landmarks_vectorised.append(z)
        meannp = np.asarray((ymean, xmean))
        coornp = np.asarray((z, w))
        dist = np.linalg.norm(coornp - meannp)
        landmarks_vectorised.append(dist)
        landmarks_vectorised.append((math.atan2(y, x) * 360) / (2 * math.pi))

    data['landmarks_vectorised'] = landmarks_vectorised
if len(detections) < 1:
    data['landmarks_vestorised'] = "error"


def make_sets():
training_data = []
training_labels = []
prediction_data = []
prediction_labels = []

for emotion in emotions:
    print("Working on %s emotion" %emotion)
    training, prediction = get_files(emotion)

    for item in training:
        image = cv2.imread(item)
        try:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        except:
            print()
        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
        clahe_image = clahe.apply(image)
        get_landmarks(clahe_image)

        if data['landmarks_vectorised'] == "error":
            print("no face detected on this one")
        else:
            training_data.append(data['landmarks_vectorised'])  # append image array to training data list
            training_labels.append(emotions.index(emotion))


    for item in prediction:
        image = cv2.imread(item)
        try:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        except:
            print()
        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
        clahe_image = clahe.apply(image)
        get_landmarks(clahe_image)

        if data['landmarks_vectorised'] == "error":
            print("no face detected on this one")
        else:
            prediction_data.append(data['landmarks_vectorised'])
            prediction_labels.append(emotions.index(emotion))

return training_data, training_labels, prediction_data, prediction_labels

accur_lin = []

for i in range(0,10):
    print("Making sets %s" % i)  # Make sets by random sampling 80/20%
    training_data, training_labels, prediction_data, prediction_labels = make_sets()

    npar_train = np.array(training_data)
    npar_trainlabs = np.array(training_labels)
    print("training SVM linear %s" % i)  # train SVM
    clf.fit(npar_train, training_labels)

    print("getting accuracies %s" % i)
    npar_pred = np.array(prediction_data)
    pred_lin = clf.score(npar_pred, prediction_labels)

print("Mean value lin svm: %s" % np.mean(accur_lin))

person Vikas Gautam    schedule 04.01.2018    source источник
comment
Пожалуйста, начните с публикации кода с правильным отступом. | Думаю, эта ошибка связана с тем, что вы проверили свою гипотезу? Готов поспорить, что это неверно, поскольку значение по умолчанию для второго параметра imread - IMREAD_COLOR, что означает всегда преобразовывать изображение в трехканальное цветное изображение BGR. Итак, какое значение image действительно вызывает эту ошибку?   -  person Dan Mašek    schedule 05.01.2018
comment
да вы пишете, я проверил, поместив только полутоновые изображения в нейтральную папку. но я не знаю, какое изображение вызывает эту проблему. все изображения 640x490.   -  person Vikas Gautam    schedule 05.01.2018
comment
Я использую cv2.imread (item, 0), но получаю ту же ошибку.   -  person Vikas Gautam    schedule 05.01.2018
comment
и все изображения в формате .png   -  person Vikas Gautam    schedule 05.01.2018
comment
Ошибка исправлена, эта ошибка возникла из-за неправильного пути для предсказания в get_files (эмоция).   -  person Vikas Gautam    schedule 05.01.2018
comment
:) Ага, часто бывает. Вы должны добавить тест, чтобы убедиться, что cv2.imread прошел успешно - если он не прошел, он вернет None. Что-то вроде if image is None: и, как минимум, заставить его выводить какое-нибудь значимое сообщение об ошибке.   -  person Dan Mašek    schedule 05.01.2018


Ответы (1)


вот поправка

def get_files(emotion):
    files = glob.glob('img\\datasets\\%s\\*' %emotion)
    random.shuffle(files)
    training = files[:int(len(files)*0.8)]
    prediction = files[-int(len(files)*0.2)]       #change this line to prediction=files[-int(len(files)*0.2):]   so that rest 20% files can be accessed
    return training, prediction
person Vikas Gautam    schedule 04.01.2018