How to open image given its full path

What’s the proper way to open one single image given a full path??
I found get_image_files but this seems to work only with folders!!

My original problem is I’m trying to generate similar images but with different brightness level like this

from fastai2.vision.transform import brightness

image = PILImage.create(imgs[idx])
fig, axs = plt.subplots(1,5,figsize=(12,4))
for change, ax in zip(np.linspace(0.1,0.9,5), axs):
    brightness(image, change).show(ax=ax, title=f'change={change:.1f}')

But. the above fails with the following error

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-1ddac5f7ce63> in <module>()
      2 fig, axs = plt.subplots(1,5,figsize=(12,4))
      3 for change, ax in zip(np.linspace(0.1,0.9,5), axs):
----> 4     brightness(image, change).show(ax=ax, title=f'change={change:.1f}')

1 frames
/usr/local/lib/python3.6/dist-packages/fastai/vision/image.py in calc(self, x, *args, **kwargs)
    473     def calc(self, x:Image, *args:Any, **kwargs:Any)->Image:
    474         "Apply to image `x`, wrapping it if necessary."
--> 475         if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs)
    476         else:          return self.func(x, *args, **kwargs)
    477 

AttributeError: 'PILImage' object has no attribute 'lighting'

The above fails because my image was a PIL image not a fastai2 Image, so that’s why I’m trying to open the image with fastai2 API.

You are mixing fastai v2 and v1 code, this brightness you are using comes from fastai v1.

Yeah I realized the mistake after looking at the code base (I thought that part didn;t change). But still couldn’t figure it how to do with fastai2, I’ve endup using PIL for everything (open image and apply transformations)

image = PILImage.create(imgs[idx])
tfm = PIL.ImageEnhance.Brightness(image)
factors = np.linspace(0.1, 0.9, 9)
images = [tfm.enhance(f) for f in factors]

fig, axs = plt.subplots(1, len(factors), figsize=(20,10))
for index, ax in enumerate(axs):
  ax.imshow(images[index])
  ax.set_title(label=f'brightness={factors[index]:.1f}')

Which gives me

But still would be interested to know how I could achieve this with fastai2

By the way, I found how to open an image

im = Image.open(imgs[idx])
im_t = cast(array(im), TensorImage)

But still not sure how to get the different level of brighness, im_t.brighness(factor) does not work!!

No, it’s a batch transform, so you need to apply it on a batch of images.

so I guess I have to make a batch of one image?
we used to have one_item in v1, what;s the equivalent in v2?

You can use this to get a batch of one image:

def repeat_one(source, n=64):
    """Single image helper for displaying batch"""
    return [get_image_files(source)[9]]*n

If you want to play around with image augmentations you could also look at this

1 Like