Specifying the pointer when copying with OpenCV

1

I'm having an image memory that I stocked and saved it in a pointer to not loose its address.

I would like now to assign it to an IplImage by the following function memcpy (what I have tested):

IplImage* img=cvCreateImage(cvSize(640, 480), IPL_DEPTH_16U, 1);
VOID* ImgMem;
memcpy(img->imageData, ImgMemory, (640*480));

It really doesn't work. It stated Unhandled exception at 0x001b96dd in ex4.exe: 0xC0000005: Access violation reading location 0x00000044.

Any idea how to deal with that?

c++
c
opencv
asked on Stack Overflow Apr 16, 2013 by user2187476 • edited Sep 3, 2015 by Haris

3 Answers

0

Your image is 640x480, but you copied 916x916 pixals.

answered on Stack Overflow Apr 16, 2013 by Tianyun Ling
0

There are two problems in your code. The first issue is you are not initializing 'ImgMem'.

VOID* ImgMem;
//    ^^^^^^ Points to whatever

If you need to use a buffer prior to copying the data to the image buffer you need to allocate memory for it.

int bufferSize = 640*480*2;
char* ImgMem = new char[bufferSize];

Make sure that you delete the memory once you are done with it or you will end up leaking memory.

delete[] ImgMem;

A better alternative would be to use std::vector;

std::vector<char> ImgMem(bufferSize, 0);

memcpy(img->imageData, &ImgMem[0], ImgMem.size());

This way the memory is allocated, managed and freed by std::vector instead of you having to do it every time.

The second problem is you are trying to copy more memory into the image buffer than it can hold.

memcpy(img->imageData, ImgMemory, (916*916));

This will copy 839,056 bytes when img->imageData can only hold 307,200 bytes (assuming 8bpp).

[Edit: This answer does not take into account the attributes provided by the IplImage structure. This includes size AND alignment which are fairly important here in regards to memcpy. For more information on members of IplImage see here]

answered on Stack Overflow Apr 16, 2013 by Captain Obvlious • edited Apr 16, 2013 by Captain Obvlious
0

pixel type is unsigned short IPL_DEPTH_16U and it is 2 bytes, therefore you need to calculate total byte size accordingly:

int totalSize = 640*480*2;
char* ImgMemory = new char[totalSize];
memcpy(img->imageData, ImgMemory, (totalSize ));
answered on Stack Overflow Apr 16, 2013 by fatihk • edited Apr 17, 2013 by fatihk

User contributions licensed under CC BY-SA 3.0