Created
December 1, 2020 15:56
-
-
Save drabaioli/c7aeda1eb21fd343c78aa1382c4a8f3a to your computer and use it in GitHub Desktop.
Split image into an MxN grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <opencv2/opencv.hpp> | |
std::vector<cv::Mat> splitImage( cv::Mat & image, int M, int N ) | |
{ | |
// All images should be the same size ... | |
int width = image.cols / M; | |
int height = image.rows / N; | |
// ... except for the Mth column and the Nth row | |
int width_last_column = width + ( image.cols % width ); | |
int height_last_row = height + ( image.rows % height ); | |
std::vector<cv::Mat> result; | |
for( int i = 0; i < N; ++i ) | |
{ | |
for( int j = 0; j < M; ++j ) | |
{ | |
// Compute the region to crop from | |
cv::Rect roi( width * j, | |
height * i, | |
( j == ( M - 1 ) ) ? width_last_column : width, | |
( i == ( N - 1 ) ) ? height_last_row : height ); | |
result.push_back( image( roi ) ); | |
} | |
} | |
return result; | |
} | |
int main() | |
{ | |
cv::Mat image = cv::imread( "image.png" ); | |
std::vector<cv::Mat> array_of_images = splitImage( image, 3, 2 ); | |
for( int i = 0; i < array_of_images.size(); ++i ) | |
{ | |
cv::imshow( "Image " + std::to_string( i ), array_of_images[i] ); | |
} | |
cv::waitKey( 0 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment