-
I'm trying to load an input.HIF, crop it, and save output.HIF while keeping the format of the output image as close as possible to the format of the input image. In my case the input.HIF was created by a Sony ILCE-7M4. The camera seems to store the file with 10 bit luma & chroma, and uses 4:2:2 chroma sub sampling: $ exiftool input.HIF | grep -Ei "Bit Depth|Chroma Format"
Chroma Format : 4:2:2
Bit Depth Luma : 10
Bit Depth Chroma : 10 My initial approach was to use: import pillow_heif
pillow_heif.register_heif_opener()
heif = pillow_heif.open_heif('input.HIF')
img = heif.to_pillow()
img.load() # required?
bit_depth = heif.info.get('bit_depth', 8)
chroma = heif.info.get('chroma', '420')
print(f"Attempting to preserve Bit Depth: {bit_depth} and Chroma Subsampling: {chroma}")
# imagine the crop here using PIL `img.crop()`
img.save('output.HIF', t="HEIF", quality=-1, bit_depth=bit_depth, chroma=chroma) Which works but results in an output.HIF with only 8 bit: $ python test.py
Attempting to preserve Bit Depth: 10 and Chroma Subsampling: 422
$ exiftool output.HIF | grep -Ei "Bit Depth|Chroma Format"
Chroma Format : 4:2:2
Bit Depth Luma : 8
Bit Depth Chroma : 8 I've also tried to use heif = pillow_heif.open_heif('input.HIF', convert_hdr_to_8bit=False) Wich results in I could use heif.safe(): heif.save("output.HIF", format="HEIF", quality=-1, bit_depth=bit_depth, chroma=chroma) But then I don't have a PIL image for easy cropping. Any ideas on best practices how to load, crop & save such a HIF file while preserving the format? If it matters, I'm using Python 3.13.7, and pillow_heif 1.1.0: $ python --version
Python 3.13.7
$ pip list
Package Version
----------- -------
numpy 2.3.2
pillow 11.3.0
pillow_heif 1.1.0
pip 25.2 Any hints are appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
As a workaround to PIL's def crop_hif(input_path, output_path, rect):
heif = pillow_heif.open_heif(input_path, convert_hdr_to_8bit=False)
np_array = np.asarray(heif[0])
x, y, w, h = rect
cropped_np_array = np_array[y:y+h, x:x+w]
mode = heif[0].mode
size = (cropped_np_array.shape[1], cropped_np_array.shape[0])
data = cropped_np_array.tobytes()
new_heif_image = pillow_heif.from_bytes(mode=mode, size=size, data=data)
new_heif_image.save(output_path,
format="HEIF",
quality=-1,
bit_depth=heif.info.get('bit_depth', 8),
chroma=heif.info.get('chroma', '420'),
nclx_profile=heif.info.get('nclx_profile'),
exif=heif.info.get('exif'),
xmp=heif.info.get('xmp')) Are there better ways to handle/crop such HIFs? Any ideas are welcome. |
Beta Was this translation helpful? Give feedback.
The best way is to ask in the Pillow repo to prioritize developing 10/12 bit support (they have this issue)