【问题标题】:OpenCV - Filter blobs by width and heightOpenCV - 按宽度和高度过滤 blob
【发布时间】:2015-11-22 20:51:23
【问题描述】:

我有一张经过精明边缘检测器过滤的图像。现在,我想检测 blob 并按宽度和高度进行一些过滤。有哪些功能需要看?

【问题讨论】:

  • connectedComponentsWithStats 包括返回的stats 数组中每个连接组件的widthheight。这就是你要找的吗?
  • *注意 - connectedComponentsconnectedComponentsWithStats 仅在 OpenCV 3.0 中可用。
  • 哦,太好了。查看文档,是的,就是这样。谢谢!
  • 没问题。如果您不介意,我会将其发布为未来谷歌用户的答案。之前我不确定这就是你要找的东西。

标签: c++ opencv


【解决方案1】:

基于minAreaRect 的轮廓和 minAreaRect 点之间的距离的替代方法。通过这种方式,可以根据样本结果图像上的角度过滤轮廓。

您可以通过更改以下几行来更改宽高比和角度

if(dist0 > dist1 *4) // dist0 and dist1 means width and height you can change as you wish
.
.
if( fabs(angle) > 35 & fabs(angle) < 150 ) // you can change angle criteria

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

using namespace cv;
using namespace std;

//! Compute the distance between two points
/*! Compute the Euclidean distance between two points
*
* @param a Point a
* @param b Point b
*/
static double distanceBtwPoints(const cv::Point2f &a, const cv::Point2f &b)
{
    double xDiff = a.x - b.x;
    double yDiff = a.y - b.y;

    return std::sqrt((xDiff * xDiff) + (yDiff * yDiff));
}

int main( int argc, char** argv )
{
    Mat src,gray;
    src = imread(argv[1]);
    if(src.empty())
        return -1;

    cvtColor( src, gray, COLOR_BGR2GRAY );
    gray = gray < 200;

    vector<vector<Point> > contours;

    findContours(gray.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

    RotatedRect _minAreaRect;

    for (size_t i = 0; i < contours.size(); ++i)
    {
        _minAreaRect = minAreaRect( Mat(contours[i]) );
        Point2f pts[4];
        _minAreaRect.points(pts);

        double dist0 = distanceBtwPoints(pts[0], pts[1]);
        double dist1 = distanceBtwPoints(pts[1], pts[2]);

        double angle = 0;
        if(dist0 > dist1 *4)
            angle =atan2(pts[0].y - pts[1].y,pts[0].x - pts[1].x) * 180.0 / CV_PI;
        if(dist1 > dist0 *4)
            angle =atan2(pts[1].y - pts[2].y,pts[1].x - pts[2].x) * 180.0 / CV_PI;

        if( fabs(angle) > 35 & fabs(angle) < 150 )
            for( int j = 0; j < 4; j++ )
                line(src, pts[j], pts[(j+1)%4], Scalar(0, 0, 255), 1, LINE_AA);
    }
    imshow("result", src);
    waitKey(0);
    return 0;
}

【讨论】:

    【解决方案2】:

    在 OpenCV 3.0 中,您可以使用 connectedComponentsWithStats,它返回一个 stats 数组,其中包括每个连接组件的宽度和高度:

    statsv –

    每个标签的统计输出,包括背景标签,请参阅下面的可用统计信息。统计数据通过 statsv(label, COLUMN) 访问,其中可用的列在下面定义。

    • CC_STAT_LEFT 最左边 (x) 坐标,即包含起点 水平方向的边界框。
    • CC_STAT_TOP 最高 (y) 坐标,它是边界框在垂直方向上的包含起点。
    • CC_STAT_WIDTH 边界框的水平尺寸
    • CC_STAT_HEIGHT 边界框的垂直尺寸
    • CC_STAT_AREA 连通分量的总面积(以像素为单位)

    【讨论】:

    • 我一点也不介意。 openCV 3 有很多新的很酷的东西
    猜你喜欢
    • 2020-01-31
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2016-08-09
    • 2022-01-09
    • 1970-01-01
    • 2014-04-22
    相关资源
    最近更新 更多