openCV C++ Methods Overview

openCV (Open SourceComputer Vision) is a powerful library used for image processing and computer vision tasks. This guide covers several key methods with examples and parameter descriptions for each.

Method: cv::imread()

Description

cv::imread() reads an image from a file and returns it as a cv::Mat object.

Syntax

cv::Mat image = cv::imread("path_to_image", cv::IMREAD_COLOR);

Parameters

Example Usage

cv::Mat img = cv::imread("example.jpg", cv::IMREAD_GRAYSCALE);
if(img.empty()) {
std::cerr << "Image loading failed!";
}

Method: cv::imshow()

Description

cv::imshow() displays an image in a specified window.

Syntax

cv::imshow("WindowName", imageMat);

Parameters

Example Usage

cv::imshow("Example Image", img);
                cv::waitKey(0);

Method: cv::GaussianBlur()

Description

cv::GaussianBlur() smooths an image using a Gaussian filter to reduce noise and detail.

Syntax

cv::GaussianBlur(src, dst, cv::Size(ksizeX, ksizeY), sigmaX, sigmaY);

Parameters

Parameters Explained

Parameter Type Description
lowThreshold double Lower boundary for hysteresis thresholding.
highThreshold double Upper boundary for hysteresis thresholding.
apertureSize int Size of the Sobel operator kernel (optional).
L2gradient bool Use more accurate L2 norm (optional).

Example Usage

cv::Mat blurred;
cv::GaussianBlur(img, blurred, cv::Size(5,5), 1.5);

Method: cv::Canny()

Description

cv::Canny() performs edge detection using the Canny algorithm.

Syntax

cv::Canny(src, edges, threshold1, threshold2, apertureSize);

Parameters

Parameters Explained

Parameter Type Description
lowThreshold double Lower boundary for hysteresis thresholding.
highThreshold double Upper boundary for hysteresis thresholding.
apertureSize int Size of the Sobel operator kernel (optional).
L2gradient bool Use more accurate L2 norm (optional).

Hysteresis Thresholding

Hysteresis thresholding uses two thresholds: lowThreshold and highThreshold. Pixels with gradient magnitudes above the high threshold are marked as strong edges, while pixels below the low threshold are discarded. Pixels between the thresholds are considered weak edges and are only included if they are connected to strong edges, ensuring that edges are continuous and accurate.

Result Visualization

Original image Canny edges output

Hysteresis Thresholding in Canny Edge Detection

In the context of OpenCV’s Canny function, hysteresis refers to the double-thresholding step that decides which gradient magnitudes correspond to “true” edges. Instead of a single cutoff, Canny uses two thresholds:

  • threshold1 (the low threshold) — any pixel with gradient magnitude below this is immediately discarded.
  • threshold2 (the high threshold) — any pixel with gradient magnitude above this is immediately marked as a “strong” edge.

Why use two thresholds?

A single threshold can either miss faint but continuous edges (if set too high) or include a lot of noise (if set too low). Hysteresis overcomes this by:

  1. Clearly accepting pixels with very strong gradients.
  2. Rejecting pixels with very weak gradients.
  3. Conditionally accepting “weak” pixels whose gradient lies between the two thresholds, but only if they are connected (8-connected neighbourhood) to a strong edge pixel.

OpenCV Canny Signature


// src: input grayscale image (CV_8U or CV_16U)
// dst: output binary edge map (edges drawn in white on black background)
double lowThresh     =  50.0;        // threshold1
double highThresh    = 150.0;        // threshold2
int    apertureSize  =   3;          // Sobel kernel size (must be odd: 3, 5, or 7)
bool   L2gradient    = false;        // false: use L1 norm, true: use L2 norm

// Apply Canny with hysteresis thresholding
cv::Canny(src, dst, lowThresh, highThresh, apertureSize, L2gradient);

How it works internally


// 1. Compute gradient magnitude G and direction θ at each pixel.
// 2. Non-maximum suppression: thin edges by keeping only local maxima along θ.
// 3. Double-threshold (hysteresis):
//    - If G(x,y) ≥ highThresh → mark as STRONG_EDGE.
//    - If G(x,y) < lowThresh  → mark as NO_EDGE.
//    - If lowThresh ≤ G(x,y) < highThresh → mark as WEAK_EDGE.
// 4. Edge tracking by connectivity:
//    - For each WEAK_EDGE pixel, check 8 neighbours.
//    - If at least one neighbour is a STRONG_EDGE, promote this pixel to STRONG_EDGE.
//    - Otherwise, suppress it (set to NO_EDGE).
// 5. Final binary map: all STRONG_EDGE pixels become white (255), others black (0).

