当我尝试在openCV中反转UIImage时,为什么我的应用程序崩溃?

时间:2018-11-09 01:07:43

标签: opencv image-processing

我已经研究了很长时间了,由于某种原因,我无法获得以下代码。

+(UIImage *)processInvertedImage:(UIImage *)image {

    cv::Mat mat;
    UIImageToMat(image, mat);   ///this is CV_8U from iPhone camera

    cv::Mat output;
    mat.convertTo(output, CV_32F);   ///cv::invert() requires CV_32F!! (apparently)

    cv::Mat invert;
    cv::invert(output, invert);     /// app crashes here, error message below

    cv::Mat gray;
    cv::cvtColor(invert, gray, CV_RGB2GRAY);  

    UIImage *binImg = MatToUIImage(gray);

    return binImg;

}

我收到以下错误代码:

libc ++ abi.dylib:终止于cv :: Exception类型的未捕获异常:OpenCV(3.4.2)/ Volumes / build-storage / build / 3_4_iOS-mac / opencv / modules / core / src / lapack。 cpp:839:错误:(-215:断言失败)类型== 5 ||在功能“反转”中输入== 6

此类型是什么== 5 ||类型== 6是什么意思?

1 个答案:

答案 0 :(得分:0)

让我尝试永远回答这个问题。 type == 5 || type == 6意味着您需要使用CV_32FCV_64F。但是,UIImage通常有4个频道。我敢打赌,您的UIImageToMat产生了CV_8UC3类型的垫子。因此mat的类型为CV_8UC3,而output的类型很可能为CV_32FC3,而不仅仅是CV_32F。同样,当您使用cv::invert()时,您正在查看的是数学逆,即output * mat = identity_matrix

+(UIImage *)processInvertedImage:(UIImage *)image {

    cv::Mat mat;
    UIImageToMat(image, mat);   ///this is CV_8U from iPhone camera

    if (mat.type() == CV_8UC3) {
        NSLog(@"mat type is CV_8UC3"); // mostlikely this
    } else if (mat.type() == CV_8UC4){
        NSLog(@"mat type is CV_8UC4");
    }

    cv::Mat output;
    mat.convertTo(output, CV_32F);   ///cv::invert() requires CV_32F!! (apparently)
    if (output.type() == CV_32FC3){
        NSLog(@"output type is CV_32FC3"); // most likely this 
    }

    // this is really bad naming, since you seem to use namespace cv somewhere, 
    // as CV_32F doesn't have cv:: prefix
    cv::Mat invert;                
    cv::invert(output, invert);     /// app crashes here, error message below

    cv::Mat gray;
    cv::cvtColor(invert, gray, CV_RGB2GRAY);  

    UIImage *binImg = MatToUIImage(gray);

    return binImg;

}

编辑:如果需要逆处理 ,则可以执行与上一个问题类似的操作:

+(UIImage *)processInvertedImage:(UIImage *)image {
    cv::Mat mat;
    UIImageToMat(image, mat);

    // convert to RGB
    cv::Mat rgb
    cv::cvtColor(mat, rgb, COLOR_RGBA2RGB);

    // create mat of same size and type with values 255
    cv::Mat dummy(rgb.size(), rgb.type(), cv::Scalar(255,255,255));

    // three channels
    cv::Mat rgb_invert = dummy ^ rgb;

    cv::Mat gray;
    cv::cvtColor(rgb, gray, COLOR_RGB2GRAY);

    cv::Mat gray_invert = 255 ^ gray;

    // depending what invert you would like
    UIImage* binImg = MatToUIImage(rgb_invert);

    return binImg;
}