奇怪的cvSaveImage行为

时间:2014-10-17 10:06:48

标签: opencv

我最近开始使用opencv,这个让我感到困惑。

void saveImageSnippet(char *imageName, int height, int width, void* data, int nChannels) //data is char[height * width]
{
    char fName[200]="c:\\testimg\\";
    FILE *fptr;
    IplImage *img;
    sprintf(fName,"%s%s.bmp",fName,imageName);  
    img = cvCreateImageHeader(cvSize(width, height),8/*depth*/,nChannels);
    img->imageData=(unsigned char*)data;
    cvSaveImage(fName, img); //Unhandled exception 
    cvReleaseImage(&img);   
}

在cvSaveImage:vc2008_1x.exe中0x6e8e871d处的未处理异常:0xC0000005:访问冲突读取位置0x745c3a63。 我有什么不对的吗?

现在是一个有趣的部分, 如果我添加几个未使用的变量,cvSaveImage可以正常工作

void saveImageSnippet(char *imageName, int height, int width, void* data, int nChannels) 
{
   int var1, var2; //unused variables
    char fName[200]="c:\\testimg\\";
    FILE *fptr;
    IplImage *img;
    sprintf(fName,"%s%s.bmp",fName,imageName);  
    img = cvCreateImageHeader(cvSize(width, height),8/*depth*/,nChannels);
    img->imageData=(unsigned char*)data;
    cvSaveImage(fName, img); //now it works fine
    cvReleaseImage(&img);   
}

1 个答案:

答案 0 :(得分:0)

请使用opencv的c ++ api,  避免任何东西,其中有iplimages(特别是在SO!)

#include "opencv2/highgui.hpp" // no, *not* highgui.h !

using namespace cv;

int main()
{
    string fName = format("c:\\testimg\\%s.bmp",imageName);

    Mat img = imread( fName );
    if ( img.empty() )
         return -1;
         // your image was not loaded

    imsave(fName);

    return 0;
}