Home > Software engineering >  ImportError: Imageio Pillow requires Pillow, not PIL! on M1 Mac
ImportError: Imageio Pillow requires Pillow, not PIL! on M1 Mac

Time:05-15

This question might have been asked several times but I am not able to resolve the error. I have pillow, imageio and other libraries installed on my M1 Mac. But still when I am running below code I am getting error.

Note: I have created my environment using miniforge.

Code: image = imread(source_path '/' t[folder (batch*batch_size)].strip().split(';')[0] '/' imgs[item]).astype(np.float32)

If any other information is needed to resolve this happy to add it here.

Error:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Input In [11], in <cell line: 1>()
----> 1 model.fit(train_generator, steps_per_epoch=steps_per_epoch, epochs=num_epochs, verbose=1, 
      2                     callbacks=callbacks_list, validation_data=val_generator, 
      3                     validation_steps=validation_steps, class_weight=None, workers=1, initial_epoch=0)

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/tensorflow/python/keras/engine/training.py:1133, in Model.fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1127   self._cluster_coordinator = cluster_coordinator.ClusterCoordinator(
   1128       self.distribute_strategy)
   1130 with self.distribute_strategy.scope(), \
   1131      training_utils.RespectCompiledTrainableState(self):
   1132   # Creates a `tf.data.Dataset` and handles batch and epoch iteration.
-> 1133   data_handler = data_adapter.get_data_handler(
   1134       x=x,
   1135       y=y,
   1136       sample_weight=sample_weight,
   1137       batch_size=batch_size,
   1138       steps_per_epoch=steps_per_epoch,
   1139       initial_epoch=initial_epoch,
   1140       epochs=epochs,
   1141       shuffle=shuffle,
   1142       class_weight=class_weight,
   1143       max_queue_size=max_queue_size,
   1144       workers=workers,
   1145       use_multiprocessing=use_multiprocessing,
   1146       model=self,
   1147       steps_per_execution=self._steps_per_execution)
   1149   # Container that configures and calls `tf.keras.Callback`s.
   1150   if not isinstance(callbacks, callbacks_module.CallbackList):

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/tensorflow/python/keras/engine/data_adapter.py:1364, in get_data_handler(*args, **kwargs)
   1362 if getattr(kwargs["model"], "_cluster_coordinator", None):
   1363   return _ClusterCoordinatorDataHandler(*args, **kwargs)
-> 1364 return DataHandler(*args, **kwargs)

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/tensorflow/python/keras/engine/data_adapter.py:1154, in DataHandler.__init__(self, x, y, sample_weight, batch_size, steps_per_epoch, initial_epoch, epochs, shuffle, class_weight, max_queue_size, workers, use_multiprocessing, model, steps_per_execution, distribute)
   1152 adapter_cls = select_data_adapter(x, y)
   1153 self._verify_data_adapter_compatibility(adapter_cls)
-> 1154 self._adapter = adapter_cls(
   1155     x,
   1156     y,
   1157     batch_size=batch_size,
   1158     steps=steps_per_epoch,
   1159     epochs=epochs - initial_epoch,
   1160     sample_weights=sample_weight,
   1161     shuffle=shuffle,
   1162     max_queue_size=max_queue_size,
   1163     workers=workers,
   1164     use_multiprocessing=use_multiprocessing,
   1165     distribution_strategy=ds_context.get_strategy(),
   1166     model=model)
   1168 strategy = ds_context.get_strategy()
   1170 self._current_step = 0

`enter code here`File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/tensorflow/python/keras/engine/data_adapter.py:809, in GeneratorDataAdapter.__init__(self, x, y, sample_weights, workers, use_multiprocessing, max_queue_size, model, **kwargs)
    805 super(GeneratorDataAdapter, self).__init__(x, y, **kwargs)
    807 # Since we have to know the dtype of the python generator when we build the
    808 # dataset, we have to look at a batch to infer the structure.
