Monday, October 28, 2024

How do you install matplotlib for python?

 

We have seen earlier how to install PIL and OpenCV to visualize images. Matplotlib is yet another library for creating complex plots and graphs.

 Each of these graphic libraries have their own application area:

PIL(Pillow): Great for simple manipulations like cropping, resizing and adding filters. Easy to use but not for extensive visualizations.

OpenCV: Great for real-time computer vision tasks and image processing and lend itself to feature detection, object recognition and video analysis.

Matplotlib: Great for complex plots, graphs,  and charts. Highly customizable.


Installing Matplotlib

Herein, I consider installing matplotlib in the PyCharm IDE that was used for PIL and OpenCV. You can use either the python interpreter to install the library package or the virtual terminal.

In the PyCharm IDE locate the Packages icon highlighted in blue. You can see other packages from earlier installs like pip, pillow, etc. 


In the search box type 'matplotlib' and click Install on the right


There was an error that indicated it is being used. However, it is not installed on this machine in any other program. If this works for you you are in luck.


The virtual terminal is another way to install packages. Locate the Terminal icon in PyCharm. The command line is displayed on the right. 


Type in the following : pip install matplotlib

This should install matplotlib. The program came back saying that it is already present in the site packages. 

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

(.venv) C:\Users\hoden\OneDrive\Desktop\PyCharm\PIL>pip install matplotlib

Requirement already satisfied: matplotlib in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (3.9.2)Requirement already satisfied: contourpy>=1.0.1 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (1.3.0)Requirement already satisfied: cycler>=0.10 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (0.12.1)Requirement already satisfied: fonttools>=4.22.0 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (4.54.1)Requirement already satisfied: kiwisolver>=1.3.1 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (1.4.7)Requirement already satisfied: numpy>=1.23 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (2.1.1)Requirement already satisfied: packaging>=20.0 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (24.1)Requirement already satisfied: pillow>=8 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (10.4.0)Requirement already satisfied: pyparsing>=2.3.1 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (3.2.0)Requirement already satisfied: python-dateutil>=2.7 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from matplotlib) (2.9.0.post0)  Requirement already satisfied: six>=1.5 in c:\users\hoden\pycharmprojects\exploreimage\.venv\lib\site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)[notice] A new release of pip is available: 23.2.1 -> 24.3.1[notice] To update, run: C:\Users\hoden\PycharmProjects\exploreImage\.venv\Scripts\python.exe -m pip install --upgrade pi

And, indeed it was. The reason for this is perhaps the project files are not in the virtual environment. 

Anyway, before you use matplotlib in your python project, you need to import the plotting routine using 

Import matplotlib.pyplot as plt

Usage of matplotlib 

Python code for displaying an image. 

