Skip to content

[Python] Use OpenCV To Convert JP2 To PNG Or JPEG

What is JPEG 2000 (JP2)

JPEG 2000, also known as JP2 in the title of this article, is a format for image files, and the extension is .jp2. The compression ratio of JP2 is better than JPEG.

However, up to now, most mainstream browsers do not support this format, and it is difficult for ordinary operating systems to open pictures in JP2.

This is due to the patent problem of JP2 encoding and decoding.


How To Convert JP2 File

However, if we want to convert files in JP2 files, it is not impossible.

At present, the more reliable method I have tried is to use OpenCV to convert the file format.

The following is a demonstration using a python program.

First we need to confirm is whether there is OpenCV in the python environment.

If it is not in the environment, you need to install it first using the following command:

pip3 install opencv-python


After installation, let’s take a look at a simple sample code:

# coding: utf-8
import cv2


# Convert
image = cv2.imread('test.jp2')
cv2.imwrite('test.png', image)

Use imread() to read the picture, and then use imwrite() to store the picture in different formats. This is a success, very easy.

If you got the following error message during imread():

cv2.error: OpenCV(4.2.0) 
/io/opencv/modules/imgcodecs/src/grfmt_jpeg2000.cpp:
104: error: (-213:The function/feature is not
implemented) imgcodecs: Jasper (JPEG-2000) codec is
disabled. You can enable it via 'OPENCV_IO_ENABLE_JASPER'
option. Refer for details and cautions here:
https://github.com/opencv/opencv/issues/14058 in function
'initJasper'


You need to add environment variables:

export OPENCV_IO_ENABLE_JASPER=true


Or maybe you can add the following line in the head of python file.

os.environ['OPENCV_IO_ENABLE_JASPER'] = 'true'



This way the code can work properly.


Reference


Read More

Leave a ReplyCancel reply

Exit mobile version