OpenCV in C++ — An Extensive Hands-On Guide

This tutorial is organised in incremental steps. We begin with the absolute basics—installing OpenCV, reading/writing media, and drawing simple shapes—before gradually advancing toward more sophisticated image-processing techniques. Each <details> block below can be collapsed to focus on the sections you need while studying.

1 · Setting Up OpenCV for C++

1.1 Installing OpenCV 4.x

1.2 Compiling Your First Program

// hello.cpp
#include <iostream>
#include <opencv2/opencv.hpp>

int main(){
    std::cout << "OpenCV version " << CV_VERSION << '\n';
    return 0;
}

Compile & run:

g++ hello.cpp `pkg-config --cflags --libs opencv4` -o hello
./hello

If the version prints correctly, you are ready to dive in!

2 · Reading & Writing Images

2.1 Method cv::imread( )

Signature: cv::Mat imread(const std::string& filename, int flags=IMREAD_COLOR);

ParameterDescription
filenamePath to image file.
flagse.g. IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_UNCHANGED.
cv::Mat img = cv::imread("lenna.png", cv::IMREAD_COLOR);
if(img.empty()){
    std::cerr << "Could not read image\n";
    return -1;
}

2.2 Method cv::imshow( )

Displays a window (blocking until a key is pressed).

cv::imshow("Preview", img);
cv::waitKey(0);    // 0 → wait indefinitely

2.3 Method cv::imwrite( )

bool success = cv::imwrite("output.jpg", img);
std::cout << (success ? "Saved ✓" : "Failed ✗") << '\n';

Tip 🛈: OpenCV automatically infers the output format from the file extension (PNG, JPG, BMP…).

3 · Capturing & Saving Video

3.1 Method cv::VideoCapture

cv::VideoCapture cap(0);               // 0 = default webcam
if(!cap.isOpened()){ return -1; }

cv::Mat frame;
while(cap.read(frame)){                // same as cap >> frame
    cv::imshow("Webcam", frame);
    if(cv::waitKey(1) == 27) break;    // Esc to quit
}

3.2 Method cv::VideoWriter

int codec = cv::VideoWriter::fourcc('m','p','4','v');
double fps = 30.0;
cv::Size size(frame.cols, frame.rows);
cv::VideoWriter out("record.mp4", codec, fps, size);

while(cap.read(frame)){
    out.write(frame);                  // save
    cv::imshow("Recording…", frame);
    if(cv::waitKey(1) == 27) break;
}

Remember: Release handles—cap.release(); out.release();

4 · Drawing Shapes & Text

4.1 Rectangles cv::rectangle

cv::Rect box(50, 40, 180, 120);                  
  cv::rectangle(img, box, cv::Scalar(0,255,0), 2);
cv::Rect(x, y, width, height)
  • x, y: Top-left corner
  • width, height: Size of the rectangle
cv::rectangle(image, rect, color, thickness)
  • color: cv::Scalar(B, G, R)
  • thickness: Border thickness (use -1 for filled)

4.2 Circles cv::circle

cv::Point center(150, 150);
  cv::circle(img, center, 60, cv::Scalar(255,0,0), -1);
cv::circle(image, center, radius, color, thickness)
  • center: cv::Point(x, y)
  • radius: Circle radius in pixels
  • color: cv::Scalar(B, G, R)
  • thickness: -1 for filled, or border thickness

4.3 Lines cv::line

cv::line(img, cv::Point(0,0), cv::Point(300,300),
           cv::Scalar(0,0,255), 3, cv::LINE_AA);
cv::line(image, pt1, pt2, color, thickness, lineType)
  • pt1, pt2: Start and end points
  • color: cv::Scalar(B, G, R)
  • thickness: Width of the line in pixels
  • lineType:
    • cv::LINE_8: 8-connected (default)
    • cv::LINE_4: 4-connected
    • cv::LINE_AA: Anti-aliased

4.4 Text cv::putText

cv::putText(img, "OpenCV Rocks!", cv::Point(30,280),
              cv::FONT_HERSHEY_SIMPLEX, 1.2, cv::Scalar(255,255,255), 2);
cv::putText(image, text, origin, font, scale, color, thickness)
  • text: String to draw
  • origin: Bottom-left corner of text
  • font:
    • FONT_HERSHEY_SIMPLEX
    • FONT_HERSHEY_PLAIN
    • FONT_HERSHEY_DUPLEX
    • FONT_HERSHEY_COMPLEX
  • scale: Font scale factor
  • color: cv::Scalar(B, G, R)
  • thickness: Outline thickness of text

5 · Basic Image Editing Tools

5.1 Color Conversion cv::cvtColor

cv::Mat gray;
cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);

5.2 Resizing cv::resize

cv::Mat small;
cv::resize(img, small, cv::Size(), 0.25, 0.25, cv::INTER_AREA);

5.3 Cropping (Region of Interest)

cv::Rect roi(100, 50, 200, 150);
cv::Mat crop = img(roi).clone();

5.4 Blur & Smoothing

cv::Mat gblur;
cv::GaussianBlur(img, gblur, cv::Size(11,11), 0);

5.5 Binary Thresholding cv::threshold

cv::Mat th;
cv::threshold(gray, th, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);

6 · Where to Go From Here

With the fundamentals covered, consider exploring:

Each of these topics can branch into a full notebook-sized lesson. Once you feel confident with the above basics, come back and deepen your understanding by experimenting with these more advanced capabilities.

Overview of `cv::rectangle` in OpenCV

The cv::rectangle() function in OpenCV is used to draw rectangles on images. It can draw both filled and outlined rectangles.

Its core usage syntax is:

cv::rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color,
               int thickness = 1, int lineType = LINE_8, int shift = 0);

Parameters of `cv::rectangle()`

1. Mat& img

The image on which the rectangle will be drawn.

2. Point pt1

The first vertex of the rectangle (usually the top-left corner).

3. Point pt2

The opposite vertex of the rectangle (usually the bottom-right corner).

4. Scalar color

The color of the rectangle in BGR format. Example: Scalar(255, 0, 0) is blue.

5. int thickness

Thickness of the lines. Use FILLED or -1 to fill the rectangle.

6. int lineType

7. int shift

Number of fractional bits in the point coordinates. Typically 0.

Example Usage

#include <opencv2/opencv.hpp>
  using namespace cv;
  
  int main() {
      Mat image = Mat::zeros(400, 400, CV_8UC3);
  
      // Draw a blue rectangle with thickness 2
      rectangle(image, Point(50, 50), Point(300, 300), Scalar(255, 0, 0), 2);
  
      // Draw a filled red rectangle
      rectangle(image, Point(100, 100), Point(200, 200), Scalar(0, 0, 255), FILLED);
  
      imshow("Rectangles", image);
      waitKey(0);
      return 0;
  }
  

Advanced Notes

Filled Rectangle

Use thickness = FILLED or -1 to create a solid filled rectangle.

Anti-Aliased Edges

Use lineType = LINE_AA for smoother rectangle edges, particularly for display or image generation.

Use with ROI

cv::Rect can also define a region of interest, and be used with rectangle like:

Rect roi(60, 60, 100, 150);
  rectangle(image, roi, Scalar(0, 255, 0));