2011-03-22 94 views
0

顯然,這段代碼在最後一行cvCvtColor()中給出了錯誤,出了什麼問題?這個功能有什麼可以改進的嗎?將pbm文件轉換爲IplImage

+(IplImage*) LoadPbmAsIplImage: (NSString*) fileName{ 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"pbm"]; 
    NSData *data = [NSData dataWithContentsOfFile:filePath]; 
    NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSArray *lines = [content componentsSeparatedByString:@"\n"]; 
    NSString *secondLine = [lines objectAtIndex:1]; //because first line (index 0) contains meta data 
    int width = [secondLine length]; 
    int height = [lines count]-1; 
    Mat *mat = new Mat(width, height, CV_8UC4); 
    MatIterator_<uint> it = mat->begin<uint>(); 
    for (int i=0; i<[lines count]; i++){ 
     for (int j=0; j<[[lines objectAtIndex:i] length]; j++){ 
      int pixelValue = 0; 
      if ([[lines objectAtIndex:i] characterAtIndex:j] == '1'){ 
       pixelValue = 255; 
      } 
      *it = pixelValue; 
     } 
    } 
    IplImage iplImage = *mat; 
    IplImage* rv = cvCreateImage(cvSize(iplImage.width, iplImage.height), IPL_DEPTH_8U, 3); 
    cvCvtColor(mat, rv, CV_RGBA2BGR); 
    return rv; 
} 

回答

1

您將C++接口(cv :: Mat)與C接口(IplImage)混合,爲什麼要這樣做?

Mat *mat = new Mat(width, height, CV_8UC4); 

這是內存泄漏,你永遠不刪除該地圖,也有差不多就沒有必要創建新的墊子 - 只是Mat mat(width, height, CV_8UC4)做這項工作很好,你並不需要將其刪除。

cvCvtColor(mat, rv, CV_RGBA2BGR); 

cvCvtColor需要兩個IplImage* S作爲參數,你給它一個cv::Mat*IplImage*,這可不行。將第一個mat替換爲&iplImage,或者只是一直使用C++接口。

+0

感謝您的輸入,我的首要任務是從pbm轉換到IplImage,一旦完成,我將繼續清理並優化。現在的問題是,當我在ImageView中查看它時,我會看到垃圾模糊的抽象圖像。 – Haoest 2011-03-22 23:30:03