OpenCV库的内存问题

时间:2013-01-22 12:19:50

标签: c++ opencv memory-leaks type-conversion cimg

我需要将加载了CImg library的图像转换为图像格式,可以在OpenCV中使用。

问题是CImg创建了uchar数组,其中数据以下列方式存储(在3通道图像的情况下):

  1. 首先是红色通道的像素,
  2. 然后是绿色通道的所有像素,
  3. 然后 - 蓝色通道。
  4. 它看起来像这样:R R R R R R .... G G G G G G ... B B B B B B ...

    OpenCV以不同的方式存储数据:B G R B G R B G R B G R ...

    这是我从CImg转换为IplImage的代码:

    CImg<uint8_t> src;
    src.load_jpeg_buffer(srcData, size);
    size_t width = src._width;
    size_t height = src._height;
    size_t nChannels = src._spectrum;
    size_t depth = 8;
    
    IplImage* m_image = cvCreateImage(cvSize(width, height), depth, nChannels); 
    for(size_t i = 0; i < height; i++)
    {
        for(size_t j = 0; j < width;j++)
        {
            for(size_t k = 0; k < nChannels; k++)
            { 
                ((m_image->imageData + i * m_image->widthStep))[j * nChannels + nChannels - 1 - k] =
                        src._data[k * src.size() / 3 + k + (i * m_image->widthStep + j * nChannels) / 3];   
            }
        }
    }
    

    此代码工作正常。转换后的OpenCV格式图像是原始图像的完整副本。

    我用valgrind测试了这段代码。它说它会导致很多内存问题。我找不到这种记忆问题的原因。

    如果您对此事有任何想法,我将不胜感激! 或者您可能知道另一种方法,它可以从OpenCV中的缓冲区加载图像(而不是cvDecodeImage)。

1 个答案:

答案 0 :(得分:0)

问题不在我的代码中。正如我发现 OpenCV库函数导致内存问题。 valgrind的消息示例如下:

Use of uninitialised value of size 8
==16460==    at 0x6500539: void cv::CvtColorLoop<cv::RGB2Gray<unsigned char> >(cv::Mat const&, cv::Mat&, cv::RGB2Gray<unsigned char> const&) (in /usr/local/lib/libopencv_imgproc.so.2.4.2) 

==16488== 151,812 bytes in 1 blocks are possibly lost in loss record 3,419 of 3,425
==16488==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16488==    by 0x56A2470: cv::fastMalloc(unsigned long) (in /usr/local/lib/libopencv_core.so.2.4.2)

==16488== LEAK SUMMARY:
==16488==    definitely lost: 19,988 bytes in 171 blocks
==16488==    indirectly lost: 15,201,012 bytes in 311 blocks
==16488==      possibly lost: 1,202,769 bytes in 3,618 blocks
==16488==    still reachable: 693,651 bytes in 3,733 blocks
==16488==         suppressed: 0 bytes in 0 blocks