--> 809 peek, x = self._peek_and_restore(x)
    810 peek = self._standardize_batch(peek)
    811 peek = _process_tensorlike(peek)

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/tensorflow/python/keras/engine/data_adapter.py:866, in GeneratorDataAdapter._peek_and_restore(x)
    864 @staticmethod
    865 def _peek_and_restore(x):
--> 866   peek = next(x)
    867   return peek, itertools.chain([peek], x)

Input In [4], in generator(source_path, folder_list, batch_size)
     16 imgs = os.listdir(source_path '/'  t[folder   (batch*batch_size)].split(';')[0]) # read all the images in the folder
     17 for idx,item in enumerate(img_idx): #  Iterate iver the frames/images of a folder to read them in
---> 18     image = imread(source_path '/'  t[folder   (batch*batch_size)].strip().split(';')[0] '/' imgs[item]).astype(np.float32)
     20     #crop the images and resize them. Note that the images are of 2 different shape 
     21     #and the conv3D will throw error if the inputs in a batch have different shapes
     22     # Let us resize all the images.Let's use PIL.Image.NEAREST (use nearest neighbour) resampling filter. 
     23     resized_image = resize(image,(y,z)) ##default resample=1 or 'P' which indicates PIL.Image.NEAREST

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/imageio/core/functions.py:206, in imread(uri, format, **kwargs)
    202     raise TypeError('Invalid keyword argument "mode", '
    203                     'perhaps you mean "pilmode"?')
    205 # Get reader and read first
--> 206 reader = read(uri, format, 'i', **kwargs)
    207 with reader:
    208     return reader.get_data(0)

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/imageio/core/functions.py:123, in get_reader(uri, format, mode, **kwargs)
    121     format = formats[format]
    122 else:
--> 123     format = formats.search_read_format(request)
    124 if format is None:
    125     raise ValueError('Could not find a format to read the specified file '
    126                      'in mode %r' % mode)

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/imageio/core/format.py:673, in FormatManager.search_read_format(self, request)
    671 # Select the first that can
    672 for format in selected_formats:
--> 673     if format.can_read(request):
    674         return format
    676 # If no format could read it, it could be that file has no or
    677 # the wrong extension. We ask all formats again.

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/imageio/core/format.py:188, in Format.can_read(self, request)
    183 def can_read(self, request):
    184     """ can_read(request)
    185     
    186     Get whether this format can read data from the specified uri.
    187     """
--> 188     return self._can_read(request)

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/imageio/plugins/pillow.py:97, in PillowFormat._can_read(self, request)
     96 def _can_read(self, request):
---> 97     Image = self._init_pillow()
     98     if request.mode[1] in (self.modes   '?'):
     99         if self.plugin_id in Image.OPEN:

File ~/miniforge3/envs/tensorflow/lib/python3.9/site-packages/imageio/plugins/pillow.py:81, in PillowFormat._init_pillow(self)
     79 import PIL
     80 if not hasattr(PIL, 'PILLOW_VERSION'):  # pragma: no cover
---> 81     raise ImportError('Imageio Pillow requires '
     82                       'Pillow, not PIL!')
     83 from PIL import Image
     84 self._Image = Image

ImportError: Imageio Pillow requires Pillow, not PIL!

CodePudding user response:

the library you are using is buggy, I would recommend reporting it to them

PILLOW_VERSION was removed in pillow 9.0.0:

https://github.com/python-pillow/Pillow/blob/638ba163f425fd586ded4780b8024536819922f8/src/PIL/__init__.py#L19

# VERSION was removed in Pillow 6.0.0.
# PILLOW_VERSION was removed in Pillow 9.0.0.
# Use __version__ instead.
__version__ = _version.__version__

a hacky workaround would be to comment out that line

CodePudding user response:

I came to know the below resolution. It worked for me.

This is an issue with imageio, resolved in Apr 2018: https://github.com/imageio/imageio/pull/336

Please update to imageio 2.4.0 or newer.

  • Related