Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.5 kB
2
Indexable
Never
#include <opencv2/opencv.hpp>
#include <vector>

// Function to extract coordinates from an image using a bounding box
std::vector<cv::Rect> extractBoundingBoxCoordinates(cv::Mat image) {
    std::vector<cv::Rect> boundingBoxes;

    // Convert the image to grayscale
    cv::Mat gray;
    cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);

    // Apply thresholding to segment the object from the background
    cv::Mat thresh;
    cv::threshold(gray, thresh, 0, 255, cv::THRESH_BINARY_INV + cv::THRESH_OTSU);

    // Find contours in the thresholded image
    std::vector<std::vector<cv::Point>> contours;
    cv::findContours(thresh, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    // Iterate through the contours and extract the bounding box coordinates
    for (const auto& contour : contours) {
        cv::Rect boundingBox = cv::boundingRect(contour);
        boundingBoxes.push_back(boundingBox);
    }

    return boundingBoxes;
}

int main() {
    // Load the image
    cv::Mat image = cv::imread("image.jpg");

    // Extract the bounding box coordinates
    std::vector<cv::Rect> boundingBoxes = extractBoundingBoxCoordinates(image);

    // Print the coordinates
    for (const auto& boundingBox : boundingBoxes) {
        std::cout << "x: " << boundingBox.x << ", y: " << boundingBox.y << ", w: " << boundingBox.width << ", h: " << boundingBox.height << std::endl;
    }

    return 0;
}
Leave a Comment