簡體   English   中英

如何使用 OpenCV C++ 檢測圖像中有多少樓梯

[英]How to detect how many stairs are there in an image using OpenCV C++

我正在嘗試使用 OpenCV 和 C++ 檢測圖像中有多少樓梯,我嘗試這樣做:

1-二值化。

2-Canny 過濾器。

三霍夫濾波器。

4-連通分量。

我沒有得到好的結果,你知道我應該遵循哪種方法嗎?

先感謝您。

這是一個圖像示例。

在此處輸入圖像描述

您可以獲得如下有趣的結果:

  • 水平計算像素總和; 這將為您提供一個配置文件(一維信號);

  • 計算輪廓的導數;

  • 檢測峰值; 它們是積極的和消極的,或者,每一步一個。

在此處輸入圖像描述

我的算法方法就是這樣; 找到每個樓梯的線條將為我們提供樓梯編號。 為此,可以使用 Houghline 變換 您應該閱讀下面鏈接的文檔,以便能夠理解 HoughLinesP function 的參數邏輯。

第一個問題會遇到:霍夫線變換會給你很多線。 為了獲得可用的線,我消除了y 軸值彼此接近的線。 我通過考慮兩個樓梯之間的最小距離來決定這個閾值。

注意:處理垂直(90 度)到樓梯拍攝的圖像將獲得更好的效果。

以下是這些步驟、結果和代碼:

  • 應用GauusianBlur模糊圖像。 選擇 GauusianBlur 而不是其他的原因我相信 GaussianBlur 與houghline transform有很好的結合。
  • 應用Canny 邊緣檢測
  • 將圖像轉換為 BGR 格式。
  • 應用HoughLinesP並找到所有可能的線
  • 應用上面解釋的算法方法。
  • 得到結果。

代碼:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main()
{

    Mat img = imread("/home/rnd/Desktop/photos/stairs.png");
    imshow("Source",img);

    //Apply Gaussian blur to get good results
    GaussianBlur(img,img,Size(5,5),0,0);

    Mat dst, out_img,control;
    Canny(img, dst, 80, 240, 3);
    cvtColor(dst, out_img, CV_GRAY2BGR);
    cvtColor(dst, control, CV_GRAY2BGR);

    vector<int> y_keeper_for_lines;
    vector<Vec4i> lines;
    HoughLinesP(dst, lines, 1, CV_PI/180, 30, 40, 5 );

    for( size_t i = 1; i < lines.size(); i++ )
    {
        Vec4i l = lines[i];
        line( control, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
    }

    Vec4i l = lines[0];
    line( out_img, Point(0, l[1]), Point(img.cols, l[1]), Scalar(0,0,255), 3, CV_AA);
    y_keeper_for_lines.push_back(l[1]);

    int okey = 1;
    int stair_counter = 1;

    for( size_t i = 1; i < lines.size(); i++ )
    {
        Vec4i l = lines[i];
        for(int m:y_keeper_for_lines)
        {
            if(abs(m-l[1])<15)
                okey = 0;

        }
        if(okey)
        {
            line( out_img, Point(0, l[1]), Point(img.cols, l[1]), Scalar(0,0,255), 3, CV_AA);
            y_keeper_for_lines.push_back(l[1]);
            stair_counter++;
        }
        okey = 1;

    }
    putText(out_img,"Stair number:" + to_string(stair_counter),Point(40,60),FONT_HERSHEY_SIMPLEX,1.5,Scalar(0,255,0),2);
    imshow("Before", img);
    imshow("Control", control);
    imshow("detected lines", out_img);
    waitKey(0);
    return 0;
}

結果:

高斯之后:

在此處輸入圖像描述

HoughLinesP 算法前:

在此處輸入圖像描述

算法后:

在此處輸入圖像描述

暫無
暫無

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

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