Does OpenCV support HEIC format in Python 3.6 for imread() and imwrite() functions?

Whether OpenCV’s imread() and imwrite() functions support the HEIC (High Efficiency Image Coding) file format. In my project, I need to read images, possibly in the HEIC format, using OpenCV’s cv2.imread() function, and similarly, I would need to write or save images using cv2.imwrite().
Given that HEIC is a relatively newer file format compared to traditional formats like JPEG or PNG, I am uncertain about OpenCV’s compatibility with HEIC.

1 Like

Hey Sahil!

OpenCV’s support for different image formats largely depends on the underlying image codecs installed on your system. The standard OpenCV distribution typically supports popular formats like JPEG, PNG, and BMP.

However, HEIC is a newer format and might not be supported natively by OpenCV, especially if the appropriate HEIC codecs are not installed on your system.

If OpenCV doesn’t natively support HEIC, is there a way I can work with HEIC files in my project?

To handle HEIC files in your project, you might need to convert them to a format that OpenCV recognizes, like JPEG or PNG, before processing. You can use a separate library or tool to perform this conversion. Libraries like libheif, which can handle HEIC files, could be used for this purpose. In Python, you can use a library like Pillow first to convert the HEIC image to a more common format and then process it with OpenCV.

Here’s a basic workflow:

  1. Convert the HEIC image to JPEG or PNG using a conversion library.
  2. Read the converted image with OpenCV using cv2.imread().
  3. Process the image as required for your face detection project.
  4. If needed, save the processed image using cv2.imwrite().

This approach allows you to leverage OpenCV’s powerful image-processing capabilities while bypassing its limitations with HEIC files.

Here is a simple example using the Pillow library. Note that you’ll need to have libheif installed for Pillow to handle HEIC files:

from PIL import Image

def convert_heic_to_jpeg(heic_path, jpeg_path):
    with Image.open(heic_path) as img:
        img.convert('RGB').save(jpeg_path, 'JPEG')

# Usage
convert_heic_to_jpeg('path/to/input.heic', 'path/to/output.jpeg')

This function opens a HEIC file, converts it to RGB (necessary for JPEG), and then saves it as a JPEG file. You can then use this JPEG file with OpenCV for your face detection project.