How to read image files using Python?
You can read image files using the PIL library in Python (part of the Pillow library).
Here is an example code of reading image files using the PIL library:
from PIL import Image
# 打开图像文件
image = Image.open("image.png")
# 显示图像文件
image.show()
# 获取图像的宽度和高度
width, height = image.size
print("图像宽度:", width)
print("图像高度:", height)
# 获取图像的像素值
pixels = list(image.getdata())
print("图像像素值:", pixels)
In the code above, you start by opening the image file using the Image.open() function. You can then use the show() method to display the image file.
Then, you can use the size attribute to obtain the width and height of the image.
Finally, you can use the getdata() method to retrieve the pixel values of the image and store them in a list.
Before running the above code, make sure the PIL library (part of the Pillow library) is installed. You can do this by using the command pip install pillow.