如何在Python中使用HEIC图像文件类型

j12*_*12y 8 python python-3.x heif heic

将图像从iPhone空投到OSX设备时,默认为高效率图像文件(HEIF)格式。我想用Python编辑和修改这些.HEIC文件。

我可以修改手机设置以默认将其另存为JPG,但这并不能真正解决能够使用其他文件类型的问题。我仍然希望能够处理HEIC文件以进行文件转换,提取元数据等。(示例用例-地理编码

枕头

这是尝试读取此类文件时使用Python 3.7和Pillow的结果。

$ 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'
Run Code Online (Sandbox Code Playgroud)

似乎已请求在python-pillow中提供支持(#2806),但那里存在许可/专利问题,导致无法在此使用它。

ImageMagick +魔杖

似乎可以选择ImageMagick。经过一遍brew install imagemagickpip install wand但是我没有成功。

$ 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
Run Code Online (Sandbox Code Playgroud)

还有其他替代方法可以通过编程进行转换吗?

mar*_*004 65

考虑将 PIL 与pillow-heif结合使用:

pip3 install pillow-heif
Run Code Online (Sandbox Code Playgroud)
from PIL import Image
from pillow_heif import register_heif_opener

register_heif_opener()

image = Image.open('image.heic')
Run Code Online (Sandbox Code Playgroud)

也就是说,我不知道有任何许可/专利问题会阻止 Pillow 中的 HEIF 支持(请参阅)。AFAIK,libheif只要您不将 HEIF 解码器与设备捆绑在一起并满足 LGPLv3 许可证的要求,就会被广泛采用并免费使用。

  • @OsamaBinSaleem 当然,像平常一样执行 `image.save(filepath, format="jpg", ...)` 即可。 (5认同)
  • 这很棒。我认为这是迄今为止所有答案中最简单、最直接的方法,因此应该被接受为@j12y 问题的答案。 (2认同)

dan*_*ial 21

你们应该看看这个库,它是libheif库的 Python 3 包装器,它应该用于文件转换,提取元数据:

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

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

用法示例:

 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")

  ...
Run Code Online (Sandbox Code Playgroud)

  • fwiw,我尝试在 Windows 上安装 `pyheif` 并遇到了 [this](https://github.com/david-poirier-csn/pyheif/issues/2) 问题。事实证明“pyheif”与 Windows 不兼容。 (3认同)
  • 你能举一些“做任何事情”的例子吗?这里的“metadata['data']”似乎是“bytes”类型。但是当我尝试: `metadata['data'].decode('utf-8'))` 时,我看到: `UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 27 中的字节 0x86:无效的起始字节` (2认同)

ale*_*ken 12

这是在保持元数据完整的同时进行heic转换的另一种解决方案。jpg它基于mara004上面的解决方案,但是我无法以这种方式提取图像时间戳,因此必须添加一些代码。在应用该功能之前放入heic文件:dir_of_interest

import os
from PIL import Image, ExifTags
from pillow_heif import register_heif_opener
from datetime import datetime
import piexif
import re
register_heif_opener()

def convert_heic_to_jpeg(dir_of_interest):
        filenames = os.listdir(dir_of_interest)
        filenames_matched = [re.search("\.HEIC$|\.heic$", filename) for filename in filenames]

        # Extract files of interest
        HEIC_files = []
        for index, filename in enumerate(filenames_matched):
                if filename:
                        HEIC_files.append(filenames[index])

        # Convert files to jpg while keeping the timestamp
        for filename in HEIC_files:
                image = Image.open(dir_of_interest + "/" + filename)
                image_exif = image.getexif()
                if image_exif:
                        # Make a map with tag names and grab the datetime
                        exif = { ExifTags.TAGS[k]: v for k, v in image_exif.items() if k in ExifTags.TAGS and type(v) is not bytes }
                        date = datetime.strptime(exif['DateTime'], '%Y:%m:%d %H:%M:%S')

                        # Load exif data via piexif
                        exif_dict = piexif.load(image.info["exif"])

                        # Update exif data with orientation and datetime
                        exif_dict["0th"][piexif.ImageIFD.DateTime] = date.strftime("%Y:%m:%d %H:%M:%S")
                        exif_dict["0th"][piexif.ImageIFD.Orientation] = 1
                        exif_bytes = piexif.dump(exif_dict)

                        # Save image as jpeg
                        image.save(dir_of_interest + "/" + os.path.splitext(filename)[0] + ".jpg", "jpeg", exif= exif_bytes)
                else:
                        print(f"Unable to get exif data for {filename}")
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以使用该pillow_heif库以与 PIL 兼容的方式读取 HEIF 图像。

下面的示例将导入 HEIF 图片并以png格式保存。

from PIL import Image
import pillow_heif

heif_file = pillow_heif.read_heif("HEIC_file.HEIC")
image = Image.frombytes(
    heif_file.mode,
    heif_file.size,
    heif_file.data,
    "raw",
)

image.save("./picture_name.png", format="png")
    
Run Code Online (Sandbox Code Playgroud)


小智 5

添加到 danial 的答案中,我只需要稍微修改字节数组即可获得有效的数据流以供进一步工作。前 6 个字节是 'Exif\x00\x00' .. 删除这些将为您提供原始格式,您可以将其导入任何图像处理工具。

import pyheif
import PIL
import exifread

def read_heic(path: str):
    with open(path, 'rb') as file:
        image = pyheif.read_heif(file)
        for metadata in image.metadata or []:
            if metadata['type'] == 'Exif':
                fstream = io.BytesIO(metadata['data'][6:])

    # now just convert to jpeg
    pi = PIL.Image.open(fstream)
    pi.save("file.jpg", "JPEG")

    # or do EXIF processing with exifread
    tags = exifread.process_file(fstream)
Run Code Online (Sandbox Code Playgroud)

至少这对我有用。

  • 使用您的代码,当我传递 HEIC 文件路径时,我得到 `PIL.UnidentifiedImageError: 无法识别图像文件 &lt;_io.BytesIO object at 0x109aefef0&gt;`。 (2认同)

Pid*_*hon 5

这将从 heic 文件中获取 exif 数据

import pyheif
import exifread
import io

heif_file = pyheif.read_heif("file.heic")

for metadata in heif_file.metadata:

    if metadata['type'] == 'Exif':
        fstream = io.BytesIO(metadata['data'][6:])

    exifdata = exifread.process_file(fstream,details=False)

    # example to get device model from heic file
    model = str(exifdata.get("Image Model"))
    print(model)
Run Code Online (Sandbox Code Playgroud)


小智 5

我使用 Wand 包非常成功:安装 Wand:https ://docs.wand-py.org/en/0.6.4/ 转换代码:

   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()
Run Code Online (Sandbox Code Playgroud)

  • 看来 ImageMagick(Wand 使用的低级库)不支持某些发行版的开箱即用的包管理器(例如:Centos 8)中的 heic delegate。 (2认同)

Ale*_*kun 5

从 version 开始0.10.0,就变得简单多了。

使用 OpenCV 将 8/10/12 位 HEIF 文件保存为 8/16 位 PNG:

import numpy as np
import cv2
from pillow_heif import open_heif

heif_file = open_heif("images/rgb12.heif", convert_hdr_to_8bit=False, bgr_mode=True)
np_array = np.asarray(heif_file)
cv2.imwrite("image.png", np_array)
Run Code Online (Sandbox Code Playgroud)

对于版本 <0.10.0

使用 OpenCV 和 Pillow-heif 处理 HDR(10/12) 位 HEIF 文件的示例:

import numpy as np
import cv2
import pillow_heif

heif_file = pillow_heif.open_heif("images/rgb12.heif", convert_hdr_to_8bit=False)
heif_file.convert_to("BGRA;16" if heif_file.has_alpha else "BGR;16")
np_array = np.asarray(heif_file)
cv2.imwrite("rgb16.png", np_array)
Run Code Online (Sandbox Code Playgroud)

此示例的输入文件可以是 10 或 12 位文件。


Tro*_*ler 0

我面临着和你完全相同的问题,想要一个 CLI 解决方案。做了一些进一步的研究,似乎 ImageMagick需要委托库libheif。libheif 库本身似乎也有一些依赖项。

我还没有成功地让其中任何一个发挥作用,但我会继续尝试。我建议您检查这些依赖项是否可用于您的配置。

  • 谢谢你的这个标记,它会很有用的。 (2认同)