Understanding the copy done by memcpy ()

I need to create an image that has twice as many columns of the original image. Therefore, I saved the width of the new image twice as compared to the original image.

Although this is a very simple task, and I have already done it, I am interested in learning about the strange results obtained when performing this task using memcpy() .

My code is:

 int main() { Mat image = imread("pikachu.png", 1); int columns = image.cols; int rows = image.rows; Mat twoTimesImage(image.rows, 2 * image.cols, CV_8UC3, Scalar(0)); unsigned char *pSingleImg = image.data; unsigned char *ptwoTimes = twoTimesImage.data; size_t memsize = 3 * image.rows*image.cols; memcpy(ptwoTimes , pSingleImg, memsize); memcpy(ptwoTimes + memsize, pSingleImg, memsize); cv::imshow("two_times_image.jpg", twoTimesImage); return 0; } 

Original Image:

image1

Result

image2

Expected results:

image3

Question: When the resulting image is only twice as large as the original image, how is it that 4 original images are copied to a new image? Secondly, memcpy() copies the continuous memory location in different ways, therefore, in accordance with this, I should get the image that is shown in the "Expected Results".

+6
source share
2 answers

The left cat consists of odd numbered lines, and the right cat consists of even lines of the original image. Then it doubles, so there are two more cats below. New cats have half the number of lines of the original cat.

The new image is as follows:

 line 1 line 2 line 3 line 4 line 5 line 6 ... line n-1 line n line 1 line 2 line 3 line 4 line 5 line 6 ... line n-1 line n 
+7
source

The answer provided by Klas Lindbeck is absolutely correct. Just to provide more clarity to those who might be so confused, I am writing this answer. I created an image with odd lines consisting of red and even lines consisting of blue.

Then I used the code provided in my original post. As expected from Klas Lindbรคck's answer, the red color fell into the first colony, and the blue color fell into the second column.

Original Image:

image

Resulting Image:

image2

+5
source

All Articles