%% Configure Monocular Camera Using Circle Grid Pattern and Generate Bird's-Eye View
% Configure a monocular camera using a circle grid pattern and then estimate the camera's extrinsic parameters. Use an image of an asymmetric circle grid as the calibration pattern.
% Load the intrinsic parameters of a monocular camera. intrinsics is a cameraIntrinsics object.

ld = load('IRCameraIntrinsics');
intrinsics = ld.intrinsics;

% Load an image of an asymmetric circle grid pattern that is placed parallel to the ground placed at a height. This image is for illustrative purposes and was not taken from a camera mounted to the vehicle. In a camera mounted to the vehicle, the X-axis of the pattern points to the right of the vehicle, and the Y-axis of the pattern points to the camera. Display the image.

imageFileName = fullfile(toolboxdir('vision'),'visiondata', ...
    'calibration','circleGrid','stereo','left','left07.jpg');
I = imread(imageFileName);
imshow(I)

% Define the circle grid pattern dimensions and detect the centers of the circles in the image.

patternDims = [4 11];
imagePoints = detectCircleGridPoints(I,patternDims);

%  Generate the corresponding world coordinates of the corners.

centerDistance = 0.0365; % Center-to-center distance in meters
worldPoints = generateCircleGridPoints(patternDims,centerDistance);

% Estimate the extrinsic parameters required to configure the monoCamera object. Because the checkerboard pattern is placed at a height of 1.2 m from the ground, set the height of the pattern's origin to 1.2 m.

patternOriginHeight = 1.2;
[pitch,yaw,roll,height] = estimateMonoCameraParameters(intrinsics, ...
                             imagePoints,worldPoints,patternOriginHeight);

% Configure the monocular camera using the estimated parameters.

monoCam = monoCamera(intrinsics,height,'Pitch',pitch,'Yaw',yaw,'Roll',roll)

% Define the area in front of the camera that you want to transform into a bird's-eye view. Set an area from 0 to 2.5 meters in front of the camera, with 1.75 meters to either side of the camera.

bottomOffset = 0;
distAhead = 2.5;
spaceToOneSide = 1.75;

outView = [bottomOffset,distAhead,-spaceToOneSide,spaceToOneSide];

% Set the output image width to 250 pixels. Compute the output length automatically from the width by setting the length to NaN.

outImageSize = [NaN,250];

% Create an object for performing bird's-eye-view transforms, using the previously defined parameters.

birdsEye = birdsEyeView(monoCam,outView,outImageSize);

% Transform the input image into a bird's-eye-view image and display the result.

BEV = transformImage(birdsEye,I);
imshow(BEV)

% Copyright 2021 The MathWorks, Inc.