2012-04-17 144 views
1

所以我试图使用webp API来编码图像。现在我要使用openCV来打开和处理图像,然后我想将它们保存为webp。下面是我使用的源:WebP编码 - 分割错误

#include <stdlib.h> 
#include <stdio.h> 
#include <math.h> 
#include <cv.h> 
#include <highgui.h> 
#include <webp/encode.h> 

int main(int argc, char *argv[]) 
{ 

    IplImage* img = 0; 
    int height,width,step,channels; 
    uchar *data; 
    int i,j,k; 
    if (argc<2) { 
     printf("Usage:main <image-file-name>\n\7"); 
    exit(0); 
    } 
    // load an image 
    img=cvLoadImage(argv[1]); 

    if(!img){ 
     printf("could not load image file: %s\n",argv[1]); 
     exit(0); 
    } 

    // get the image data 
    height  = img->height; 
    width  = img->width; 
    step  = img->widthStep; 
    channels = img->nChannels; 
    data  = (uchar *)img->imageData; 
    printf("processing a %dx%d image with %d channels \n", width, height, channels); 

    // create a window 
    cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); 
    cvMoveWindow("mainWin",100,100); 

    // invert the image 
    for (i=0;i<height;i++) { 
     for (j=0;j<width;j++) { 
      for (k=0;k<channels;k++) { 
       data[i*step+j*channels+k] = 255-data[i*step+j*channels+k]; 
      } 
     } 
    } 

    // show the image 
    cvShowImage("mainWin", img); 

    // wait for a key 
    cvWaitKey(0); 
    // release the image 
    cvReleaseImage(&img); 

    float qualityFactor = .9; 
    uint8_t** output; 
    FILE *opFile; 
    size_t datasize; 
    printf("encoding image\n"); 
    datasize = WebPEncodeRGB((uint8_t*)data,width,height,step,qualityFactor,output); 

    printf("writing file out\n"); 
    opFile=fopen("output.webp","w"); 
    fwrite(output,1,(int)datasize,opFile); 
} 

当我执行,我得到这样的:

[email protected]:~/webp/webp_test$ ./helloWorld ~/Pictures/mars_sunrise.jpg 
processing a 2486x1914 image with 3 channels 
encoding image 
Segmentation fault 

它显示的图像只是罚款,而是在编码段错误。我最初的猜测是,这是因为我在尝试写出数据之前释放了img,但在尝试编码之前或之后我释放它似乎并不重要。有什么我错过了,可能会导致这个问题?我是否必须复制图像数据或其他内容?

WebP api文档是...稀疏。下面是自述说,关于WebPEncodeRGB:

The main encoding functions are available in the header src/webp/encode.h 
The ready-to-use ones are: 

size_t WebPEncodeRGB(const uint8_t* rgb, int width, int height, 
    int stride, float quality_factor, uint8_t** output); 

的文档特别不说什么“步幅”是的,但我假设它与从OpenCV中的“一步”。这是否合理?

在此先感谢!

回答

0

所以看起来这个问题在这里:

// load an image 
img=cvLoadImage(argv[1]); 

功能cvLoadImage需要一个额外的参数

cvLoadImage(const char* filename, int iscolor=CV_LOAD_IMAGE_COLOR) 

,当我改变

img=cvLoadImage(argv[1],1); 

的段错误走了。

1

在尝试使用指向图像数据的指针进行编码之前,您可以使用cvReleaseImage释放图像。可能该释放功能释放图像缓冲区,并且指针现在不再指向有效内存。

可能是您的段错误的原因。

+0

+1这正是我要发布的内容。 – karlphillip 2012-04-17 18:28:49

+0

正如我在我的文章中指出的,“我最初的猜测是,这是因为我在尝试写出数据之前先释放img,但在尝试编码之前或之后是否释放它似乎并不重要“。 我试着将'release'移动到编码之后,但我得到完全相同的结果。 – 2012-04-17 19:06:53

5

首先,如果稍后使用它,请不要释放图像。其次,你的输出参数指向非初始化地址。这是如何使用输出地址的初始化内存:

uint8_t* output; 
datasize = WebPEncodeRGB((uint8_t*)data, width, height, step, qualityFactor, &output);