Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two Mat images into one

Tags:

c++

c

opencv

I have a problem. I have an image. Then I have to split the image into two equal parts. I made this like that (the code is compiled, everything is good):

Mat image_temp1 = image(Rect(0, 0, image.cols, image.rows/2)).clone();
Mat image_temp2 = image(Rect(0, image.rows/2, image.cols, image.rows/2)).clone();

Then I have to change each part independently and finally to merge into one. I have no idea how to make this correctly. How I should merge this 2 parts of image into one image?
Example: http://i.stack.imgur.com/CLDK7.jpg

like image 922
dmitryvodop Avatar asked Dec 04 '14 14:12

dmitryvodop


Video Answer


3 Answers

There is several way to do this, but the best way I found is to use cv::hconcat(mat1, mat2, dst) for horizontal merge orcv::vconcat(mat1, mat2, dst) for vertical.

Don't forget to take care of empty matrix merge case !

like image 148
Alto Avatar answered Sep 21 '22 17:09

Alto


Seems that cv::Mat::push_back is exactly what are you looking for:

C++: void Mat::push_back(const Mat& m) : Adds elements to the bottom of the matrix.

Parameters:    
    m – Added line(s).

The methods add one or more elements to the bottom of the matrix. When elem is Mat , its type and the number of columns must be the same as in the container matrix.

Optionally, you could create new cv::Mat of proper size and place image parts directly into it:

Mat image_temp1 = image(Rect(0, 0, image.cols, image.rows/2)).clone();
Mat image_temp2 = image(Rect(0, image.rows/2, image.cols, image.rows/2)).clone();
...
cv::Mat result(image.rows, image.cols);
image_temp1.copyTo(result(Rect(0, 0, image.cols, image.rows/2)));
image_temp2.copyTo(result(Rect(0, image.rows/2, image.cols, image.rows/2));
like image 20
Rasim Avatar answered Sep 21 '22 17:09

Rasim


How about this:

Mat newImage = image.clone();
Mat image_temp1 = newImage(Rect(0, 0, image.cols, image.rows/2));
Mat image_temp2 = newImage(Rect(0, image.rows/2, image.cols, image.rows/2));

By not using clone() to create the temp images, you're implicitly modifying newImage when you modify the temp images without the need to merge them again. After changing image_temp1 and image_temp2, newImage will be exactly the same as if you had split, modified, and then merged the subimages.

like image 38
beaker Avatar answered Sep 24 '22 17:09

beaker