Understanding the copy done by memcpy()

最后都变了- 提交于 2020-01-01 05:31:23

问题


I have to create an image which has two times the number of columns to that of the original image. Therefore, I have kept the width of the new image two times to that of the original image.

Although this is a very simple task and I have already done it but I am wondering about the strange results obtained by doing this task using memcpy().

My code:

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:

Result

Expected Results:

Question: When the resulting image is just two times to that of the original image then, how come 4 original images are getting copied to the new image? Secondly, the memcpy() copies the continous memory location in a row-wise fashion so, according to that I should get an image which is shown in the "Expected results".


回答1:


The left cat consists of the odd numbered lines and the right cat consists of the even numbered lines of the original picture. This is then doubled, so that there are two more cats underneath. The new cats have half the number of lines of the original cat.

The new picture is laid out like this:

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



回答2:


the answer provided by "Klas Lindbäck" is absolutely correct. Just to provide more clarity to someone who might have a similar confusion, I am writing this answer. I created an image with odd rows consisting of red color and even rows consisting of blue color.

Then, I used the code given in my original post. As, expected by the answer of "Klas Lindbäck", the red color came into the first coloumn and the blue color came into the second column.

Original image:

Resulting image:



来源:https://stackoverflow.com/questions/31673359/understanding-the-copy-done-by-memcpy

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