Home > Back-end >  cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument)
cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument)

Time:08-26

I'm doing a course now and I was typing the codes of the tutor to the Python file. However, I got an error. I want to say that the tutor didn't had any errors. The link of the video is this (go to the part "Face Rcognition with OpenCV's built-in recognizer"). I'm new to OpenCV and couldn't find why this error appears.

The error I got is:

Traceback (most recent call last):
  File "c:/Users/Ad/Desktop/OpenCV/faces_train.py", line 33, in <module>
    create_train()
  File "c:/Users/Ad/Desktop/OpenCV/faces_train.py", line 24, in create_train
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'cvtColor'
 Overload resolution failed:
  > - src is not a numpy array, neither a scalar
  > - Expected Ptr<cv::UMat> for argument 'src'

The code I wrote is:

import os
import cv2 as cv
import numpy as np

people = ['Ben Affleck', 'Elton John', 'Jerry Seinfield', 'Madonna', 'Mindy Kaling']
DIR = r'C:\Users\Ad\Desktop\OpenCV\Faces'

haar_cascade = cv.CascadeClassifier('haatcascade_frontalface_default.xml')

features = []
labels = []

def create_train():
    for person in people:
        path = os.path.join(DIR, person)

        label = people.index(person)

        for img in os.listdir(path):

            img_path = os.path.join(path, img)
            img_array = cv.imread(img_path)

            gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

            faces_rect = cv.detectMultiScale(gray, scaleFactor = 1.1, minNeighbours = 4)

            for (x,y,w,h) in faces_rect:
                faces_roi = gray[y:y h, x:x w]
                features.append(faces_roi)
                labels.append(label)

create_train()
print('Training done------------------------')

features = np.array(features, dtype = 'object')
labels = np.array(labels)

face_recognizer = cv.face.LBPHFaceRecognizer_create()


face_recognizer.train(features, labels)

np.save('features.npy', features)
np.save('labels.npy', labels)

CodePudding user response:

You are not passing the numpy array of the image to the cv2.cvt_color()

Just pass the numpy array and it should work with you:

gray = cv.cvtColor(img_array, cv.COLOR_BGR2GRAY)

  • Related