%% Draw Rectangle on Image Using OpenCV in MATLAB
% Draw a rectangle on an image by using the prebuilt MATLAB interface for the OpenCV function cv::rectangle. Compute the corresponding bounding box values in MATLAB to use to crop the image region.
% Add the MATLAB interface to OpenCV package names to the import list.

import clib.opencv.*;
import vision.opencv.util.*;

% Read an image into the MATLAB workspace.

img = imread("highway.png");

% Create interface objects for the OpenCV Mat and InputOutputArray classes to store the input image.

[inputMat,ocvArray] = createMat(img,"InputOutput");

%
%% Define Rectangular Region
% Call the OpenCV function cv::Rect2i using MATLAB, and specify the coordinates and dimensions for the rectangle. Display the values.

rec = cv.Rect2i(140,60,100,100)

%
%% Draw Rectangle and Display Results
% Specify the properties of the line to use for drawing the rectangle. Set these values:
% Color of the line to red. To set this value, use the OpenCV function cv::Scalar.
% Thickness of the line to 2.
% Line type to 4.
% Shift to 0.

color = cv.Scalar(255,0,0);
thickness = 2;
lineType = 4;
shift = 0;

% Draw the defined rectangle on the image by using the OpenCV function cv::rectangle.

cv.rectangle(ocvArray,rec,color,thickness,lineType,shift);

% Read and display the output image.

outputImg = getImage(ocvArray);
figure
imshow(outputImg)

%
%% Compute Bounding Box
% Use the utility function rectToBbox to compute the bounding box value from the values returned by OpenCV function cv::Rect2i.

bbox = rectToBbox(rec);

% Display the bounding box values. Notice that the bounding box values in the MATLAB workspace have one-based indexing.

bbox

% Crop the region within the bounding box by using the imcrop function and display the cropped image.

croppedImg = imcrop(img,bbox);
figure
imshow(croppedImg)

% Copyright 2021 The MathWorks, Inc.