Transfer Python code to c++

Hello dear community, could you please help me to transfer a small piece of code from python to c++/

Here is a code:

        c = max(contours, key=cv2.contourArea)// contours is  std::vector<std::vector<cv::Point>>
        M = cv2.moments(c) 

        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])

I can’t find c++ example how to find the biggest contour? And after find a moments

Thank you

#include <opencv2/opencv.hpp> // Include the appropriate OpenCV header

int main() {
    // Define a vector of vector of cv::Point to store contours
    std::vector<std::vector<cv::Point>> contours;

    // Assuming you have filled the 'contours' vector with contour data

    // Find the contour with the maximum area using a lambda function
    std::vector<cv::Point> c = *std::max_element(contours.begin(), contours.end(), [](const std::vector<cv::Point>& a, const std::vector<cv::Point>& b) {
        return cv::contourArea(a) < cv::contourArea(b);
    });

    // Calculate the moments of the contour
    cv::Moments M = cv::moments(c);

    // Calculate the centroid of the contour
    int cx = static_cast<int>(M.m10 / M.m00); // X-coordinate of centroid
    int cy = static_cast<int>(M.m01 / M.m00); // Y-coordinate of centroid

    // Display the centroid coordinates
    std::cout << "Centroid X: " << cx << ", Y: " << cy << std::endl;

    return 0;
}

This code will find the contour with the largest area, calculate its moments, and then calculate the centroid using the moment values. The centroid coordinates are then displayed. Make sure to include the correct OpenCV header and library paths for your development environment.

1 Like

Thank you very much!!! That exactly what i’am looking for

Note that Dima_Fantasy has been identified as an AI spam bot (based on comments moderators made on other threads.)