Requirements:
- Install OpenCV library. For example, on Ubuntu, you can use:
sudo apt-get install libopencv-dev
.
C++ Program (edge_detection.cpp
)
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 |
#include <opencv2/opencv.hpp> #include <iostream> int main() { // Load the grayscale image cv::Mat image = cv::imread("input.png", cv::IMREAD_GRAYSCALE); if (image.empty()) { std::cerr << "Error loading image!" << std::endl; return -1; } // Create matrices for the Sobel X and Y gradients cv::Mat gradX, gradY; cv::Mat absGradX, absGradY; cv::Mat edges; // Compute the Sobel X and Y gradients cv::Sobel(image, gradX, CV_16S, 1, 0, 3); cv::Sobel(image, gradY, CV_16S, 0, 1, 3); // Convert gradients to absolute values cv::convertScaleAbs(gradX, absGradX); cv::convertScaleAbs(gradY, absGradY); // Combine the gradients to get the edge magnitude cv::addWeighted(absGradX, 0.5, absGradY, 0.5, 0, edges); // Display the results cv::imshow("Original Image", image); cv::imshow("Sobel Edges", edges); // Wait for a key press and exit cv::waitKey(0); return 0; } |
Explanation:
- Include OpenCV Headers:
#include <opencv2/opencv.hpp>
: Includes the necessary OpenCV headers.
- Load Image:
cv::Mat image = cv::imread("input.png", cv::IMREAD_GRAYSCALE);
: Loads an image in grayscale mode. Replace"input.png"
with the path to your image file.
- Compute Gradients:
cv::Mat gradX, gradY;
: Declare matrices to hold the gradients in the X and Y directions.cv::Sobel(image, gradX, CV_16S, 1, 0, 3);
: Computes the Sobel gradient in the X direction.cv::Sobel(image, gradY, CV_16S, 0, 1, 3);
: Computes the Sobel gradient in the Y direction.
- Convert to Absolute Values:
cv::convertScaleAbs(gradX, absGradX);
: Converts the gradient values to 8-bit absolute values.cv::convertScaleAbs(gradY, absGradY);
: Converts the gradient values to 8-bit absolute values.
- Combine Gradients:
cv::addWeighted(absGradX, 0.5, absGradY, 0.5, 0, edges);
: Combines the X and Y gradients to get the edge magnitude.
- Display Results:
cv::imshow("Original Image", image);
: Displays the original grayscale image.cv::imshow("Sobel Edges", edges);
: Displays the result of the edge detection.cv::waitKey(0);
: Waits for a key press to close the displayed images.
Compilation:
To compile this program, you need to link against the OpenCV libraries. For example:
1g++ edge_detection.cpp -o edge_detection `pkg-config --cflags --libs opencv4`
1./edge_detection