2012-04-17 36 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);