'How to split an image into M x N tiles

How can I split a Mat object/image into M x N equal pieces and store the pieces from left to right and from top down, into a Mat vector using OpenCV and C++?

Many thanks



Solution 1:[1]

Here an example:

You take rectangles one by one in a loop and use crop to capture the selected part from the full picture.

Notice the full picture may not be divided perfectly, so one part in each row /column may be slightly bigger than the rest.

#include <opencv2/opencv.hpp>
#include <highgui.h>
#include <iostream>
#include <string>
#include <vector>

//usage: app pic.ext M N
int main(int argc, char* argv[])
{
    int M=0,N=0;
    
    M = std::stoi(argv[2]);
    N = std::stoi(argv[3]);
    
    cv::Mat img = cv::imread(argv[1]);
    if (img.empty())
    {
        std::cout << "failed to open the image" << std::endl;
        return -1;        
    }
    std::vector<std::vector<cv::Mat>> result;
    /* Regular size */
    int crop_width = img.size().width / M;
    int crop_height = img.size().height / N;
    /* column / row first part size when part size is not evenly divided*/
    int crop_width1 = img.size().width - (M-1)*crop_width;
    int crop_height1 = img.size().height - (N-1)*crop_height;
    
    int offset_x = 0;
    int offset_y = 0;
    for(int i = 0; i < M; i++) //rows
    {
        std::vector<cv::Mat> tmp;
        offset_x = 0;
        for(int j=0; j< N; j++) //columns
        {
            cv::Rect roi;
            roi.x = offset_x;
            roi.y = offset_y 
            roi.width = (j>0) ? crop_width :  crop_width1;
            roi.height = (i>0) ? crop_height : crop_height1;
            offset_x += roi.width;
            /* Crop the original image to the defined ROI */
            cv::Mat crop = img(roi);
            /* You can save part to a file: */
            //cv::imwrite(std::to_string(i) + "x" + std::to_string(j)+".png", crop);
            tmp.push_back(crop);
            
            
        }
        result.push_back(tmp);
        offset_y += (i>0) crop_height : crop_height1; 
    }
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1