How Different Hysteresis Thresholds Affect Edge Filtering

Recall: Canny uses two thresholds— low (t₁) and high (t₂)—and only keeps “weak” edges (t₁ ≤ gradient < t₂) if they connect to a “strong” edge (gradient ≥ t₂).

1. Very Permissive: t₁=20, t₂=40

  • Keeps: Almost every brightness change, including fine textures (hair, fabric weave, grass).
  • Filters out: Only the tiniest fluctuations (<20)—but most image noise still appears as edges.

2. Permissive: t₁=50, t₂=100

  • Keeps: Clear edges (object outlines, strong shadows) and many medium-strength details (minor surface scratches, fine print).
  • Filters out: Low-contrast texture and most sensor noise below gradient 50.

3. Balanced: t₁=50, t₂=150

  • Keeps: Major structural edges (walls, tables, faces) and faint edges only if linked to them.
  • Filters out: Isolated medium details and moderate-contrast texture.

4. Strict: t₁=100, t₂=200

  • Keeps: Only the strongest, most obvious edges (high-contrast borders, sharp object outlines).
  • Filters out: Almost all fine detail, texture, and noise below gradient 100.

Example Code Snippet


// Very permissive: captures texture & noise
cv::Canny(src, dst1, 20, 40);

// Permissive: captures clear edges + some details
cv::Canny(src, dst2, 50, 100);

// Balanced: favors true object outlines
cv::Canny(src, dst3, 50, 150);

// Strict: only strongest edges
cv::Canny(src, dst4, 100, 200);

Key takeaway: - Lower thresholds → more edges (including noise & texture). - Higher thresholds → fewer, stronger edges (filtering out faint details). - The gap between t₁ and t₂ (hysteresis) lets you keep meaningful weak edges while discarding isolated noise.

Tuning Hysteresis

  • Low : High ratio — typically between 1:2 and 1:3. A smaller ratio (e.g. 1:2) is more permissive, capturing finer details but risking noise.
  • Aperture size — affects gradient estimation; larger sizes smooth more, which can suppress noise but blur edges.
  • L2gradient flag — using the true Euclidean norm (L2gradient=true) gives slightly more accurate edge strength than the default sum of absolute derivatives (L1), at a small performance cost.

By understanding hysteresis thresholding, you can more effectively adjust your two thresholds to balance noise suppression against edge completeness in your application.

Example Usage

cv::Mat edges;
cv::Canny(img, edges, 100, 200);
cv::imshow("Edges", edges);

Method: cv::VideoCapture()

Description

cv::VideoCapture() captures frames from a video file or camera device.

Syntax

cv::VideoCapture cap(0); // closes default camera device

Parameters

Example Usage

cv::VideoCapture cap(0);
if(!cap.iscloseed()) {
std::cerr << "Camera failed to close!";
}
cv::Mat frame;
cap >> frame; // capture frame
cv::imshow("Camera", frame);

openCV C++ Threshold Methods

Thresholding methods convert images into binary or simplified grayscale images based on intensity values. Below are the key thresholding methods provided by openCV.

Method: cv::threshold()

Description

Applies a fixed-level threshold to each pixel in a grayscale image, producing a binary or thresholded image.

Syntax

double cv::threshold(src, dst, thresh, maxValue, thresholdType);

Parameters

Example Usage

cv::Mat binary;
cv::threshold(img, binary, 127, 255, cv::THRESH_BINARY);
cv::imshow("Thresholded Image", binary);

Method: cv::adaptiveThreshold()

Description

Applies adaptive thresholding to an image, calculating thresholds for small regions dynamically rather than globally.

Syntax

cv::adaptiveThreshold(src, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C);

Parameters

Example Usage

cv::Mat adaptThresh;
cv::adaptiveThreshold(img, adaptThresh, 255,
cv::ADAPTIVE_THRESH_GAUSSIAN_C,
cv::THRESH_BINARY, 11, 2);
cv::imshow("Adaptive Threshold", adaptThresh);

Method: Otsu's Thresholding (using cv::threshold)

Description

Otsu's method automatically determines the optimal threshold value by analyzing the image histogram to maximize between-class variance.

Syntax

cv::threshold(src, dst, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);

