c++ - OpenCV - 按宽度和高度过滤 Blob

标签 c++ opencv

我有一张经过 Canny 边缘检测器过滤的图像。现在,我想检测 Blob 并按宽度和高度进行一些过滤。我必须查看哪些功能?

最佳答案

基于 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

enter image description here enter image description here

#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;
}

关于c++ - OpenCV - 按宽度和高度过滤 Blob ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33860019/

相关文章:

opencv - 使用 OpenCV 的视频中的人脸识别给出未处理的异常

vb.net - VB - 在 PictureBox 中根据使用鼠标事件按下的按钮执行操作

c - 使用 openCV 检测序列号

c++ - 编写一个程序,读取一串字符并调用递归函数来确定字符串中的字母是否构成回文

c++ - 在 C++ 中读取大型 CSV 文件(~4GB)

c++ - 访问冲突读取位置 0xCDCDCDD1

iphone - iPhone照片微笑操作应用程序

c# - 应用程序虚拟化是如何实现的?

c++ - C++ 中的指针和引用错误

python - 如何将标签图像从 pydrake/Drake 直接保存到磁盘?