edge.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "opencv2/core/utility.hpp"
  2. #include "opencv2/imgproc.hpp"
  3. #include "opencv2/imgcodecs.hpp"
  4. #include "opencv2/highgui.hpp"
  5. #include <stdio.h>
  6. using namespace cv;
  7. using namespace std;
  8. int edgeThresh = 1;
  9. int edgeThreshScharr=1;
  10. Mat image, gray, blurImage, edge1, edge2, cedge;
  11. const char* window_name1 = "Edge map : Canny default (Sobel gradient)";
  12. const char* window_name2 = "Edge map : Canny with custom gradient (Scharr)";
  13. // define a trackbar callback
  14. static void onTrackbar(int, void*)
  15. {
  16. blur(gray, blurImage, Size(3,3));
  17. // Run the edge detector on grayscale
  18. Canny(blurImage, edge1, edgeThresh, edgeThresh*3, 3);
  19. cedge = Scalar::all(0);
  20. image.copyTo(cedge, edge1);
  21. imshow(window_name1, cedge);
  22. /// Canny detector with scharr
  23. Mat dx,dy;
  24. Scharr(blurImage,dx,CV_16S,1,0);
  25. Scharr(blurImage,dy,CV_16S,0,1);
  26. Canny( dx,dy, edge2, edgeThreshScharr, edgeThreshScharr*3 );
  27. /// Using Canny's output as a mask, we display our result
  28. cedge = Scalar::all(0);
  29. image.copyTo(cedge, edge2);
  30. imshow(window_name2, cedge);
  31. }
  32. static void help(const char** argv)
  33. {
  34. printf("\nThis sample demonstrates Canny edge detection\n"
  35. "Call:\n"
  36. " %s [image_name -- Default is fruits.jpg]\n\n", argv[0]);
  37. }
  38. const char* keys =
  39. {
  40. "{help h||}{@image |fruits.jpg|input image name}"
  41. };
  42. int main( int argc, const char** argv )
  43. {
  44. help(argv);
  45. CommandLineParser parser(argc, argv, keys);
  46. string filename = parser.get<string>(0);
  47. image = imread(samples::findFile(filename), IMREAD_COLOR);
  48. if(image.empty())
  49. {
  50. printf("Cannot read image file: %s\n", filename.c_str());
  51. help(argv);
  52. return -1;
  53. }
  54. cedge.create(image.size(), image.type());
  55. cvtColor(image, gray, COLOR_BGR2GRAY);
  56. // Create a window
  57. namedWindow(window_name1, 1);
  58. namedWindow(window_name2, 1);
  59. // create a toolbar
  60. createTrackbar("Canny threshold default", window_name1, &edgeThresh, 100, onTrackbar);
  61. createTrackbar("Canny threshold Scharr", window_name2, &edgeThreshScharr, 400, onTrackbar);
  62. // Show the image
  63. onTrackbar(0, 0);
  64. // Wait for a key stroke; the same function arranges events processing
  65. waitKey(0);
  66. return 0;
  67. }