Opencv筆記:利用霍夫變換檢測圖像中的紅球

代碼功能爲從一副圖像中檢測紅球,當然也可以針對視頻的單幀圖像進行檢測,關於霍夫圓變換HoughCircles()函數及其原理主要參考了《opencv3編程入門》

HoughCircles()函數

函數原型:

void HoughCircles(InputArray image, outputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0);

參數說明:
image: 輸入圖像,8位灰度單通道圖像;
circles: 用於儲存檢測到的園的輸出矢量,(x, y, radius);
method: 調用的檢測方法,opencv中使用的是霍夫梯度法(CV_HOUGH_GRADIENT);
dp: 用於檢測圓心的累加器圖像的分辨率與輸入圖像之比的倒數;
minDist: 檢測的不同圓的圓心之間 的最小距離;
param1, param2: 與檢測方法相對應的參數;
minRadius, maxRadius: 圓半徑的最小值和最大值。

主函數

/* redball_detect.cpp
Description: the test example for detect the red ball.
Date: 2017/10/12
*/

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

#define SRC_WINDOW_NAME "redball"
#define MID_WINDOWNAME "redball_gray"

Mat srcImage,  dstImage;
Mat channel[3];

int main()
{
    // 原圖像讀取
    srcImage = imread("redball5.jpg", 1);
    imshow(SRC_WINDOW_NAME, srcImage);

    // 提取紅色通道圖像
    int g_nHm = 9; // 可利用滑動條調節
    split(srcImage, channel);
    channel[0] = channel[0].mul(.1*g_nHm); // B    (mul: per-element matrix multiplication)
    channel[1] = channel[1].mul(.1*g_nHm); // G
    channel[2] = channel[2] - channel[0] - channel[1]; // R
    channel[2] = 3 * channel[2];
    imshow(MID_WINDOWNAME, channel[2]);
    dstImage = channel[2];
    GaussianBlur(dstImage, dstImage, Size(9, 9), 2, 2); // 用於減少檢測噪聲

    // 霍夫圓檢測
    vector<Vec3f> circles; // 3通道float型向量
    HoughCircles(dstImage, circles, CV_HOUGH_GRADIENT, 1, srcImage.rows / 5, 200, 16, 0, 0);

    // 結果顯示
    for (size_t i = 0; i < circles.size(); i++)
    {
        Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
        int radius = cvRound(circles[i][2]);

        circle(srcImage, center, 3, Scalar(0, 255, 0), -1, 8, 0);
        circle(srcImage, center, radius, Scalar(155, 50, 255), 3, 8, 0);
        cout << circles[i][0] << "\t" << circles[i][1] << "\t" << circles[i][2] << endl;
    }
    // cout << circles[0][0] << endl;
    imshow(SRC_WINDOW_NAME, srcImage);
    waitKey(0);

    return 0;
}

代碼中的幾點說明:
- 因爲需要檢測的紅色球,所以提取RGB圖像中的紅色通道值更有利於檢測;
- g_nHm是可調節參數,可以利用滑動條確定最好的值;
- GaussianBlur()函數用於抑制檢測過程中的噪聲,可以參考檢測結果中使用GaussianBlur前後的對比。

結果顯示

原圖:


SrcImage

g_nHm=9時紅色通道圖像:


red_channel

不加高斯平滑的檢測結果:


result_without_gaussian

加入高斯平滑的檢測結果:


result_with_gaussian

發佈了56 篇原創文章 · 獲贊 214 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章