error: ValueError: object arrays are not supported

asked 2016-11-06 01:55:15 -0600

hilal gravatar image

updated 2016-11-06 02:31:51 -0600

berak gravatar image

Hi I am new to open Cv and Python :) I try to run my script with python 2.7 and 2.4.13 openCV my script:

#****************************************************
# -*- coding: utf-8 -*-

import cv2
import numpy as np
import os
import sys
from scipy.cluster.vq import *

def get_all_files_dir(path):
    return [os.path.join(path, file) for file in os.listdir(path)]

class StatModel(object):
    def load(self, fn):
        self.model.load(fn)
    def save(self, fn):
        self.model.save(fn)

class SVM(StatModel):
    def __init__(self):
        self.model = cv2.SVM()

    def train(self, samples, responses,cParam):

        params = dict( kernel_type = cv2.SVM_LINEAR, 
                       svm_type = cv2.SVM_C_SVC
                       ,C = cParam )

        self.model.train(samples, responses, params = params)

    def predict(self, samples):
        return np.float32( [self.model.predict(sample) for sample in samples])


def predictImages(inputPath,outputPath):

    Path = inputPath
    tst_descriptors = []
    image_paths_test =get_all_files_dir(Path)
    for image_path in image_paths_test:
        image = cv2.imread(image_path)
        keypoints = featureDetector.detect(image)   
        keypoints, descriptor = descriptorExtractor.compute(image, keypoints)
        tst_descriptors.append((image_path, descriptor))   

    descriptors = tst_descriptors[0][1]
    for image_path, descriptor in tst_descriptors[0:]:
        descriptors = np.vstack((descriptors, descriptor)) 

    test_features = np.zeros((len(image_paths_test), k), "float32")
    for i in xrange(len(image_paths_test)):
        print i
        print vocab == None
        print tst_descriptors[i][1] == None
        #print len(tst_descriptors)
        #print tst_descriptors[i][1].shape
        #print vocab.shape

        words, distance = vq(tst_descriptors[i][1],vocab)
        for word in words:
            test_features[i][word] += 1
        #normalize
        test_features[i] = test_features[i] = test_features[i]/ np.linalg.norm(test_features[i])

    predictions =  [classes_names[int(cls)] for cls in clf.predict(test_features)]
    with open(outputPath+"\ClassOutput.txt","w") as text_file:
       text_file.writelines(img + " : " + cls + "\n" for img,cls in zip(image_paths, predictions))



if len(sys.argv) != 4:
    print("Run the script as follows: python CV2.py <TrainingImagesPath> <TestImagesPath> <textOutputPath>")
    print("TrainingImagesPath should have two folders inside, one with positive examples and one with negative examples")
    print("I.E. Face and NotFace - same naming as the classes")
    sys.exit()


training_folder_path = sys.argv[1]
test_input_path = sys.argv[2]
outputPath = sys.argv[3]
classes_names = os.listdir(training_folder_path)


matcher = cv2.DescriptorMatcher_create("FlannBased")
featureDetector = cv2.FeatureDetector_create("SIFT")
descriptorExtractor = cv2.DescriptorExtractor_create("SIFT")



image_paths = []
image_classes = []
class_id = 0
for training_name in classes_names:
    dir = os.path.join(training_folder_path, training_name)
    class_path = get_all_files_dir(dir)
    image_paths+=class_path
    image_classes+=[class_id]*len(class_path)
    class_id+=1

listOfDescriptors = []
for image_path in image_paths:
    image = cv2.imread(image_path)
    keypoints = featureDetector.detect(image)
    keypoints, descriptor = descriptorExtractor.compute(image, keypoints)
    listOfDescriptors.append((image_path, descriptor))   

descriptors = listOfDescriptors[0][1]
for image_path, descriptor in listOfDescriptors[1:]:
    descriptors = np.vstack((descriptors, descriptor))  

#K-Means
k = 80
vocab, variance = kmeans(descriptors, k, 1) 
#Histograms
image_features = np.zeros((len(image_paths), k), "float32")
for i in xrange(len(image_paths)):
    words, distance = vq(listOfDescriptors[i][1],vocab)
    for word in words:
        image_features[i][word] += 1
    #normalize 
    image_features[i] = image_features[i]/ np.linalg.norm(image_features[i])

clf = SVM()
clf.train(image_features, np.array(image_classes),4)

predictImages(test_input_path,outputPath)

print("Done. Check input directory for text file.")
#*****************************************************

I run the script like this:

python CV2.py <TrainingImagesPath> <TestImagesPath> <textOutputPath>

and I got the error :

n [1]: runfile('C:/Users/hilalham/Desktop/cv/CV2/CV2.py', args='C:/Users/hilalham ...
(more)
edit retag flag offensive close merge delete