Opencv 奇怪的图像行为

Opencv 奇怪的图像行为,opencv,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",fNa

我最近开始使用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);   
}

请使用OpenCV的C++ API, 避免任何有iplimages的东西(尤其是在这里!)


请避免使用不推荐的c-api。不应该用它来编写新的代码。是的,如果有一个选项,人们会这样做。但我正在编写一个多年来开发的相当复杂的C代码(来自opencv 2.1天)。所以,现在,我只能将就着我所拥有的。知道为什么会出现这种异常吗?
#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;
}