Python: Read Image Grayscale Pixel Values

In Python, you can use the PIL library (Pillow) to read an image and obtain the grayscale values of each pixel. Here is an example code:

from PIL import Image

# 打开图片文件
image = Image.open('example.jpg')

# 获取图片的宽度和高度
width, height = image.size

# 遍历图片的每个像素点,获取灰度值
for y in range(height):
    for x in range(width):
        pixel = image.getpixel((x, y))
        # 如果是RGB图片,可以将三个通道的值取平均得到灰度值
        grey = sum(pixel) / len(pixel)
        print(f'灰度值为 {grey} 的像素点坐标为 ({x}, {y})')

In this code snippet, firstly open an image file named example.jpg, and get its width and height. Then iterate through each pixel using a nested loop, use the getpixel method to obtain the RGB value of each pixel, and calculate the grayscale value. Finally, output the grayscale value and coordinates of each pixel. You can further process or analyze the grayscale values as needed.

bannerAds