1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
|
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv;
Mat g_srcImage, g_srcGrayImage, g_dstImage;
Mat g_cannyDetectedEdges; int g_cannyLowThreshold = 1;
Mat g_sobelGradient_X, g_sobelGradient_Y; Mat g_sobelAbsGradient_X, g_sobelAbsGradient_Y; int g_sobelKernelSize = 1;
Mat g_scharrGradient_X, g_scharrGradient_Y; Mat g_scharrAbsGradient_X, g_scharrAbsGradient_Y;
static void on_Canny(int, void *); static void on_Sobel(int, void *); void Scharr();
int main(int argc, char **argv) { g_srcImage = imread("lena.jpg"); if (!g_srcImage.data) { printf("Oh,no,读取srcImage错误~! \n"); return false; }
imshow("Original", g_srcImage);
g_dstImage.create(g_srcImage.size(), g_srcImage.type());
cvtColor(g_srcImage, g_srcGrayImage, COLOR_BGR2GRAY);
namedWindow("Canny Result", WINDOW_AUTOSIZE); namedWindow("Sobel Result", WINDOW_AUTOSIZE);
createTrackbar("参数值:", "Canny Result", &g_cannyLowThreshold, 120, on_Canny); createTrackbar("参数值:", "Sobel Result", &g_sobelKernelSize, 3, on_Sobel);
on_Canny(0, 0); on_Sobel(0, 0);
Scharr();
while ((char(waitKey(1)) != 'q')) { }
return 0; }
void on_Canny(int, void *) { blur(g_srcGrayImage, g_cannyDetectedEdges, Size(3, 3));
Canny(g_cannyDetectedEdges, g_cannyDetectedEdges, g_cannyLowThreshold, g_cannyLowThreshold * 3, 3);
g_dstImage = Scalar::all(0);
g_srcImage.copyTo(g_dstImage, g_cannyDetectedEdges);
imshow("Canny Result", g_dstImage); }
void on_Sobel(int, void *) { Sobel(g_srcImage, g_sobelGradient_X, CV_16S, 1, 0, (2 * g_sobelKernelSize + 1), 1, 1, BORDER_DEFAULT); convertScaleAbs(g_sobelGradient_X, g_sobelAbsGradient_X);
Sobel(g_srcImage, g_sobelGradient_Y, CV_16S, 0, 1, (2 * g_sobelKernelSize + 1), 1, 1, BORDER_DEFAULT); convertScaleAbs(g_sobelGradient_Y, g_sobelAbsGradient_Y);
addWeighted(g_sobelAbsGradient_X, 0.5, g_sobelAbsGradient_Y, 0.5, 0, g_dstImage);
imshow("Sobel Result", g_dstImage); }
void Scharr() { Scharr(g_srcImage, g_scharrGradient_X, CV_16S, 1, 0, 1, 0, BORDER_DEFAULT); convertScaleAbs(g_scharrGradient_X, g_scharrAbsGradient_X);
Scharr(g_srcImage, g_scharrGradient_Y, CV_16S, 0, 1, 1, 0, BORDER_DEFAULT); convertScaleAbs(g_scharrGradient_Y, g_scharrAbsGradient_Y);
addWeighted(g_scharrAbsGradient_X, 0.5, g_scharrAbsGradient_Y, 0.5, 0, g_dstImage);
imshow("Scharr Result", g_dstImage); }
|