将pbm文件转换为IplImage

时间:2011-03-22 04:07:21

标签: iphone ios opencv

显然,这段代码在最后一行cvCvtColor()给出了错误,出了什么问题?这个功能有什么可以改进的吗?

+(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 个答案:

答案 0 :(得分:1)

您将C ++接口(cv :: Mat)与C接口(IplImage)混合,为什么这样做?

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

这是一个内存泄漏,你永远不会删除那个地图,也几乎没有理由用新建一个Mat - 只需Mat mat(width, height, CV_8UC4)就可以完成工作,你不需要删除它。

cvCvtColor(mat, rv, CV_RGBA2BGR);

cvCvtColor需要两个IplImage*作为参数,你给它一个cv::Mat*和一个IplImage*,这是行不通的。将第一个mat替换为&iplImage,或者只是一致地使用c ++接口。