使用c++视觉处理canny 边缘检测、sobel边缘检测、scharr 滤波边缘检测
# include <opencv2/opencv.hpp> int main ( ) { cv:: Mat image = cv:: imread ( "1.jpg" , cv:: IMREAD_GRAYSCALE) ; if ( image. empty ( ) ) { std:: cerr << "无法加载图像" << std:: endl; return - 1 ; } cv:: namedWindow ( "边缘检测结果" , cv:: WINDOW_AUTOSIZE) ; cv:: Mat cannyEdges; cv:: Canny ( image, cannyEdges, 50 , 150 ) ; cv:: Mat sobelX, sobelY; cv:: Sobel ( image, sobelX, CV_16S, 1 , 0 ) ; cv:: Sobel ( image, sobelY, CV_16S, 0 , 1 ) ; cv:: Mat sobelEdges; cv:: convertScaleAbs ( sobelX, sobelX) ; cv:: convertScaleAbs ( sobelY, sobelY) ; cv:: addWeighted ( sobelX, 0.5 , sobelY, 0.5 , 0 , sobelEdges) ; cv:: Mat scharrX, scharrY; cv:: Scharr ( image, scharrX, CV_16S, 1 , 0 ) ; cv:: Scharr ( image, scharrY, CV_16S, 0 , 1 ) ; cv:: Mat scharrEdges; cv:: convertScaleAbs ( scharrX, scharrX) ; cv:: convertScaleAbs ( scharrY, scharrY) ; cv:: addWeighted ( scharrX, 0.5 , scharrY, 0.5 , 0 , scharrEdges) ; cv:: imshow ( "原始图像" , image) ; cv:: imshow ( "Canny边缘检测" , cannyEdges) ; cv:: imshow ( "Sobel边缘检测" , sobelEdges) ; cv:: imshow ( "Scharr边缘检测" , scharrEdges) ; cv:: waitKey ( 0 ) ; return 0 ;
}
调用本地相机实时检测:canny 边缘检测、sobel边缘检测、scharr 滤波边缘检测
# include <opencv2/opencv.hpp> int main ( ) { cv:: VideoCapture cap ( 0 ) ; if ( ! cap. isOpened ( ) ) { std:: cerr << "无法打开相机" << std:: endl; return - 1 ; } cv:: namedWindow ( "实时边缘检测" , cv:: WINDOW_AUTOSIZE) ; while ( true ) { cv:: Mat frame; cap >> frame; if ( frame. empty ( ) ) { std:: cerr << "无法捕获图像" << std:: endl; break ; } cv:: Mat grayImage; cv:: cvtColor ( frame, grayImage, cv:: COLOR_BGR2GRAY) ; cv:: Mat cannyEdges; cv:: Canny ( grayImage, cannyEdges, 50 , 150 ) ; cv:: Mat sobelX, sobelY; cv:: Sobel ( grayImage, sobelX, CV_16S, 1 , 0 ) ; cv:: Sobel ( grayImage, sobelY, CV_16S, 0 , 1 ) ; cv:: Mat sobelEdges; cv:: convertScaleAbs ( sobelX, sobelX) ; cv:: convertScaleAbs ( sobelY, sobelY) ; cv:: addWeighted ( sobelX, 0.5 , sobelY, 0.5 , 0 , sobelEdges) ; cv:: Mat scharrX, scharrY; cv:: Scharr ( grayImage, scharrX, CV_16S, 1 , 0 ) ; cv:: Scharr ( grayImage, scharrY, CV_16S, 0 , 1 ) ; cv:: Mat scharrEdges; cv:: convertScaleAbs ( scharrX, scharrX) ; cv:: convertScaleAbs ( scharrY, scharrY) ; cv:: addWeighted ( scharrX, 0.5 , scharrY, 0.5 , 0 , scharrEdges) ; cv:: imshow ( "原始图像" , frame) ; cv:: imshow ( "Canny边缘检测" , cannyEdges) ; cv:: imshow ( "Sobel边缘检测" , sobelEdges) ; cv:: imshow ( "Scharr边缘检测" , scharrEdges) ; if ( cv:: waitKey ( 1 ) == 27 ) { break ; } } return 0 ;
}