ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

OpenCV 2.3 RC Python SVM: TypeError: <unknown> is not a numpy array

asked 2011-06-26 06:02:23 -0500

Pi Robot gravatar image

updated 2014-01-28 17:09:56 -0500

ngrennan gravatar image


I am trying to use the new cv2 SVM (Support Vector Machine) Python binding in OpenCV 2.3 RC. I compiled OpenCV from source under Ubuntu 10.04 and as soon as I execute this function:

svm = cv2.SVM(training_data, responses)

I get the error:

TypeError: <unknown> is not a numpy array

Does anyone know what I am doing wrong or how to fix this?

Here is the full function I am using to train the SVM. The variables self.positive_samples and self.negative_samples are Python lists of SURF feature vectors (64 elements long). The variable self.classes is a Python list of 1's and -1's indicating the class a sample belongs to.

def init_classifier(self):

    n_positive_samples = len(self.positive_samples)
    n_negative_samples = len(self.negative_samples)

    n_samples = n_positive_samples + n_negative_samples

    training_data = cv.CreateMat(n_samples, 64, cv.CV_32FC1)
    responses = cv.CreateMat(n_samples, 1, cv.CV_32FC1)

    for i in range(n_positive_samples):
        cv.Set2D(responses, i, 0, self.classes[i])
        for j in range(64):        
            cv.Set2D(training_data, i, j, self.positive_samples[i][j])

    for i in range(n_positive_samples, n_samples):
        i_negative = i - n_positive_samples
        cv.Set2D(responses, i, 0, self.classes[i_negative])
        for j in range(64):        
            cv.Set2D(training_data, i, j, self.negative_samples[i_negative][j])

    svm = cv2.SVM(training_data, responses)
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2011-06-26 11:57:25 -0500

Pi Robot gravatar image

updated 2011-06-26 11:57:46 -0500

OK, it only took me about 5 hours of trial and error to finally figure this out. Turns out the SVM class requires the training data to be of type numpy.float32. Since my training data was in regular Python arrays, I had to convert them like this:

training_data = np.array(python_training_data, dtype=np.float32)
responses = np.array(python_responses, dtype=np.float32)

Now all is well.


edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2011-06-26 06:02:23 -0500

Seen: 3,028 times

Last updated: Jun 26 '11