c++ - 如何计算OpenCV中每个圆圈中的像素数?
问题描述
我目前有一个源图像:源图像
我已经为每个作为投资回报率做了一个边界矩形:矩形
我的目标是找到每个矩形内的红色像素数。但是,我不知道如何进行。我已经使用区域 (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);
结果是:
推荐阅读
- laravel - Swift_TransportException(503) - 预期响应代码 354,但得到代码“503”,消息“503 5.5.1 错误的命令序列 - Laravel
- python - XMLTree 解析和打印
- python - 文件替换()方法
- python-sphinx - 尝试创建 PDF 时出现 Sphinx/PlantUML 错误
- javascript - 如何使用charts.js 设置折线图的x 轴和y 轴以及标题?
- docker - docker 无法运行 vscodium
- django - Heroku - 简单 Django 应用程序的 gunicorn 超时
- python - 如何更改 matplotlib GUI 中滑块的显示值?
- node.js - Github 操作使用 @actions/core 或 @actions/github 写入 Node 中的 repo?
- firefox - 将 PWA 应用程序添加到 Firefox 桌面