Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with HEIC image file types in Python

The High Efficiency Image File (HEIF) format is the default when airdropping an image from an iPhone to a OSX device. I want to edit and modify these .HEIC files with Python.

I could modify phone settings to save as JPG by default but that doesn't really solve the problem of being able to work with the filetype from others. I still want to be able to process HEIC files for doing file conversion, extracting metadata, etc. (Example Use Case -- Geocoding)

Pillow

Here is the result of working with Python 3.7 and Pillow when trying to read a file of this type.

$ ipython
Python 3.7.0 (default, Oct  2 2018, 09:20:07)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from PIL import Image

In [2]: img = Image.open('IMG_2292.HEIC')
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-2-fe47106ce80b> in <module>
----> 1 img = Image.open('IMG_2292.HEIC')

~/.env/py3/lib/python3.7/site-packages/PIL/Image.py in open(fp, mode)
   2685         warnings.warn(message)
   2686     raise IOError("cannot identify image file %r"
-> 2687                   % (filename if filename else fp))
   2688
   2689 #

OSError: cannot identify image file 'IMG_2292.HEIC'

It looks like support in python-pillow was requested (#2806) but there are licensing / patent issues preventing it there.

ImageMagick + Wand

It appears that ImageMagick may be an option. After doing a brew install imagemagick and pip install wand however I was unsuccessful.

$ ipython
Python 3.7.0 (default, Oct  2 2018, 09:20:07)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from wand.image import Image

In [2]: with Image(filename='img.jpg') as img:
   ...:     print(img.size)
   ...:
(4032, 3024)

In [3]: with Image(filename='img.HEIC') as img:
   ...:     print(img.size)
   ...:
---------------------------------------------------------------------------
MissingDelegateError                      Traceback (most recent call last)
<ipython-input-3-9d6f58c40f95> in <module>
----> 1 with Image(filename='ces2.HEIC') as img:
      2     print(img.size)
      3

~/.env/py3/lib/python3.7/site-packages/wand/image.py in __init__(self, image, blob, file, filename, format, width, height, depth, background, resolution, pseudo)
   4603                     self.read(blob=blob, resolution=resolution)
   4604                 elif filename is not None:
-> 4605                     self.read(filename=filename, resolution=resolution)
   4606                 # clear the wand format, otherwise any subsequent call to
   4607                 # MagickGetImageBlob will silently change the image to this

~/.env/py3/lib/python3.7/site-packages/wand/image.py in read(self, file, filename, blob, resolution)
   4894             r = library.MagickReadImage(self.wand, filename)
   4895         if not r:
-> 4896             self.raise_exception()
   4897
   4898     def save(self, file=None, filename=None):

~/.env/py3/lib/python3.7/site-packages/wand/resource.py in raise_exception(self, stacklevel)
    220             warnings.warn(e, stacklevel=stacklevel + 1)
    221         elif isinstance(e, Exception):
--> 222             raise e
    223
    224     def __enter__(self):

MissingDelegateError: no decode delegate for this image format `HEIC' @ error/constitute.c/ReadImage/556

Any other alternatives available to do a conversion programmatically?

like image 869
j12y Avatar asked Jan 28 '19 04:01

j12y


People also ask

Can Python read HEIC files?

The most common python library for image modification is Pillow (PIL). It can handle almost all image formats, except for a few, among which High Efficiency Image File Format (HEIC), is one of them.

How do I use HEIC files?

HEIC files are the default format for images across your Apple devices, so it should be easy to open them on your Mac. Just right-click on the file and select Open with Preview – the file should then launch in the Preview program. Alternatively, you can import the files to your Photos app or upload them to Dropbox.

Can OpenCV read HEIC?

I did some research, and my conclusion is that OpenCV does not support . HEIC image format.

How to open HEIC images with Python?

Opening .HEIC images with Python. To be continued… | by Svensson | Medium The most common python library for image modification is Pillow (PIL). It can handle almost all image formats, except for a few, among which High Efficiency Image File Format (HEIC), is one of them.

What is a HEIC file?

HEIC stands for High Efficiency Image Container. The format is an updated variant of the High Efficiency Image Format (HEIF), traditionally used by Apple across its mobile devices. Apple uses HEIC for HEIF images.

How do I edit HEIC files in Photoshop?

Click on the File Handling tab. In the JPEG and TIFF Handling box, choose Automatically open JPEGs and HEICs with settings or Automatically open all supported JPEGs and HEICs from the drop-down menu. You can then open and edit your HEIC files like normal.

What is the best Python library for image modification?

The most common python library for image modification is Pillow (PIL). It can handle almost all image formats, except for a few, among which High Efficiency Image File Format (HEIC), is one of them. This is a rather common problem as it became the standard iPhone image format in iOS 11 released in 2017.


Video Answer


3 Answers

You guys should check out this library, it's a Python 3 wrapper to the libheif library, it should serve your purpose of file conversion, extracting metadata:

https://github.com/david-poirier-csn/pyheif

https://pypi.org/project/pyheif/

Example usage:

 import io

 import whatimage
 import pyheif
 from PIL import Image


 def decodeImage(bytesIo):

    fmt = whatimage.identify_image(bytesIo)
    if fmt in ['heic', 'avif']:
         i = pyheif.read_heif(bytesIo)

         # Extract metadata etc
         for metadata in i.metadata or []:
             if metadata['type']=='Exif':
                 # do whatever
        
         # Convert to other file format like jpeg
         s = io.BytesIO()
         pi = Image.frombytes(
                mode=i.mode, size=i.size, data=i.data)

         pi.save(s, format="jpeg")

  ...
like image 86
danial Avatar answered Oct 07 '22 22:10

danial


I was quite successful with Wand package : Install Wand: https://docs.wand-py.org/en/0.6.4/ Code for conversion:

   from wand.image import Image
   import os

   SourceFolder="K:/HeicFolder"
   TargetFolder="K:/JpgFolder"

   for file in os.listdir(SourceFolder):
      SourceFile=SourceFolder + "/" + file
      TargetFile=TargetFolder + "/" + file.replace(".HEIC",".JPG")
    
      img=Image(filename=SourceFile)
      img.format='jpg'
      img.save(filename=TargetFile)
      img.close()
like image 20
Richard Dvořák Avatar answered Oct 08 '22 00:10

Richard Dvořák


Consider using PIL in conjunction with pillow-heif:

pip3 install pillow-heif
from PIL import Image
from pillow_heif import register_heif_opener

register_heif_opener()

image = Image.open('image.heic')
like image 7
mara004 Avatar answered Oct 07 '22 23:10

mara004