error: (-215:Assertion failed) samples.cols == var_count && samples.type() == CV_32F in function 'cv::ml::SVMImpl::predict'

51 views Asked by At

I'm trying to test my trained model from svm & lbph for face recognition and here's the error

An error occurred while processing image Test/image1.png: OpenCV(4.8.0) D:\a\opencv-python\opencv-python\opencv\modules\ml\src\svm.cpp:2013: error: (-215:Assertion failed) samples.cols == var_count && samples.type() == CV_32F in function 'cv::ml::SVMImpl::predict'

This is my code : file svmLBPH.py :

import cv2
import numpy as np
from skimage.feature import local_binary_pattern

class LBPH_SVM_Recognizer():
    def __init__(self, max_iter= 100, epsilon = 0.001, C= 100, Gamma = 0.001) :
        self.svm = cv2.ml.SVM_create()
        self.svm.setKernel(cv2.ml.SVM_CHI2)
        self.svm.setType(cv2.ml.SVM_C_SVC)
        self.svm.setTermCriteria((cv2.TERM_CRITERIA_MAX_ITER, max_iter, epsilon))
        self.svm.setC(C)
        self.svm.setGamma(Gamma)

        self.face_histogram = []
        self.y = []

    def find_lbp_histogram(self, image, P=8, R=1, eps=1e-7, n_window=(8,8)):
        E = []
        h, w = image.shape
        h_sz = int(np.floor(h/n_window[0]))
        w_sz = int(np.floor(w/n_window[1]))
        lbp_img = local_binary_pattern(image, P=P, R=R, method="default")
        for (x, y, C) in self.sliding_window(lbp_img, stride=(h_sz, w_sz), window=(h_sz, w_sz)):
            if C.shape[0] != h_sz or C.shape[1] != w_sz:
                continue
            H = np.histogram(C,                          
                             bins=2**P, 
                             range=(0, 2**P),
                             density=True)[0] 
            E.extend(H)
        return E
    
    def sliding_window(self, image, stride, window):
        for y in range(0, image.shape[0], stride[0]):
            for x in range(0, image.shape[1], stride[1]):
                yield (x, y, image[y:y + window[1], x:x + window[0]])
                   

    def train(self, x, y):
        self.y = y
        # Convert histogram matrix into feature vectors
        self.face_histograms = [self.find_lbp_histogram(img) for img in x]
        hist_mat = np.array(self.face_histograms, dtype=np.float32)
        hist_mat = hist_mat.reshape(len(hist_mat), -1)  # Merubah matriks histogram menjadi satu baris
        self.svm.train(hist_mat, cv2.ml.ROW_SAMPLE, y)

    
    def predict(self, x):
        hists = [self.find_lbp_histogram(img) for img in x]
        hist_mat = np.array(hists, dtype=np.float32)
        ret, idx = self.svm.predict(hist_mat, True)
        confidence = 1.0 / (1.0 + np.exp(-ret)) # convert retVal to confidence level (0-1) sigmoid
        return idx, confidence ```

file trainModelSVMLBPH.ipynb :
# Load your trained LBPH_SVM model
lbph_svm_model = LBPH_SVM_Recognizer()
lbph_svm_model.svm.load("../ServerTeleBot/lbph_svm_model_v1.yml")

# Initialize the face cascade classifier
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')

# Directory containing test images
direktori_test = "Test/"

# Loop through all .png files in the test directory
for filename in os.listdir(direktori_test):
    if filename.endswith(".png"):
        gambar_path = os.path.join(direktori_test, filename)
        try:
            # Load the test image
            frame = cv2.imread(gambar_path)

            if frame is not None:
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                gray = gray.astype(np.uint8)  # Convert to uint8 type
                lbp_img = local_binary_pattern(gray, P=8, R=1, method="default")
                faces = face_cascade.detectMultiScale(gray, 1.1, 5)
                for (x, y, w, h) in faces:
                    face_img = gray[y:y+h, x:x+w]
                    face_img = cv2.resize(face_img, (100, 100))

                    # Ensure that the data type is CV_32F and reshape as needed
                    hist = face_img.ravel()
                    hist = np.float32(hist).reshape(1, -1)

                    # Perform the prediction using your trained LBPH_SVM model
                    idx, confidence = lbph_svm_model.predict([hist])

                    # Convert the predicted index to a label
                    label_kelas = labels[int(idx[0])]

                    # Display the test image with predicted class and confidence
                    plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
                    plt.title(f"Predicted Class: {label_kelas}, Confidence: {confidence[0]:.2f}")
                    plt.axis('off')
                    plt.show()
                else:
                    print("Failed to load the test image:", gambar_path)
        except Exception as e:
            print(f"An error occurred while processing image {gambar_path}: {str(e)}")
                    
cv2.destroyAllWindows()

The image in the list directory is not thrown an exception, and the image can be recognized.

0

There are 0 answers