Tuesday, October 1, 2024

How do you display an image using PILL?

PIL(Pillow) is another library that can be used to display images. Pillow can also be installed using pip in the Terminal as shown by running the code pip install Pillow


After installing Pillow , you can display the image using python code as shown.

---------------

from PIL import Image

# open the image file

image=Image.open('Images/TheKiss.jpg')

#Display the image

image.show()

-----------

When you run this code the image gets displayed.


When you use Image.open(), you should give the path either the absolute path or the path relative to the project, in the above the relative project is given ('Images/TheKiss.jpg).

Here is an example of using the absolute path (in the file system)

-------------

PIL import Image


# Open an image file image = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images
\TheKiss.jpg')

# Display the image
image.show()

-----------

You can see  the absolute path is used. The code gets run and you see the same image. 



If you omit the 'r' in front of the absolute path, you will get an Unicode error. The 'r' tells the interpreter to treat it as 'raw' text.

If you right click the image you can access the image path, both relative and absolute.



PyCharm does a pretty good job providing timely help with drop-down hints, code completion and syntax highlighting.










No comments: