Shape Approximation Using OpenCV (C++)

Overview

Shape approximation in OpenCV simplifies contours by reducing the number of points using the cv::approxPolyDP method. This is especially useful in shape detection, such as distinguishing between triangles, rectangles, or circles.

Key Method: cv::approxPolyDP()

This method approximates a polygonal curve with the specified precision. It’s based on the Douglas-Peucker algorithm.

void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed);
  • curve: Input vector of 2D points (e.g. a contour)
  • approxCurve: Resulting approximation
  • epsilon: Maximum distance from the contour to the approximation
  • closed: Whether the contour is closed

Example Code


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

using namespace cv;
using namespace std;

int main() {
    Mat image = imread("shapes.png", IMREAD_GRAYSCALE);
    threshold(image, image, 127, 255, THRESH_BINARY);
    
    vector<vector<Point>> contours;
    findContours(image, contours, RETR_TREE, CHAIN_APPROX_SIMPLE);
    
    for (const auto& contour : contours) {
        double epsilon = 0.02 * arcLength(contour, true);
        vector<Point> approx;
        approxPolyDP(contour, approx, epsilon, true);
        
        int vertices = (int)approx.size();
        cout << "Vertices: " << vertices << endl;

        // Shape detection
        if (vertices == 3)
            cout << "Triangle" << endl;
        else if (vertices == 4)
            cout << "Rectangle or Square" << endl;
        else if (vertices > 4)
            cout << "Circle or Ellipse" << endl;
    }

    return 0;
}
			

Notes

  • Note: Epsilon value is crucial. Smaller values retain more detail; larger values simplify more.
  • Tip: Use drawContours() to visualize the approximated shape on the image.
  • Application: Useful in document scanning, shape-based object detection, and contour simplification for performance.