How to stitch an array of images into an MxN image collage

早过忘川 提交于 2021-01-28 05:13:34

问题


So I have an array of Mat objects (jpeg images) and I want to convert that into an MxN array so the final output would be an image made of all the input images from the array, put into the matrix from left to right, then from up to down. Suppose all input images are the same size, how do I do this in C++ using Opencv?

Many thanks


回答1:


This should do it:

#include <opencv2/opencv.hpp>

cv::Mat imageCollage( std::vector<cv::Mat> & array_of_images, int M, int N )
{
  // All images should be the same size
  const cv::Size images_size = array_of_images[0].size();
  // Create a black canvas
  cv::Mat image_collage( images_size.height * N, images_size.width * M, CV_8UC3, cv::Scalar( 0, 0, 0 ) );

  for( int i = 0; i < N; ++i )
  {
    for( int j = 0; j < M; ++j )
    {
      if( ( ( i * M ) + j ) >= array_of_images.size() )
        break;

      cv::Rect roi( images_size.width * j, images_size.height * i, images_size.width, images_size.height );
      array_of_images[ ( i * M ) + j ].copyTo( image_collage( roi ) );
    }
  }
  
  return image_collage;
}


int main()
{
  std::vector<cv::Mat> array_of_images;
  array_of_images.push_back( cv::imread( "1.jpg" ) );
  array_of_images.push_back( cv::imread( "2.jpg" ) );
  cv::Mat image_collage = imageCollage( array_of_images, 3, 3 );

  cv::imshow( "Image Collage", image_collage );
  cv::waitKey( 0 );
}


来源:https://stackoverflow.com/questions/64972297/how-to-stitch-an-array-of-images-into-an-mxn-image-collage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!