第六章图像滤波 方向滤波器边缘检测

Sobel滤波器
void Sobel( InputArray src, OutputArray dst, int ddepth,
int dx, int dy, int ksize = 3,
double scale = 1, double delta = 0,
int borderType = BORDER_DEFAULT );
用索贝尔算子进行边缘检测:
计算X和Y方向上的导数并进行相加得到Sobel滤波器的范式
找到范式的最大值和最小值
将范式转换成8位图像,并进行二值化的到边缘

#include <iostream>
#include <iomanip>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

int main()
{
    // Read input image
    cv::Mat image = cv::imread("D:/1.jpg", 0);
    if (!image.data)
        return 0;

    // Display the image
    cv::namedWindow("Original Image");
    cv::imshow("Original Image", image);

    // Compute norm of Sobel
    cv::Sobel(image, sobelX, CV_16S, 1, 0);
    cv::Sobel(image, sobelY, CV_16S, 0, 1);
    cv::Mat sobel;
    //compute the L1 norm
    sobel = abs(sobelX) + abs(sobelY);

    double sobmin, sobmax;
    cv::minMaxLoc(sobel, &sobmin, &sobmax);

    // Conversion to 8-bit image
    // sobelImage = -alpha*sobel + 255
    cv::Mat sobelImage;
    sobel.convertTo(sobelImage, CV_8U, -255. / sobmax, 255);

    // Display the image
    cv::namedWindow("Sobel Image");
    cv::imshow("Sobel Image", sobelImage);

    // Apply threshold to Sobel norm (low threshold value)
    cv::Mat sobelThresholded;
    cv::threshold(sobelImage, sobelThresholded, 190, 128, cv::THRESH_BINARY);

    // Display the image
    cv::namedWindow("Binary Sobel Image (low)");
    cv::imshow("Binary Sobel Image (low)", sobelThresholded);

    // Apply threshold to Sobel norm (high threshold value)
    cv::threshold(sobelImage, sobelThresholded, 190, 255, cv::THRESH_BINARY);

    // Display the image
    cv::namedWindow("Binary Sobel Image (high)");
    cv::imshow("Binary Sobel Image (high)", sobelThresholded);

    cv::waitKey();
    return 0;
}

你可能感兴趣的:(opencv)