Austin Gayler
Austin Gayler

Reputation: 4356

Trouble converting 32FC3 to 8UC3 to save image as jpg in OpenCV

I'm reading a series of jpgs and then using OpenCV's convertTo(Mat, CV_32FC3) function to convert them:

    Mat outImg = Mat.zeros(tmp.size(), CV_32FC3);
    Mat curImg = new Mat();

    for (int i = 0; i < imgCount; i++) {
        fname = fp + String.format("%02d", i) + ".jpg";
        curImg = imread(fname);
        curImg.convertTo(curImg, CV_32FC3);
        Imgproc.accumulateWeighted(curImg, outImg, 0.01);
    }

    outImg.convertTo(outImg, CV_8UC3, ?????);
    imwrite(fp + "output" + "-" + curTime + ".jpg", outImg);

I guess I have to convert it back to a CV_8UC3 before I can write it to a jpg, but I'm not sure how to do that. I found some other SO answer that said I needed to scale it by multiplying it by 255 (the third parameter in convertTo()), but doing so makes the output completely white. 100 is a better number but there's still a significant amount of clipping (not to mention 255 being the most logical number for an 8 bit picture). Is this the right way to do this? If not, how can I save the image correctly?

Upvotes: 2

Views: 2657

Answers (1)

kiranpradeep
kiranpradeep

Reputation: 11201

To answer your question, the conversions would have been

curImg.convertTo(curImg, CV_32FC3, 1/255.0);
outImg.convertTo(outImg, CV_8UC3, 255);

But, I assume your intention here is noise reduction by averaging images. If that is the case, the conversion to/from CV_32FC3 is not required.. What ever was the depth of your input image, imread( with default flag CV_LOAD_IMAGE_COLOR ) would load it as an 8 bit image ( e.g. 8UC3 assuming color image). So we can average images without any conversion.

Rewriting as below.

Mat outImg;
for (int i = 0; i < imgCount; i++) {
    fname = fp + String.format("%02d", i) + ".jpg";
    //load as 8 bit image what ever was input image depth
    Mat curImg = imread(fname);
    Imgproc.accumulateWeighted(curImg, outImg, 0.01);
}
imwrite(fp + "output" + "-" + curTime + ".jpg", outImg);

Upvotes: 5

Related Questions