merge images opencv c++

To merge images using OpenCV in C++, you can follow these steps:

  1. Import the necessary libraries: Begin by including the required OpenCV libraries in your code. This can be done using the #include directive:
#include <opencv2/opencv.hpp>
  1. Read the input images: Use the imread() function to read the input images. Specify the file paths of the images you want to merge as arguments. Make sure to check if the images were loaded successfully:
cv::Mat image1 = cv::imread("path_to_image1.jpg");
cv::Mat image2 = cv::imread("path_to_image2.jpg");

if (image1.empty() || image2.empty()) {
    // Handle error if images were not loaded
    return -1;
}
  1. Resize the images (if necessary): If the input images have different dimensions, you may need to resize them to ensure they have the same size. Use the resize() function for this purpose:
cv::resize(image1, image1, cv::Size(image2.cols, image2.rows));
  1. Create a destination image: Create a new image that will store the merged result. The size of this image should be large enough to accommodate both input images:
cv::Mat mergedImage = cv::Mat(image1.rows, image1.cols + image2.cols, image1.type());
  1. Copy the input images into the destination image: Use the copyTo() function to copy the pixels of the input images into the appropriate regions of the destination image:
image1.copyTo(mergedImage(cv::Rect(0, 0, image1.cols, image1.rows)));
image2.copyTo(mergedImage(cv::Rect(image1.cols, 0, image2.cols, image2.rows)));
  1. Display or save the merged image: You can choose to either display the merged image or save it to a file. For displaying, use the imshow() function:
cv::imshow("Merged Image", mergedImage);
cv::waitKey(0);

For saving, use the imwrite() function:

cv::imwrite("path_to_save_merged_image.jpg", mergedImage);

Remember to replace "path_to_image1.jpg", "path_to_image2.jpg", and "path_to_save_merged_image.jpg" with the actual file paths you want to use.

That's it! By following these steps, you can merge two images using OpenCV in C++.