Ask Your Question

Revision history [back]

error: ValueError: object arrays are not supported

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/Desktop/cv/CV2/trainImg C:/Users/hilalham/Desktop/cv/CV2/testImg C:/Users/hilalham/Desktop/cv/CV2/output.txt', wdir='C:/Users/hilalham/Desktop/cv/CV2') 0 False True C:/Users/hilalham/Desktop/cv/CV2/CV2.py:55: FutureWarning: comparison to None will result in an elementwise object comparison in the future. print vocab == None Traceback (most recent call last):

File "<ipython-input-1-a2fc42f81ed6>", line 1, in <module> runfile('C:/Users/hilalham/Desktop/cv/CV2/CV2.py', args='C:/Users/hilalham/Desktop/cv/CV2/trainImg C:/Users/hilalham/Desktop/cv/CV2/testImg C:/Users/hilalham/Desktop/cv/CV2/output.txt', wdir='C:/Users/hilalham/Desktop/cv/CV2')

File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile execfile(filename, namespace)

File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc)

File "C:/Users/hilalham/Desktop/cv/CV2/CV2.py", line 128, in <module> predictImages(test_input_path,outputPath)

File "C:/Users/hilalham/Desktop/cv/CV2/CV2.py", line 61, in predictImages words, distance = vq(tst_descriptors[i][1],vocab)

File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\scipy\cluster\vq.py", line 210, in vq obs = _asarray_validated(obs, check_finite=check_finite)

File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\scipy_lib_util.py", line 231, in _asarray_validated raise ValueError('object arrays are not supported')

ValueError: object arrays are not supported

any one who can help, please?

click to hide/show revision 2
No.2 Revision

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

berak gravatar image

error: ValueError: object arrays are not supported

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)]

os.listdir(path)] class StatModel(object): def load(self, fn): self.model.load(fn) def save(self, fn): self.model.save(fn)

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

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):

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>") <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()

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)

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

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

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-Means k = 80 vocab, variance = kmeans(descriptors, k, 1)

Histograms

#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])

np.linalg.norm(image_features[i]) clf = SVM() clf.train(image_features, np.array(image_classes),4)

predictImages(test_input_path,outputPath)

np.array(image_classes),4) predictImages(test_input_path,outputPath) print("Done. Check input directory for text file.")

*****************

file.") #*****************************************************

I run the script like this: this:

python CV2.py <trainingimagespath> <testimagespath> <textoutputpath>

<TrainingImagesPath> <TestImagesPath> <textOutputPath>

and I got the error :

n [1]: runfile('C:/Users/hilalham/Desktop/cv/CV2/CV2.py', args='C:/Users/hilalham/Desktop/cv/CV2/trainImg C:/Users/hilalham/Desktop/cv/CV2/testImg C:/Users/hilalham/Desktop/cv/CV2/output.txt', wdir='C:/Users/hilalham/Desktop/cv/CV2')
0
False
True
C:/Users/hilalham/Desktop/cv/CV2/CV2.py:55: FutureWarning: comparison to None `None` will result in an elementwise object comparison in the future.
  print vocab == None
Traceback (most recent call last):

last): File "<ipython-input-1-a2fc42f81ed6>", line 1, in <module> runfile('C:/Users/hilalham/Desktop/cv/CV2/CV2.py', args='C:/Users/hilalham/Desktop/cv/CV2/trainImg C:/Users/hilalham/Desktop/cv/CV2/testImg C:/Users/hilalham/Desktop/cv/CV2/output.txt', wdir='C:/Users/hilalham/Desktop/cv/CV2')

wdir='C:/Users/hilalham/Desktop/cv/CV2') File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile execfile(filename, namespace)

namespace) File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc)

loc) File "C:/Users/hilalham/Desktop/cv/CV2/CV2.py", line 128, in <module> predictImages(test_input_path,outputPath)

predictImages(test_input_path,outputPath) File "C:/Users/hilalham/Desktop/cv/CV2/CV2.py", line 61, in predictImages words, distance = vq(tst_descriptors[i][1],vocab)

vq(tst_descriptors[i][1],vocab) File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\scipy\cluster\vq.py", line 210, in vq obs = _asarray_validated(obs, check_finite=check_finite)

check_finite=check_finite) File "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\scipy_lib_util.py", "C:\Users\hilalham\AppData\Local\Continuum\Anaconda2\lib\site-packages\scipy\_lib\_util.py", line 231, in _asarray_validated raise ValueError('object arrays are not supported')

supported') ValueError: object arrays are not supported

supported

any one who can help, please?