我目前的原始图片为:Source image
我已将每个边界矩形作为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;
}
}
答案 0 :(得分:2)
也许,这对您有帮助。
// 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);
结果: