Ask Your Question
0

Training and Test images must be of equal size

asked 2017-06-16 00:00:48 -0600

beta gravatar image

I'm trying to do face recognition for my project similar to this. But I need to detect it in a video. So I'm taking a video (Friends Video) and take some images from this video for training purpose. I'm using the following code to get the frames:

import cv2
vidcap = cv2.VideoCapture('pathToFolder/Friends - Bad monkey, Hot girls and Phoebe saves the monkey.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:
  success,image = vidcap.read()
  print('Read a new frame: ', success)
  cv2.imwrite("pathToFolder/Friends/frame%d.jpg" % count, image)     # save frame as JPEG file
  count += 1

And then running the following code:

import cv2, sys, numpy, os
size = 3
#fn_haar = 'haarcascade_frontalface_default.xml'
fn_dir = 'pathToFolder/Friends_Train'

# Part 1: Create fisherRecognizer
print('Training...')

# Create a list of images and a list of corresponding names
(images, lables, names, id) = ([], [], {}, 0)

# Get the folders containing the training data
for (subdirs, dirs, files) in os.walk(fn_dir):

    # Loop through each folder named after the subject in the photos
    for subdir in dirs:
        names[id] = subdir
        subjectpath = os.path.join(fn_dir, subdir)

        # Loop through each photo in the folder
        for filename in os.listdir(subjectpath):

            # Skip non-image formates
            f_name, f_extension = os.path.splitext(filename)
            if(f_extension.lower() not in
                    ['.png','.jpg','.jpeg','.gif','.pgm']):
                print("Skipping "+filename+", wrong file type")
                continue
            path = subjectpath + '/' + filename
            lable = id

            # Add to training data
            images.append(cv2.imread(path, 0))
            lables.append(int(lable))
        id += 1
(im_width, im_height) = (112, 92)

# Create a Numpy array from the two lists above
(images, lables) = [numpy.array(lis) for lis in [images, lables]]

# OpenCV trains a model from the images
# NOTE FOR OpenCV2: remove '.face'
model = cv2.face.createFisherFaceRecognizer()
model.train(images, lables)




# Part 2: Use fisherRecognizer on camera stream
haar_cascade = cv2.CascadeClassifier('C:/opencv-3.2.0/data/haarcascades/haarcascade_frontalface_default.xml')

webcam = cv2.VideoCapture('pathToFolder/Friends - Bad monkey, Hot girls and Phoebe saves the monkey.mp4')
while True:

    # Loop until the camera is working
    rval = False
    while(not rval):
        # Put the image from the webcam into 'frame'
        (rval, frame) = webcam.read()
        if(not rval):
            print("Failed to open webcam. Trying again...")

    # Flip the image (optional)
    #frame=cv2.flip(frame,1,0)

    # Convert to grayscalel
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Resize to speed up detection (optinal, change size above)
    mini = cv2.resize(gray, (int(gray.shape[1] / size), int(gray.shape[0] / size)))

    # Detect faces and loop through each one
    faces = haar_cascade.detectMultiScale(mini)
    for i in range(len(faces)):
        face_i = faces[i]

        # Coordinates of face after scaling back by `size`
        (x, y, w, h) = [v * size for v in face_i]
        face = gray[y:y + h, x:x + w]
        face_resize = cv2.resize(face, (im_width, im_height))

        # Try to recognize the face
        prediction = model.predict(face_resize)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)

        # [1]
        # Write the name of recognized face
        cv2.putText(frame,
           '%s - %.0f' % (names[prediction[0]],prediction[1]),
           (x-10, y-10), cv2.FONT_HERSHEY_PLAIN,1,(0, 255, 0))

    # Show the image and check ...
(more)
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2017-06-16 00:13:01 -0600

berak gravatar image

it's exactly, what the error says: you have to resize both your train and test images.

so, before appending your trainimages:

        # Add to training data
        face = cv2.imread(path, 0)  ## you should check..
        face_resize = cv2.resize(face, (im_width, im_height))
        images.append(face_resize)
edit flag offensive delete link more

Comments

1

Thanks Berak! Your answer solved the problem.Thanks a lot!

beta gravatar imagebeta ( 2017-06-16 01:38:23 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-06-16 00:00:48 -0600

Seen: 4,681 times

Last updated: Jun 16 '17