Pythonで画像のピクセル値を読み取る方法は何ですか?
画像のピクセル値を読み取るためには、Pythonの画像処理ライブラリであるPIL(Python Imaging Library)またはOpenCVライブラリを使用することができます。以下に、これらのライブラリを使って画像のピクセル値を読み取るためのサンプルコードを示します。
- PILライブラリを使用して画像のピクセル値を読み取る:
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}')
- OpenCVライブラリを使用して画像のピクセル値を読み取る:
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}')
Above code can read RGB (or BGR) values of each pixel of an image and output them to the console. It should be noted that when using the OpenCV library, the pixel values read are in BGR order.
このコードは、画像の各ピクセルのRGB(またはBGR)値を読み取り、それらをコンソールに出力します。OpenCVライブラリを使用する際には、読み取られるピクセル値がBGRの順序であることに注意する必要があります。