Sobel边缘检测的OpenCV实现

来源:互联网 发布:u盘格式化恢复数据 编辑:程序博客网 时间:2024/06/05 22:34

Sobel边缘检测的OpenCV实现

  • 方式1:直接调用Sobel函数实现
  • 方式2:根据Sobel模板实现边缘检测
#include <opencv2/opencv.hpp>#include <cv.h>#include <math.h>using namespace cv;static string winName = "Sobel边缘检测图像";void on_trackbar(int threshold, void* usrdata){    Mat src = *(Mat*)(usrdata);    Mat dst(src.rows, src.cols, CV_8UC1, Scalar(0));    for (int i = 1; i < src.rows - 1; ++i)    {        uchar *p = dst.ptr<uchar>(i);        uchar *p1 = src.ptr<uchar>(i - 1);        uchar *p2 = src.ptr<uchar>(i);        uchar *p3 = src.ptr<uchar>(i + 1);        for (int j = 1; j < src.cols - 1; ++j)        {            int gx = p1[j - 1] * (-1) + p2[j - 1] * (-2) + p3[j - 1] * (-1)                + p1[j + 1] + p2[j + 1] * 2 + p3[j + 1];            int gy = p3[j - 1] * (-1) + p3[j] * (-2) + p3[j + 1] * (-1)                + p1[j - 1] + p1[j] * 2 + p1[j + 1];            int grad = sqrt(gx*gx + gy*gy);            if (grad > threshold)            {                p[j] = 255;            }        }    }    imshow(winName, dst);}int main(void){    Mat src = imread("lena512.bmp");        int threshold = 128;    cvtColor(src, src, CV_BGR2GRAY);    imshow("原始图像", src);    // 1. sobel函数    //Mat dst(src.rows, src.cols, CV_8UC1, Scalar(0));    //Sobel(src, dst, -1, 1, 0, 3, 1, 0, BORDER_DEFAULT);    //Sobel(dst, dst, -1, 0, 1, 3, 1, 0, BORDER_DEFAULT);    //imshow(winName, dst);    // 2. sobel实现(带有trackbar)    namedWindow(winName, CV_WINDOW_AUTOSIZE);    on_trackbar(threshold, &src);    createTrackbar("阈值:", winName, &threshold, 256, on_trackbar, &src);    waitKey(0);    return 0;}
0 0
原创粉丝点击