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 |
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main() { // Load the image Mat image = imread("input.jpg"); if (image.empty()) { cerr << "Error loading image!" << endl; return -1; } // Convert image to grayscale Mat grayImage; cvtColor(image, grayImage, COLOR_BGR2GRAY); // Apply Gaussian blur to the grayscale image Mat blurredImage; GaussianBlur(grayImage, blurredImage, Size(5, 5), 0); // Save the processed image if (!imwrite("output.jpg", blurredImage)) { cerr << "Error saving image!" << endl; return -1; } cout << "Image processing completed successfully." << endl; return 0; } |
Explanation
- Include Libraries: The program includes the OpenCV library for image processing. OpenCV is a popular computer vision library that provides various functions for image manipulation.
- Load Image: The
imread
function loads an image from a specified file path into aMat
object. If the image cannot be loaded, an error message is displayed. - Convert to Grayscale: The
cvtColor
function converts the loaded image to a grayscale image. Grayscale images are easier to process for many image analysis tasks. - Apply Gaussian Blur: The
GaussianBlur
function applies a Gaussian blur to the grayscale image. Blurring helps in reducing noise and detail, which is useful for edge detection. - Detect Edges: The
Canny
function detects edges in the blurred image. The Canny edge detection algorithm finds edges by looking for areas with rapid intensity changes. - Display Images: The
namedWindow
andimshow
functions are used to create windows and display the original and processed images. - Wait for User Input: The
waitKey
function waits for a key press before closing the image windows.