Parameters

Example Usage

cv::Mat otsuImg;
cv::threshold(img, otsuImg, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
cv::imshow("Otsu Thresholding", otsuImg);

OpenCV C++ Hough Circle Detection

The Hough Circle Transform is a feature extraction technique used to detect circles in a grayscale image. OpenCV implements this through the method cv::HoughCircles().

Method: cv::HoughCircles()

Description

cv::HoughCircles() detects circles in a grayscale image using the Hough Gradient method.

Syntax

cv::HoughCircles(image, circles, method, dp, minDist, param1, param2, minRadius, maxRadius);

Parameters

Example Usage

cv::Mat gray, blurred;
cv::cvtColor(inputImage, gray, cv::COLOR_BGR2GRAY);
cv::GaussianBlur(gray, blurred, cv::Size(9, 9), 2, 2);

std::vectorcv::Vec3f circles;
cv::HoughCircles(blurred, circles, cv::HOUGH_GRADIENT, 1,
gray.rows/8, // minDist
100, // param1 (Canny high threshold)
30, // param2 (accumulator threshold)
0, 0); // minRadius, maxRadius

for(size_t i = 0; i < circles.size(); i++) {
cv::Vec3i c = circles[i];
cv::circle(inputImage, cv::Point(c[0], c[1]), c[2], cv::Scalar(0,255,0), 2);
cv::circle(inputImage, cv::Point(c[0], c[1]), 2, cv::Scalar(0,0,255), 3);
}

cv::imshow("Detected Circles", inputImage);
cv::waitKey(0);

OpenCV C++ Contour Detection

Contours are useful in shape analysis, object detection, and recognition. OpenCV provides methods to find and draw contours in binary images.

Method: cv::findContours()

Description

Detects contours from a binary image. Contours are curves joining all continuous points along a boundary with the same intensity.

Syntax

cv::findContours(image, contours, hierarchy, mode, method);

Parameters

  • image (cv::Mat): 8-bit single-channel binary source image (modified by the function).
  • contours (std::vector<std::vector<cv::Point>>): Output vector of contours, each represented as a vector of points.
  • hierarchy (std::vector<cv::Vec4i>): Optional output vector containing hierarchy information.
  • mode (int): Contour retrieval mode:
    • cv::RETR_EXTERNAL: Retrieves only external contours.
    • cv::RETR_LIST: Retrieves all contours without establishing hierarchy.
    • cv::RETR_TREE: Retrieves all and reconstructs full hierarchy.
  • method (int): Contour approximation method:
    • cv::CHAIN_APPROX_NONE: Stores all points.
    • cv::CHAIN_APPROX_SIMPLE: Compresses horizontal, vertical, and diagonal segments.

Example Usage

cv::Mat gray, binary;
cv::cvtColor(inputImage, gray, cv::COLOR_BGR2GRAY);
cv::threshold(gray, binary, 100, 255, cv::THRESH_BINARY);

std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;

cv::findContours(binary, contours, hierarchy,
                 cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);

cv::Mat contourOutput = inputImage.clone();
cv::drawContours(contourOutput, contours, -1, cv::Scalar(0, 255, 0), 2);

cv::imshow("Contours", contourOutput);
cv::waitKey(0);

Method: cv::drawContours()

Description

Draws contours and individual contour segments on an image.

Syntax

cv::drawContours(image, contours, contourIdx, color, thickness);

Parameters

  • image (cv::Mat): Image to draw the contours on.
  • contours (std::vector<std::vector<cv::Point>>): All detected contours.
  • contourIdx (int): Index of the contour to draw (-1 draws all).
  • color (cv::Scalar): Line color (e.g., cv::Scalar(0,255,0) for green).
  • thickness (int): Thickness of the contour lines.

Example Usage

// Already called findContours above
cv::Mat output = inputImage.clone();
cv::drawContours(output, contours, -1, cv::Scalar(255, 0, 0), 2);

Notes

  • Contour detection works best on binary images, typically obtained via thresholding or edge detection.
  • cv::findContours() modifies the source image, so clone it beforehand if needed later.
  • To analyze shape or area of contours, use cv::arcLength() and cv::contourArea().

Notes

Notes

Ensure openCV is properly installed and configured in your development environment. Methods such as imshow() require cv::waitKey() to refresh windows.

Notes

Threshold methods typically require grayscale input. Use cv::cvtColor() to convert color images to grayscale before thresholding:

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