%% Detect Vehicles in Traffic Scenes from Monocular Video Using YOLO v2
% Configure a YOLO v2 object detector for detecting vehicles within a video captured by a monocular camera.
% Load a yolov2ObjectDetector object pretrained to detect vehicles.

vehicleDetector = load('yolov2VehicleDetector.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 yolov2ObjectDetectorMonoCamera object.

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

% Set up the video reader and read the input monocular video.

videoFile = '05_highway_lanechange_25s.mp4';
reader = VideoReader(videoFile);

% Create a video player to display the video and the output detections.

videoPlayer = vision.DeployableVideoPlayer();

% Detect vehicles in the video by using the detector. Specify the detection threshold as 0.6. Annotate the video with the bounding boxes for the detections, labels, and detection confidence scores.

cont = hasFrame(reader);
while cont
    I = readFrame(reader);
    [bboxes,scores,labels] = detect(detectorMonoCam,I,'Threshold',0.6); % Run the YOLO v2 object detector
    
    if ~isempty(bboxes)
        displayLabel = strcat(cellstr(labels),':',num2str(scores));
        I = insertObjectAnnotation(I,'rectangle',bboxes,displayLabel);
    end
    step(videoPlayer, I);    
    cont = hasFrame(reader) && isOpen(videoPlayer); % Exit the loop if the video player figure window is closed
end

% Copyright 2018 The MathWorks, Inc.