|
| 1 | +% Copyright (c) 2015, MathWorks, Inc. |
| 2 | + |
| 3 | +%% Download and and predict using a pretrained ImageNet model |
| 4 | + |
| 5 | +% Download from MatConvNet pretrained networks repository |
| 6 | +urlwrite('http://www.vlfeat.org/matconvnet/models/imagenet-vgg-f.mat', 'imagenet-vgg-f.mat'); |
| 7 | +cnnModel.net = load('imagenet-vgg-f.mat'); |
| 8 | + |
| 9 | +% Setup up MatConvNet, modify the path if it's installed in a different |
| 10 | +% folder |
| 11 | +run(fullfile('matconvnet-1.0-beta15','matlab','vl_setupnn.m')); |
| 12 | + |
| 13 | +% Load and display an example image |
| 14 | +imshow('dog_example.png'); |
| 15 | +img = imread('dog_example.png'); |
| 16 | + |
| 17 | +% Predict label using ImageNet trained vgg-f CNN model |
| 18 | +label = cnnPredict(cnnModel,img); |
| 19 | +title(label,'FontSize',20) |
| 20 | + |
| 21 | +%% Load images from folder |
| 22 | + |
| 23 | +% Use imageSet to manage images stored in multiple folders |
| 24 | +imset = imageSet('pet_images','recursive'); |
| 25 | + |
| 26 | +% Preallocate arrays with fixed size for prediction |
| 27 | +imageSize = cnnModel.net.normalization.imageSize; |
| 28 | +trainingImages = zeros([imageSize sum([imset(:).Count])],'single'); |
| 29 | + |
| 30 | +% Load and resize images for prediction |
| 31 | +for ii = 1:numel(imset) |
| 32 | + for jj = 1:imset(ii).Count |
| 33 | + trainingImages(:,:,:,jj) = imresize(single(read(imset(ii),jj)),imageSize(1:2)); |
| 34 | + end |
| 35 | +end |
| 36 | + |
| 37 | +% Get the image labels directly from the ImageSet object |
| 38 | +trainingLabels = getImageLabels(imset); |
| 39 | +summary(trainingLabels) |
| 40 | + |
| 41 | +%% Extract features using pretrained CNN |
| 42 | + |
| 43 | +% Depending on how much memory you have on your GPU you may use a larger |
| 44 | +% batch size. We have 400 images, I'm going to choose 200 as my batch size |
| 45 | +cnnModel.info.opts.batchSize = 200; |
| 46 | + |
| 47 | +% Make prediction on a CPU |
| 48 | +[~, cnnFeatures, timeCPU] = cnnPredict(cnnModel,trainingImages,'UseGPU',false); |
| 49 | +% Make prediction on a GPU |
| 50 | +[~, cnnFeatures, timeGPU] = cnnPredict(cnnModel,trainingImages,'UseGPU',true); |
| 51 | + |
| 52 | +% Compare the performance increase |
| 53 | +bar([sum(timeCPU),sum(timeGPU)],0.5) |
| 54 | +title(sprintf('Approximate speedup: %2.00f x ',sum(timeCPU)/sum(timeGPU))) |
| 55 | +set(gca,'XTickLabel',{'CPU','GPU'},'FontSize',18) |
| 56 | +ylabel('Time(sec)'), grid on, grid minor |
| 57 | + |
| 58 | +%% Train a classifier using extracted features and calculate CV accuracy |
| 59 | + |
| 60 | +% Train and validate a linear support vector machine (SVM) classifier. |
| 61 | +classifierModel = fitcsvm(cnnFeatures, trainingLabels); |
| 62 | + |
| 63 | +% 10 fold crossvalidation accuracy |
| 64 | +cvmdl = crossval(classifierModel,'KFold',10); |
| 65 | +fprintf('kFold CV accuracy: %2.2f\n',1-cvmdl.kfoldLoss) |
| 66 | + |
| 67 | +%% Object Detection |
| 68 | +% Use findPet function that was automatically generated using the |
| 69 | +% Image Region Analyzer App |
| 70 | + |
| 71 | +%% Tying the workflow together |
| 72 | +frameNumber = 0; |
| 73 | +vr = VideoReader(fullfile('PetVideos','videoExample.mov')); |
| 74 | +vw = VideoWriter('test.avi','Motion JPEG AVI'); |
| 75 | +opticFlow = opticalFlowFarneback; |
| 76 | +open(vw); |
| 77 | +while hasFrame(vr) |
| 78 | + % Count frames |
| 79 | + frameNumber = frameNumber + 1; |
| 80 | + |
| 81 | + % Step 1. Read Frame |
| 82 | + videoFrame = readFrame(vr); |
| 83 | + |
| 84 | + % Step 2. Detect ROI |
| 85 | + vFrame = imresize(videoFrame,0.25); % Get video frame |
| 86 | + frameGray = rgb2gray(vFrame); % Convert to gray for detection |
| 87 | + bboxes = findPet(frameGray,opticFlow); % Find bounding boxes |
| 88 | + if ~isempty(bboxes) |
| 89 | + img = zeros([imageSize size(bboxes,1)]); |
| 90 | + for ii = 1:size(bboxes,1) |
| 91 | + img(:,:,:,ii) = imresize(imcrop(vFrame,bboxes(ii,:)),imageSize(1:2)); |
| 92 | + end |
| 93 | + |
| 94 | + % Step 3. Recognize object |
| 95 | + % (a) Extract features using a CNN |
| 96 | + [~, scores] = cnnPredict(cnnModel,img,'UseGPU',true,'display',false); |
| 97 | + |
| 98 | + % (b) Predict using a trained Classifier |
| 99 | + label = predict(classifierModel,scores); |
| 100 | + |
| 101 | + % Step 4. Annotate object |
| 102 | + vFrame = insertObjectAnnotation(vFrame,'Rectangle',bboxes,cellstr(label),'FontSize',40); |
| 103 | + end |
| 104 | + |
| 105 | + % Step 5. Write video to file |
| 106 | + writeVideo(vw,videoFrame); |
| 107 | + |
| 108 | +% fprintf('Frame: %d of %d\n',frameNumber,ceil(vr.FrameRate*vr.Duration)); |
| 109 | +end |
| 110 | +close(vw); |
| 111 | + |
0 commit comments