To read a BMP file in Python, you can use the `Pillow` library. Pillow is a powerful image processing library that provides capabilities for opening, manipulating, and saving many different image file formats, including BMP.
First, you need to install the Pillow library. You can do this using pip by running the following command in your command prompt or terminal:
pip install Pillow
Once you have Pillow installed, you can use the following code to read a BMP file in Python:
from PIL import Image
# Open the BMP file
image = Image.open("example.bmp")
# Get the dimensions of the image
width, height = image.size
# Print the dimensions
print("Image dimensions: {} x {}".format(width, height))
# Get the pixel values of the image
pixels = image.load()
# Access a specific pixel (x, y)
x = 0
y = 0
pixel_value = pixels[x, y]
print("Pixel value at (0, 0):", pixel_value)
In the code above, we first import the `Image` module from the Pillow library. We then use the `Image.open()` function to open the BMP file. Replace “example.bmp” with the path to your own BMP file.
We can use the `size` attribute of the opened image to get its dimensions. The width and height are assigned to the respective variables.
The `load()` function returns a pixel access object that we can use to get the pixel values. We assign it to the `pixels` variable. To access a specific pixel, we can use indexing (x, y).
This is just a simple example to demonstrate how to read a BMP file. You can further process the image based on your requirements using the available functions and methods in the Pillow library.