%% Detect Vehicles Using Monocular Camera and Faster R-CNN
% Configure a Faster R-CNN 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 fasterRCNNObjectDetector object pretrained to detect vehicles.

detector = vehicleDetectorFasterRCNN;

%
% 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);

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

%
% Configure the detector for use with the camera. Limit the width of detected objects to a typical range for vehicle widths: 1.5–2.5 meters. The configured detector is a fasterRCNNObjectDetectorMonoCamera object.

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

%
% Read in an image captured by the camera.

I = imread('carsinfront.png');
imshow(I)

%
% 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] = detect(detectorMonoCam,I);
I = insertObjectAnnotation(I,'rectangle',bboxes,scores,'Color','g');
imshow(I)

% Copyright 2018 The MathWorks, Inc.