Search code examples
javaandroidopencvwrapperjavacv

Using method convertTo in opencv java wrapper


any body please help me to understand how to use method convertTo in JavaCV. i was trying and searching a lot of time and not find the proper answer. so my problem is, when i try to convert type of mat from gray image to CV_32F and try to display it in android screen it will give me no result. this my source :

    Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGBA2GRAY, 1); // dst is gray image
    dst.convertTo(dst_f, CvType.CV_32F, 1./255, 0); //convert dst to CV_32F with optional scale
    Imgproc.cvtColor(dst_f, src, Imgproc.COLOR_GRAY2RGBA, 4); // to display it in android before convert to bitmap

I was trying also in opencv C++ with this code and it run smoothly :

    imshow("dst", image);
    cvtColor(image, dst, CV_BGR2GRAY);
    dst.convertTo(dst_f, CV_32F, 1.0/255, 0);
    imshow("dst_f", dst_f);

UPDATED :

I think i wrong when i try to display image online in android screen. i don't know how to display it altough i knew that android need 4 channel to display image in screen. but when i convert gray to CV_32F image type and i try to display with same code like above and it run smoothly without no result.


Solution

  • After some research and Experiment, i just got my golden answer, here it is :

    Android can only display 4 channels image in the screen so you need to convert it to 4 channels (RGBA), but before you convert to RGBA/BGRA you have to change Mat image to CV_8U with same scaled. just look at this example :

    Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGBA2GRAY, 1); 
    dst.convertTo(dst_f, CvType.CV_32F, 1./255, 0);    
    dst_f.convertTo(final, CvType.CV_8U, 255, 0); 
    Imgproc.cvtColor(final, src, Imgproc.COLOR_GRAY2RGBA, 4);
    

    With above code, your code will work perfectly in Android screen, but it will give you a broken picture if you try to save it to jpg image or other picture extension. if you want to save it to sdcard you can use this source :

    Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2GRAY, 1);
    dst.convertTo(dst_f, CvType.CV_32F, 1.0/255, 0); // Convert Mat image to CV_32F and scale it to 1.0/255
    dst_f.convertTo(final, CvType.CV_32F, 255, 0); //Convert it Back to Default type before
    Imgproc.cvtColor(final, roi, Imgproc.COLOR_GRAY2RGB, 0);
    Imgproc.cvtColor(roi, roi, Imgproc.COLOR_RGB2RGBA, 0);
    

    above all is my own experiment, if you wanna ask me something, i will answer as good as i can. Thanks. Hope this help others a lot