k2 = image.shape[1]/image.shape[0] if k2 < k1: resized = imutils.resize(image, height = height) zeros = np.zeros((height, width - resized.shape[1])) #zeros = zeros + 255 image = np.concatenate((resized, zeros), axis=1) else: resized = imutils.resize(image, width = width) zeros = np.zeros((height - resized.shape[0], width)) #zeros = zeros + 255 image = np.concatenate((resized, zeros), axis=0) #image = imutils.rotate_bound(results, 90) image = image/255.0 image = [image] image = iap.preprocess(image) predict = model.predict([[image]]) predict = np.argmax(predict, axis=2) #print(len(predict)) res = fastdecode(predict, dic) string = string + res + ' ' if mark: print(string)
testGen.close() testGen = HDF5DatasetGenerator(config.TEST_HDF5, 64, preprocessors=[mp], classes=2) predictions = [] widgets = [ "Evaluating: ", progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA() ] pbar = progressbar.ProgressBar(maxval=testGen.numImages // 64, widgets=widgets).start() for (i, (images, labels)) in enumerate(testGen.generator(passes=1)): for image in images: crops = cp.preprocess(image) crops = np.array([iap.preprocess(c) for c in crops], dtype='float32') pred = model.predict(crops) predictions.append(pred.mean(axis=0)) pbar.update(i) pbar.finish() print("[INFO] predicting on test data (with crops) ...") (rank1, _) = rank5_accuracy(predictions, testGen.db["labels"]) print("[INFO] rank-1: {:.2f}%".format(rank1 * 100)) testGen.close()
frame = imutils.resize(frame, width=800) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) clone = frame.copy() # detect faces in grayscale image rects = detector(gray, 1) # loop over face detections for rect in rects: # align faces face = fa.align(frame, gray, rect) # resize and crop image age_crops = cp.preprocess(age_mp.preprocess(sp.preprocess(face))) age_crops = np.array([iap.preprocess(c) for c in age_crops]) gender_crops = cp.preprocess(gender_mp.preprocess(sp.preprocess(face))) gender_crops = np.array([iap.preprocess(c) for c in gender_crops]) # predict on age and gender based on extracted crops age_pred = age_model.predict(age_crops).mean(axis=0) gender_pred = gender_model.predict(gender_crops).mean(axis=0) # draw bounding box around face x, y, w, h = face_utils.rect_to_bb(rect) cv2.rectangle(clone, (x, y), (x + w, y + h), (0, 255, 0), 2) clone = agh.visualize_video(age_pred, gender_pred, age_le, gender_le, clone, (x, y))
predictions = [] # initialize the progress bar widgets = ["Evaluating: ", progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA()] pbar = progressbar.ProgressBar(maxval=testGen.numImages // 64, widgets=widgets).start() # loop over a single pass of the test data for (i, (images, labels)) in enumerate(testGen.generator(passes=1)): # loop over each of the individual images for image in images: # apply the crop preprocessor to the image to generate 10 # separate crops, then convert them from images to arrays crops = cp.preprocessor(image) crops = np.array([iap.preprocess(c) for c in crops], dtype="float32") # make predictions on the crops and then average them # together to obtain the final prediction pred = model.predict(crops) predictions.append(pred.mean(axis=0)) # update the progress bar pbar.update(i) # compute the rank-1 accuracy pbar.finish() print("[INFO] predicting on test data (with crops)...") (rank1, _) = rank5_accuracy(predictions, testGen.db["labels"]) print("[INFO] rank-1: {:.2f}%".format(rank1*100))
genderMeans["B"]) iap = ImageToArrayPreprocessor() # load a sample of testing images rows = open(config.TEST_MX_LIST).read().strip().split("\n") rows = np.random.choice(rows, size=args["sample_size"]) # loop over the rows for row in rows: # unpack the row (_, gtLabel, imagePath) = row.strip().split("\t") image = cv2.imread(imagePath) # pre-process the image, one for the age model and another for # the gender model ageImage = iap.preprocess(ageMP.preprocess( sp.preprocess(image))) genderImage = iap.preprocess(genderMP.preprocess( sp.preprocess(image))) ageImage = np.expand_dims(ageImage, axis=0) genderImage = np.expand_dims(genderImage, axis=0) # pass the ROIs through their respective models agePreds = ageModel.predict(ageImage)[0] genderPreds = genderModel.predict(genderImage)[0] # sort the predictions according to their probability ageIdxs = np.argsort(agePreds)[::-1] genderIdxs = np.argsort(genderPreds)[::-1] # visualize the age and gender predictions ageCanvas = AgeGenderHelper.visualizeAge(agePreds, ageLE)
# patches from it face = sp.preprocess(face) patches = cp.preprocess(face) # allocate memory for the age and gender patches agePatches = np.zeros((patches.shape[0], 3, 227, 227), dtype="float") genderPatches = np.zeros((patches.shape[0], 3, 227, 227), dtype="float") # loop over the patches for j in np.arange(0, patches.shape[0]): # perform mean subtraction on the patch agePatch = ageMP.preprocess(patches[j]) genderPatch = genderMP.preprocess(patches[j]) agePatch = iap.preprocess(agePatch) genderPatch = iap.preprocess(genderPatch) # update the respective patches lists agePatches[j] = agePatch genderPatches[j] = genderPatch # make predictions on age and gender based on the extracted # patches agePreds = ageModel.predict(agePatches) genderPreds = genderModel.predict(genderPatches) # compute the average for each class label based on the # predictions for the patches agePreds = agePreds.mean(axis=0) genderPreds = genderPreds.mean(axis=0)
def main(): """Evaluate AlexNet on Cats vs. Dogs """ # load the RGB means for the training set means = json.loads(open(config.DATASET_MEAN).read()) # initialize the image preprocessors simple_preprocessor = SimplePreprocessor(227, 227) mean_preprocessor = MeanPreprocessor(means["R"], means["G"], means["B"]) crop_preprocessor = CropPreprocessor(227, 227) image_to_array_preprocessor = ImageToArrayPreprocessor() # load the pretrained network print("[INFO] loading model...") model = load_model(config.MODEL_PATH) # initialize the testing dataset generator, then make predictions on the testing data print("[INFO] predicting on test data (no crops)...") test_gen = HDF5DatasetGenerator(config.TEST_HDF5, 64, preprocessors=[ simple_preprocessor, mean_preprocessor, image_to_array_preprocessor ], classes=2) predictions = model.predict_generator(test_gen.generator(), steps=test_gen.num_images // 64, max_queue_size=10) # compute the rank-1 and rank-5 accuracies (rank1, _) = rank5_accuracy(predictions, test_gen.database["labels"]) print("[INFO] rank-1: {:.2f}%".format(rank1 * 100)) test_gen.close() # re-initialize the testing set generator, this time excluding the `SimplePreprocessor` test_gen = HDF5DatasetGenerator(config.TEST_HDF5, 64, preprocessors=[mean_preprocessor], classes=2) predictions = [] # initialize the progress bar widgets = [ "Evaluating: ", progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA() ] progress_bar = progressbar.ProgressBar(maxval=test_gen.num_images // 64, widgets=widgets).start() # loop over a single pass of the test data # passes=1 to indicate the testing data only needs to be looped over once for (i, (images, _)) in enumerate(test_gen.generator(passes=1)): # loop over each of the individual images for image in images: # apply the crop preprocessor to the image to generate 10 # separate crops, then convert them from images to arrays crops = crop_preprocessor.preprocess(image) crops = np.array( [image_to_array_preprocessor.preprocess(c) for c in crops], dtype="float32") # make predictions on the crops and then average them # together to obtain the final prediction pred = model.predict(crops) predictions.append(pred.mean(axis=0)) # update the progress bar progress_bar.update(i) # compute the rank-1 accuracy progress_bar.finish() print("[INFO] predicting on test data (with crops)...") (rank1, _) = rank5_accuracy(predictions, test_gen.database["labels"]) print("[INFO] rank-1: {:.2f}%".format(rank1 * 100)) test_gen.close()
sp = AspectAwarePreprocessor(width=224, height=224) mp = MeanPreprocessor(config.R_MEAN, config.G_MEAN, config.B_MEAN) iap = ImageToArrayPreprocessor(dataFormat="channels_first") # loop over the testing images for row in rows: # grab the target class label and the image path from the row (target, imagePath) = row.split("\t")[1:] target = int(target) # load the image from disk and pre-process it by resizing the # image and applying the pre-processors image = cv2.imread(imagePath) orig = image.copy() orig = imutils.resize(orig, width=min(500, orig.shape[1])) image = iap.preprocess(mp.preprocess(sp.preprocess(image))) image = np.expand_dims(image, axis=0) # classify the image and grab the indexes of the top-5 predictions preds = model.predict(image)[0] idxs = np.argsort(preds)[::-1][:5] # show the true class label print("[INFO] actual={}".format(le.inverse_transform(target))) # format and display the top predicted class label label = le.inverse_transform(idxs[0]) label = label.replace(":", " ") label = "{}: {:.2f}%".format(label, preds[idxs[0]] * 100) cv2.putText(orig, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)