簡體   English   中英

如何計算OpenCV中每個圓圈的像素數?

[英]How to count the number of pixels in each circle in OpenCV?

我目前有以下來源圖片: 源圖片

我已經將每個區域的邊界矩形作為ROI: Rects

我的目標是找到每個矩形內紅色像素的數量。 但是,我不知道如何進行。 我已經使用區域(30 * 30)和countNonZero通過分別手動裁剪並另存為單獨的圖像來查找每個圓圈的像素數。 但是,我想在整個圖像中實現它,我可以在邊界矩形中進行迭代。

編輯:如果有幫助,這是我用來獲取邊界矩形的代碼。

for (int i = 0; i < contours.size(); i++)
    {
        approxPolyDP(Mat(contours[i]), contours_poly[i], 0.1, true);
        //Get the width and heights of the bounding rectangles
        int w = boundingRect(Mat(contours[i])).width;
        int h = boundingRect(Mat(contours[i])).height;
        //Apply aspect ratio for filtering rects (optional)
        double ar = (double)w / h;
        //Apply a bounding Rects/Circles


        //Rect/contour filter optional
        if (hierarchy[i][3] == -1) //No parent
            if ((w >= 28 && w <= 32) && (h >= 28 && h <= 32) && ar < 1.1 && ar > 0.9) {
                //Apply a bounding Rects/Circles
                boundRect[i] = boundingRect(Mat(contours_poly[i]));
                minEnclosingCircle((Mat)contours_poly[i], center[i], radius[i]);
                //Add to a new 
                filtered_contours.push_back(contours_poly[i]);

                std::cout << i << " w: " << w << " h: " << h << std::endl;
            }

    }

也許這對您有幫助。

// Load image.
cv::Mat circles = cv::imread("circles.jpg", cv::IMREAD_GRAYSCALE);

// Use simple threshold to get rid of compression artifacts.
cv::Mat circlesThr;
cv::threshold(circles, circlesThr, 128, 255, cv::THRESH_BINARY_INV);

// Find contours in binary image (cv::RETR_EXTERNAL -> only most outer contours).
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(circlesThr, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

// Iterate all contours...
// Iterate all contours...
for (std::vector<cv::Point>& contour : contours)
{
    // Determine bounding rectangle of contour.
    cv::Rect rect = cv::boundingRect(contour);

    // Count non-zero pixels within bounding rect.
    std::string count = std::to_string(cv::countNonZero(circlesThr(rect)));

    // Output text to image.
    cv::putText(circlesThr, count, cv::Point(rect.x - 5, rect.y - 5), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255));
}

// Save output image.
cv::imwrite("output.jpg", circlesThr);

結果是:

輸出圖像

暫無
暫無

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

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