How to read pixel values of an image in Python?
To read pixel values of an image, you can use either the Python Imaging Library (PIL) or the OpenCV library. Below is an example code showing how to read image pixel values using these two libraries.
- Read the pixel values of an image using the PIL library.
from PIL import Image
# 打开图像
image = Image.open('image.jpg')
# 获得图像的宽度和高度
width, height = image.size
# 获取像素值
pixels = image.load()
# 遍历每个像素
for i in range(width):
for j in range(height):
r, g, b = pixels[i, j] # 获取像素RGB值
print(f'Pixel at ({i}, {j}): R={r}, G={g}, B={b}')
- Read pixel values of an image using the OpenCV library.
import cv2
# 读取图像
image = cv2.imread('image.jpg')
# 获取图像的宽度和高度
height, width, _ = image.shape
# 遍历每个像素
for i in range(height):
for j in range(width):
b, g, r = image[i, j] # 获取像素BGR值
print(f'Pixel at ({i}, {j}): B={b}, G={g}, R={r}')
The code above can read the RGB (or BGR) values of each pixel in an image and output them to the console. It is important to note that when using the OpenCV library, the pixel values are read in BGR order.