%% Detect Vehicles Using Monocular Camera and SSD
% Configure a SSD object detector for use with a monocular camera mounted on an ego vehicle. Use this detector to detect vehicles within an image captured by the camera.
% Load a ssdObjectDetector object pretrained to detect vehicles.

vehicleDetector = load('ssdVehicleDetector.mat','detector');
detector = vehicleDetector.detector;

% Model a monocular camera sensor by creating a monoCamera object. This object contains the camera intrinsics and the location of the camera on the ego vehicle.

focalLength = [309.4362 344.2161];    % [fx fy]
principalPoint = [318.9034 257.5352]; % [cx cy]
imageSize = [480 640];                % [mrows ncols]
height = 2.1798;                      % height of camera above ground, in meters
pitch = 14;                           % pitch of camera, in degrees
intrinsics = cameraIntrinsics(focalLength,principalPoint,imageSize);

sensor = monoCamera(intrinsics,height,'Pitch',pitch);

% Configure the detector for use with the camera. Limit the width of detected objects to 1.5 – 2.5 meters. The configured detector is a ssdObjectDetectorMonoCamera object.

vehicleWidth = [1.5 2.5];
detectorMonoCam = configureDetectorMonoCamera(detector,sensor,vehicleWidth);

% Read an image captured by the camera.

I = imread('highwayCars.png');

% Detect the vehicles in the image by using the detector. Annotate the image with the bounding boxes for the detections and the detection confidence scores.

[bboxes,scores,labels] = detect(detectorMonoCam,I,'Threshold',0.6);
I = insertObjectAnnotation(I,'rectangle',bboxes,scores,'Color','g');
imshow(I)

% Display the labels for detected bounding boxes. The labels specify the class names of the detected objects.

disp(labels)

% Copyright 2019 The MathWorks, Inc.