We will use the same RGB.png image as in the earlier posts.

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

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# Load the image
image = mpimg.imread(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_2\RGB.png')
# Display the image
plt.imshow(image)
plt.axis('off')
# Hide axes for a cleaner look
plt.title('Displayed Image')
plt.show()

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

The following image gets displayed:


What display device matplotlib uses to display an image?

Matplotlib uses a backend to display images and plots. The backend is responsible for rendering the visualizations to the screen or saving them to a file. By default, Matplotlib selects the appropriate backend based on your environment. Some common backends are:

  • TkAgg: Uses the Tkinter library for rendering.

  • Qt5Agg: Uses the Qt5 library for rendering.

  • MacOSX: Used for rendering on macOS.

  • GTK3Agg: Uses the GTK3 library for rendering.

  • Agg: Used for rendering to files without displaying on screen.

How to check the display device used for rendering:

The following code is used to check the display device:

Import matplotlib
print(matplotlib.get_backend())

On my Windows 11 laptop, it appears to use the TkAgg library for rendering as I get a reply 'tkagg' for the above code.





Sunday, October 13, 2024

Do these libraries PIL and OpenCV produce exactly the same image, or will there be changes in the rendered images?

 In earlier posts we have seen how images can be displayed using PIL and OpenCV.

Now the question is will these two methods look at the same input image and display the same way?

Here is the chosen image in PNG format, I just created using PAINT. The idea is colors may change, but the text will remain same.

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

Using OpenCV

import cv2


# Load the image from file

image = cv2.imread(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_2\RGB.png'

# Display the image in a window

cv2.imshow('Loaded Image', image)

# Wait for a key press and close the window

cv2.waitKey(0)

cv2.destroyAllWindows()

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

Using PILLow or PILL

from PIL import Image

# Open an image file

image = Image.open(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_2\RGB.png')

# Display the image

image.show()

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

The images displayed by the two codes are as shown:



Displayed Image: Using OpenCV
Displayed Image: Using PIl

What I found using PyCharm and a chosen image was that there was no difference. They displayed the same way without any changes to color. The only difference is that the image displayed using OpenCV has a slight cut-off in the left side. This may be corrected by placing the image in the center of a predesigned canvas.

What do the AI assistants say:

However, I decided to quiz the AI tools available on the web Co_Pilot, Gemini and Meta AI.

Gemini's answer:

In most cases, these two methods will display the image with minimal to no noticeable differences. However, there are some potential scenarios where there might be slight variations:

1. Color Space:

OpenCV: By default, OpenCV loads images in BGR (Blue, Green, Red) color space.

Pillow: Pillow loads images based on the image format's native color space (usually RGB for common formats).

This difference is usually negligible for human perception, but it's important to be aware of if you're doing further processing that relies on specific color channels. You can convert the color space in OpenCV using cv2.cvtColor(image, cv2.COLOR_BGR2RGB).

note: Looks like it is not the default behaviour.

2. Alpha Channel Handling:

Images with an alpha channel (transparency information) might be handled slightly differently between the libraries. In most cases, both will display the image with transparency preserved, but there could be subtle differences in how the alpha channel information is interpreted.

3. Advanced Image Formats:

Some uncommon image formats may be supported by one library but not the other, leading to different behavior. However, common formats like JPEG, PNG, and BMP should be handled identically.

In conclusion:

For most display purposes, the two methods will produce visually identical results. However, if you need precise control over color space, alpha channel handling, or are working with uncommon formats, understanding the potential differences between OpenCV and Pillow is important.


Co-Pilot's answer:

The two methods of displaying an image using OpenCV and PIL (Pillow) will not produce exactly the same rendered image due to differences in how each library handles image loading and display. Here are the key differences:

OpenCV

Color Format: OpenCV loads images in BGR format by default. This means that the colors might appear different if you don’t convert the image to RGB before displaying it.

Display Window: OpenCV uses its own windowing system (cv2.imshow) to display images. This window is managed by OpenCV and has its own look and feel.

PIL (Pillow)

Color Format: PIL loads images in RGB format by default. This means that the colors will be displayed as expected without any need for conversion.

Display Method: PIL uses the default image viewer of your operating system to display images (image.show()). This means the image will be displayed in whatever application is set as the default for viewing images on your system.

Summary

Color Handling: OpenCV displays images in BGR format, which can cause color inversion if not converted to RGB. PIL displays images in RGB format.

Display Method: OpenCV uses its own window, while PIL relies on the system’s default image viewer



Meta AI's answer:

Do OpenCV and PIL display the same image in the same way without any color differences?

OpenCV and PIL (Python Imaging Library) handle image display differently, which can result in color differences.

*OpenCV:*


1. Default color space: BGR (Blue, Green, Red)

2. Displays images in BGR format

3. Uses cv2.imshow() function for display


*PIL:*


1. Default color space: RGB (Red, Green, Blue)

2. Displays images in RGB format

3. Uses Image.show() or Image.display() functions

Due to this difference in color spaces:

- Images displayed using OpenCV will have a different color representation compared to PIL.


It is being said that the AI agents greatly help in computer coding. I would say, although they may be working from the same databank of information, they need not provide the same answer. The developer has to know stuff beyond just the codes.

Jump to changing color with Python:

https://hodentekhelp.blogspot.com/2024/11/how-do-you-work-with-color-images-in.html

Wednesday, October 2, 2024

How do I install OpenCV to study images?

 Previously, we have seen how to install OpenCV using PIP.

Now we will see how to work with OpenCV.

In PyCharm, the default python file name is main.py. I already have a main.py and I will create a new python file as shown in the picture. 


When you create a new python file you can give a name to it, main-OpenCV.py herein.

main_opencv.py gets added to the project. The code window on the right is empty and starts at line 1.


Now let us look at the same image as in the previous using PIL.

Run the following code in main-OpenCV as shown.

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

import cv2

# Load the image from file

image = cv2.imread('Images/TheKiss.jpg')


# Display the image in a window

cv2.imshow('Loaded Image', image)


# Wait for a key press and close the window

cv2.waitKey(0)

cv2.destroyAllWindows()

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

It takes a short while to generate the image as shown.

You would have noticed the difference between displaying using PIL and OpenCV. The method imshow() is a part of the matplotlib library but has also become a part of the OpenCV.  The imshow() creates a window managed by OpenCV in the context of the OpenCV applications. However the PIL program uses the default viewer settings that can change depending on the settings and the OS.

The images displayed by the two methods can be different as well.

Jump  to installing OpenCV to change color of images:

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.

Jump to change color with Python: