Opencv - 使用相同的算法查找不同对象的边缘

时间:2015-07-08 20:28:16

标签: c++ algorithm opencv feature-detection edge

我是openCV的新手,这是我的第一个项目,所以我需要一些建议。我试图找到不同对象的维度。我已经根据opencv.org上的教程编写了一些代码,并通过Bradski& amp; amp; Kaehler。

到目前为止,我正在使用一个对象。当我试图找到不同对象的维度时,我意识到我需要更改Canny的threshold1值。

所以我的问题是:如何让我的程序自动对不同的对象进行这种调整?所以我不需要手动更改任何东西。我应该使用什么样的算法?

背景将是相同的,相机的位置将是固定的,我们可以假设照明将是相同的。

对于这张图片,我需要一个threshold1值53,以便找到边缘。 bluePaper2.png

对于这个,值141非常好。 hardDisk2.png

我找不到这个的任何值,因为它的颜色几乎与背景的颜色相同。 bigPaper1.png

这是我的代码:

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

using namespace cv;
using namespace std;

Mat src, src_gray, src_blur;
Mat canny_output;

int canny_thresh = 53;
int canny_max_thresh = 200;
int canny_kernel = 3;
int canny_ratio = 3;
bool L2gradient = true;

char* source_window = "Source";
char* canny_window = "Canny";
char* contour_window = "Contours";

/** @function main */
int main(int argc, char** argv)
{
    /// Load source image and convert it to gray
    src = imread("bluePaper2.png", 1);

    /// Create Window   
    namedWindow(source_window, CV_WINDOW_AUTOSIZE);
    imshow(source_window, src);

    /// Convert image to gray and blur it
    cvtColor(src, src_gray, CV_BGR2GRAY);

    /// Reduce noise with a kernel 3x3
    blur(src_gray, src_blur, Size(3, 3));   

    /// Detect edges using Canny
    Canny(src_blur, canny_output, canny_thresh, canny_thresh * canny_ratio, canny_kernel, L2gradient);

    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    /// Find contours
    findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    /// Find the rotated rectangles and ellipses for each contour
    vector<RotatedRect> minRect(contours.size());
    vector<RotatedRect> minEllipse(contours.size());

    for (int i = 0; i < contours.size(); i++)
    {
        minRect[i] = minAreaRect(Mat(contours[i]));
        if (contours[i].size() > 5)
        {
            minEllipse[i] = fitEllipse(Mat(contours[i]));
        }
    }

    /// Draw contours + rotated rects + ellipses
    Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
    for (int i = 0; i< contours.size(); i++)
    {
        // contour
        drawContours(drawing, contours, i, Scalar(255, 255, 0), 2, 8, vector<Vec4i>(), 0, Point());
        // ellipse
        ellipse(drawing, minEllipse[i], Scalar(0, 0, 255), 2, 8);
        // rotated rectangle
        Point2f rect_points[4]; minRect[i].points(rect_points);
        for (int j = 0; j < 4; j++)
            line(drawing, rect_points[j], rect_points[(j + 1) % 4], Scalar(0, 255, 0), 2, 8);
    }

    /// Show in a window
    namedWindow(canny_window, CV_WINDOW_AUTOSIZE);
    namedWindow(contour_window, CV_WINDOW_AUTOSIZE);

    imshow(canny_window, canny_output);
    imshow(contour_window, drawing);

    waitKey(0);
    return(0);
}

提前致谢。

0 个答案:

没有答案