Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Can OpenCV write binarized image as 1-bit depth indexed PNG?

Hi there!

We're developing an Android app and looking for a tool for compressing doc images as much as possible. We're going to send them to a server for recognition and file size makes sense. Finally these images are binarized for recognition purposes (i.e. contain black and white colors only). We've considered a lot of variants but without success. Now we're trying to apply OpenCV for this namely to save these binarized images as PNG. We'd like to use indexed PNG with 1-bit depth as the most appropriate format for black&white only images. We tested this format manually and it worked quite well giving about 10 compression ratio (comparing JPEG). We found IMWRITE_PNG_BILEVEL parameter which looks relevant for our task. Its description says

Binary level PNG, 0 or 1, default is 0.

OK, we applied it like this

Bitmap image = BitmapFactory.decodeFile(inputFilePath);
Mat matrix = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1);
Utils.bitmapToMat(image, matrix);
MatOfInt parameters = new MatOfInt(
        Imgcodecs.CV_IMWRITE_PNG_COMPRESSION, 9,
        Imgcodecs.CV_IMWRITE_PNG_BILEVEL, 1
);
boolean result = Imgcodecs.imwrite(outputFilePath, matrix, parameters);

The problem is this gives false result and empty image files. We tried parameters in different combinations. If we set 0 for IMWRITE_PNG_BILEVEL (or remove it) the app creates correct files, otherwise files are empty. We couldn't find any explanation on this parameter excepting the quote above which is not too verbose. So far could anyone either give working example of using this parameter or point out an error in our code or provide some additional explanation on this? This parameter might be not appropriate for our needs at all, who knows? We're not experts in OpenCV and any help will be appreciated!