i've been working this weeks in a gender recognition project (in python) using at first: Fisherfaces as Feature Extraction method and 1-NN classifier with Euclidean Distance but now i though it was not enough reliable (in my humble opinion) so i'm about to use SVM but im lost when i have to create and train a model to use it in my dataset of images, but i can't find the solution for the commands i need in http://scikit-learn.org. I've tried with this code but it doesn't work, dunno why i have this error while executing:
File "prueba.py", line 46, in main
clf.fit(R, r)
File "/Users/Raul/anaconda/lib/python2.7/site-packages/sklearn/svm/base.py", line 139, in fit
X = check_array(X, accept_sparse='csr', dtype=np.float64, order='C')
File "/Users/Raul/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py", line 350, in check_array
array.ndim)
ValueError: Found array with dim 3. Expected <= 2
And this is my code:
import os, sys
import numpy as np
import PIL.Image as Image
import cv2
from sklearn import svm
def read_images(path, id, sz=None):
c = id
X,y = [], []
for dirname, dirnames, filenames in os.walk(path):
for subdirname in dirnames:
subject_path = os.path.join(dirname, subdirname)
for filename in os.listdir(subject_path):
try:
im = Image.open(os.path.join(subject_path, filename))
im = im.convert("L")
# resize to given size (if given)
if (sz is not None):
im = im.resize(sz, Image.ANTIALIAS)
X.append(np.asarray(im, dtype=np.uint8))
y.append(c)
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
#c = c+1
return [X,y]
def main():
# check arguments
if len(sys.argv) != 3:
print "USAGE: example.py </path/to/images/males> </path/to/images/females>"
sys.exit()
# read images and put them into Vectors and id's
[X,x] = read_images(sys.argv[1], 1)
[Y, y] = read_images(sys.argv[2], 0)
# R all images and r all id's
[R, r] = [X+Y, x+y]
clf = svm.SVC()
clf.fit(R, r)
if __name__ == '__main__':
main()
I'd appreciate any kind of help in how can i make gender recognition with SVM Thanks for reading
X.append(np.asarray(im, dtype=np.uint8))
I guess this is appending a 2d-array. You might want to flatten it before appending so that each instance becomes this looking:
array([255, 255, 255, ..., 255, 255, 255], dtype=uint8)
instead of:
array([
[255, 255, 255, ..., 255, 255, 255],
[255, 255, 255, ..., 255, 255, 255],
[255, 0, 0, ..., 0, 0, 0],
...,
[255, 0, 0, ..., 0, 0, 0],
[255, 255, 255, ..., 255, 255, 255],
[255, 255, 255, ..., 255, 255, 255]], dtype=uint8)
Try this:
X.append(np.asarray(im, dtype=np.uint8).ravel())