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.
brew install opencv
sudo apt install libopencv-dev
vcpkg install opencv4:x64-windows
// 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!
Signature: cv::Mat imread(const std::string& filename, int flags=IMREAD_COLOR);
Parameter | Description |
---|---|
filename | Path to image file. |
flags | e.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;
}
Displays a window (blocking until a key is pressed).
cv::imshow("Preview", img);
cv::waitKey(0); // 0 → wait indefinitely
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…).
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
}
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();
cv::rectangle
cv::Rect box(50, 40, 180, 120);
cv::rectangle(img, box, cv::Scalar(0,255,0), 2);
cv::circle
cv::Point center(150, 150);
cv::circle(img, center, 60, cv::Scalar(255,0,0), -1);
cv::line
cv::line(img, cv::Point(0,0), cv::Point(300,300),
cv::Scalar(0,0,255), 3, cv::LINE_AA);
cv::putText
cv::putText(img, "OpenCV Rocks!", cv::Point(30,280),
cv::FONT_HERSHEY_SIMPLEX, 1.2, cv::Scalar(255,255,255), 2);
cv::cvtColor
cv::Mat gray;
cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
cv::resize
cv::Mat small;
cv::resize(img, small, cv::Size(), 0.25, 0.25, cv::INTER_AREA);
cv::Rect roi(100, 50, 200, 150);
cv::Mat crop = img(roi).clone();
cv::Mat gblur;
cv::GaussianBlur(img, gblur, cv::Size(11,11), 0);
cv::threshold
cv::Mat th;
cv::threshold(gray, th, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
With the fundamentals covered, consider exploring:
findContours
, approxPolyDP
.BFMatcher
.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.
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);
Mat& img
The image on which the rectangle will be drawn.
Point pt1
The first vertex of the rectangle (usually the top-left corner).
Point pt2
The opposite vertex of the rectangle (usually the bottom-right corner).
Scalar color
The color of the rectangle in BGR format. Example: Scalar(255, 0, 0)
is blue.
int thickness
Thickness of the lines. Use FILLED
or -1
to fill the rectangle.
int lineType
LINE_8
– 8-connected line (default)LINE_4
– 4-connected lineLINE_AA
– Anti-aliased lineint shift
Number of fractional bits in the point coordinates. Typically 0
.
#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;
}
Use thickness = FILLED
or -1
to create a solid filled rectangle.
Use lineType = LINE_AA
for smoother rectangle edges, particularly for display or image generation.
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));