cgohlke / tifffile

Read and write TIFF files
https://pypi.org/project/tifffile
BSD 3-Clause "New" or "Revised" License
539 stars 155 forks source link

UnicodeEncodeError when using tifffile #44

Closed sebi06 closed 3 years ago

sebi06 commented 3 years ago

Hi,

I cannot figure out why I run into this problem: Any hints what goes wrong

tifffile: 2020.12.8 Python 3.7.8 | packaged by conda-forge | (default, Nov 27 2020, 18:48:03) [MSC v.1916 64 bit (AMD64)] on win32

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\cellpose\lib\site-packages\tifffile\tifffile.py", line 7332, in overwrite
    value = value.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xb5' in position 555: ordinal not in range(128)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:/Users/m1srh/Documents/GitHub/czi_demos/test_nuclei_segmentation.py", line 426, in <module>
  File "c:/Users/m1srh/Documents/GitHub/czi_demos/test_nuclei_segmentation.py", line 426, in <module>
    img.close()
  File "C:\ProgramData\Anaconda3\envs\cellpose\lib\site-packages\tifffile\tifffile.py", line 2771, in __exit__
    self.close()
  File "C:\ProgramData\Anaconda3\envs\cellpose\lib\site-packages\tifffile\tifffile.py", line 2764, in close
    self._write_image_description()
  File "C:\ProgramData\Anaconda3\envs\cellpose\lib\site-packages\tifffile\tifffile.py", line 2753, in _write_image_description
    self._descriptiontag.overwrite(self, description, erase=False)
  File "C:\ProgramData\Anaconda3\envs\cellpose\lib\site-packages\tifffile\tifffile.py", line 7336, in overwrite
    ) from exc
ValueError: TIFF strings must be 7-bit ASCII
sebi06 commented 3 years ago

I might be related to using 'µm' as unit for scale. But from what I know this worked so far.

cgohlke commented 3 years ago

Hi Sebastian. Yes, the micron character is not in the 7-bit ASCII range as required by the TIFF standard. You can pass your own encoded byte string instead of a unicode str, e.g. imwrite(filename, data, description='micron \xB5'.encode('latin-1'))). See also #17.

sebi06 commented 3 years ago

Ok, thx. I was not aware of this. And thanks for the tip.