Search code examples
numpydatasetsvmglobimage-recognition

HOG +SVM training with iniria dataset, TypeError: samples is not a numpy array, neither a scalar


I'm working on pedestrian detection with a team. I am trying to figure out an error that keeps showing up that says "TypeError: samples is not a numpy array, neither a scalar" which when appear points to the line of code that is svm.train(X_data, cv2.ml.ROW_SAMPLE, labels12)

i tried following dozens of online guides but i still couldn't solve the problem, and im also very new to this

import cv2
import numpy as np
from skimage import feature
from skimage import exposure
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# training

X_data = []
labels1 = []
label = []
files = glob.glob ("new_pos_1/crop*.PNG")
for myFile in files:
    # print(myFile)
    image = cv2.imread(myFile,)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    X_data.append (image)
    labels1.append('Pedestrian')


print('X_data shape:', np.array(X_data).shape)
labels12 = np.array([labels1])
print('labels12 shape:',np.array(labels12).shape)
print('labels shape:', np.array(labels1).shape)
#Testing
Y_data = []

files = glob.glob ("new_pos_1/person*.PNG")
for myFile in files:
    # print(myFile)
    image = cv2.imread (myFile)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    Y_data.append (image)
    label.append('Pedestrian')

print('Y_data shape:', np.array(Y_data).shape)

print('label shape:', np.array(label).shape)

hog_features = []
for image in np.array(X_data):
    (fd, hogImage) = feature.hog(image, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2),
                                    transform_sqrt=True, block_norm="L2-Hys", visualise=True)
    hogImage = exposure.rescale_intensity(hogImage, out_range=(0, 255))
    hogImage = hogImage.astype("uint8")
    hog_features.append(fd)

print("I'm done hogging")
print(hog_features)
svm = cv2.ml.SVM_create()
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setType(cv2.ml.SVM_C_SVC)
svm.setC(2.67)
svm.setGamma(5.383)
print("Done initializing SVM parameters")
# Train SVM on training data
svm.train(X_data, cv2.ml.ROW_SAMPLE, labels12)
print("Done trainning")
svm.save('svm_data.dat')
print("SAVED.")
#testResponse = svm.predict(testData)[1].ravel()
cv2.waitKey(0)

The line at the beginning that says labels12 = np.array([labels1]) i used to try and fix the error that showed up to no avail. This is the original website that helped me write this code: https://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial/


Solution

  • you should also do X_data2 = np.array([X_data]) and call svm.train(X_data2, cv2.ml.ROW_SAMPLE, labels12)