edge.cpp 2.18 KB
Newer Older
1 2
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
3
#include "opencv2/imgcodecs.hpp"
4
#include "opencv2/highgui.hpp"
5

6
#include <stdio.h>
7 8 9 10 11

using namespace cv;
using namespace std;

int edgeThresh = 1;
12 13 14 15 16 17
int edgeThreshScharr=1;

Mat image, gray, blurImage, edge1, edge2, cedge;

const char* window_name1 = "Edge map : Canny default (Sobel gradient)";
const char* window_name2 = "Edge map : Canny with custom gradient (Scharr)";
18 19

// define a trackbar callback
20
static void onTrackbar(int, void*)
21
{
22
    blur(gray, blurImage, Size(3,3));
23 24

    // Run the edge detector on grayscale
25
    Canny(blurImage, edge1, edgeThresh, edgeThresh*3, 3);
26
    cedge = Scalar::all(0);
27

28 29 30 31 32 33 34 35 36 37 38 39
    image.copyTo(cedge, edge1);
    imshow(window_name1, cedge);

    /// Canny detector with scharr
    Mat dx,dy;
    Scharr(blurImage,dx,CV_16S,1,0);
    Scharr(blurImage,dy,CV_16S,0,1);
    Canny( dx,dy, edge2, edgeThreshScharr, edgeThreshScharr*3 );
    /// Using Canny's output as a mask, we display our result
    cedge = Scalar::all(0);
    image.copyTo(cedge, edge2);
    imshow(window_name2, cedge);
40 41
}

42
static void help()
43
{
44 45
    printf("\nThis sample demonstrates Canny edge detection\n"
           "Call:\n"
Dmitriy Anisimov's avatar
Dmitriy Anisimov committed
46
           "    /.edge [image_name -- Default is ../data/fruits.jpg]\n\n");
47 48
}

49
const char* keys =
50
{
ValeryTyumen's avatar
ValeryTyumen committed
51
    "{help h||}{@image |../data/fruits.jpg|input image name}"
52 53 54 55
};

int main( int argc, const char** argv )
{
56
    help();
57
    CommandLineParser parser(argc, argv, keys);
58
    string filename = parser.get<string>(0);
59

60
    image = imread(filename, IMREAD_COLOR);
61 62
    if(image.empty())
    {
63 64
        printf("Cannot read image file: %s\n", filename.c_str());
        help();
65 66 67
        return -1;
    }
    cedge.create(image.size(), image.type());
68
    cvtColor(image, gray, COLOR_BGR2GRAY);
69 70

    // Create a window
71 72
    namedWindow(window_name1, 1);
    namedWindow(window_name2, 1);
73 74

    // create a toolbar
75 76
    createTrackbar("Canny threshold default", window_name1, &edgeThresh, 100, onTrackbar);
    createTrackbar("Canny threshold Scharr", window_name2, &edgeThreshScharr, 400, onTrackbar);
77 78 79 80 81 82 83 84 85

    // Show the image
    onTrackbar(0, 0);

    // Wait for a key stroke; the same function arranges events processing
    waitKey(0);

    return 0;
}