簡體   English   中英

如何使用opencv框架將點[4]添加到輪廓

[英]How to add the points[4] to the contours by using opencv framework

我目前正在使用opencv framework(3.4.1)進行對象測量,但是無法將points[4]添加到輪廓中。 請讓我知道如何在下面的代碼中將points[4]添加到boxContours中。

僅在將點添加到前者時,才能將boxContours傳遞給drawContours

cv::findContours( gray, contours, hierarchy, CV_RETR_EXTERNAL, 
CV_CHAIN_APPROX_SIMPLE);
NSLog(@"contour size %lu",contours.size());
for (int i = 0; i< contours.size(); i++)
{
    cv::RotatedRect rect = cv::minAreaRect(contours[i]);
    cv::Point2f points[4];
    rect.points(points);

    std::vector<std::vector<cv::Point2f>> boxContours;

    cv::drawContours(image, boxContours, i,cvScalar(0,255,0),2);   
}

請參見此代碼以獲取“繪制旋轉矩形”! 您可以輕松地繪制線條!

Mat image(200, 200, CV_8UC3, Scalar(0));
RotatedRect rRect = RotatedRect(Point2f(100,100), Size2f(100,50), 30);
Point2f vertices[4];
rRect.points(vertices);

for (int i = 0; i < 4; i++)
    line(image, vertices[i], vertices[(i+1)%4], Scalar(0,255,0));

imshow("rectangles", image);
waitKey(0);

在此處輸入圖片說明

drawContours函數需要一個向量cv :: Point的向量,因此,如果要使用該函數,則必須構造該向量。 例如,這種方式:

int main(int argc, char* argv[])
{
    cv::Mat image = cv::imread("C:/StackOverflow/Input/coloredLines.png");

    cv::Mat mask = cv::Mat::zeros(image.size(), CV_8UC1);

    // create the edge mask:
    for (int j = 0; j < image.rows; ++j)
        for (int i = 0; i < image.cols; ++i)
            if (image.at<cv::Vec3b>(j, i) != cv::Vec3b(255, 255, 255)) mask.at<unsigned char>(j, i) = 255;


    // here's where your code starts:

    std::vector<std::vector<cv::Point > > contours;
    cv::findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);


    // now draw all the bounding rects, using  drawContours function:
    for (unsigned int i = 0; i < contours.size(); ++i)
    {
        cv::RotatedRect rect = cv::minAreaRect(contours[i]);
        cv::Point2f points[4];
        rect.points(points);

        // must be cv::Point to be used by drawContours function
        std::vector<cv::Point> boundingContour;

        // push all the contour points in that temporary vector
        for (unsigned int j = 0; j < 4; ++j)
            boundingContour.push_back(points[j]);

        // create a temporary dummy container that could hold multiple contours, but we'll only have exactly one in here
        std::vector<std::vector<cv::Point>> boxContours;
        boxContours.push_back(boundingContour);

        // there is only 1 contour inside, so always draw the 0-index contour!
        cv::drawContours(image, boxContours, 0, cvScalar(0, 255, 0), 2);

    }

    cv::imshow("image", image);

    cv::waitKey(0);
    return 0;
}

這是我使用的圖像:

輸入:

在此處輸入圖片說明

用於findContours的蒙版:

在此處輸入圖片說明

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM