Cristian
Cristian

Reputation: 495

cv::Mat GRAY to RGBA and convert to UIImage

I have a 1 channel cv::Mat that I need to convert RGBA, whenever I do so the Image prints white(on IOS simulator).

UIImage *matToUIImage(cv::Mat grayMat){
    std::cout << grayMat.channels() << std::endl;
    //prints 1 

    cv::Mat alphaMat;
    cv::cvtColor(grayMat, alphaMat, CV_GRAY2BGRA);

    std::cout << alphaMat.channels() << std::endl;
    //prints 4

    alphaMat.convertTo(alphaMat, CV_8U);
    UIImage *finalImage = MatToUIImage(alphaMat);
    return finalImage;
}

enter image description here

when I run the same image without converting to alpha the image prints fine.

UIImage *matToUIImage(cv::Mat grayMat){
std::cout << grayMat.channels() << std::endl;
//prints 1 

alphaMat.convertTo(alphaMat, CV_8U);
UIImage *finalImage = MatToUIImage(alphaMat);
return finalImage;
}

enter image description here

Also when I try to edit convertTo method

// alphaExist = 1
alphaMat.convertTo(alphaMat, CV_8U, 1);

I get the same white image.

How I print Image in swift:

@IBOutlet weak var photoImageView: UIImageView!


@IBAction func convertImage(_ sender: UIButton) {
    photoImageView.image = OpenCVWrapper.convert(photoImageView.image)
}

Upvotes: 1

Views: 452

Answers (1)

Cristian
Cristian

Reputation: 495

All I had to do was convert the Mat to CV_8U before I converted it to RGBA.

UIImage *matToUIImage(cv::Mat grayMat){
    std::cout << grayMat.channels() << std::endl;
    //prints 1 

    grayMat.convertTo(grayMat, CV_8U);

    cv::Mat alphaMat;
    cv::cvtColor(grayMat, alphaMat, CV_GRAY2BGRA);

    std::cout << alphaMat.channels() << std::endl;
    //prints 4

    alphaMat.convertTo(alphaMat, CV_8U);
    UIImage *finalImage = MatToUIImage(alphaMat);
    return finalImage;
}

Upvotes: 1

Related Questions