本篇文章旨在通过详细的逐行注释,介绍如何分别使用 C/C++/Python 读取图片并获取指定像素位置的RGB值。
Python实现
from PIL import Image
import matplotlib.pyplot as plt
filename = "demo.jpg" # 图片文件路径
# 打开图像
image = Image.open(filename)
# 获取图像的宽度和高度
width, height = image.size
x = 100 # 像素位置的x坐标
y = 100 # 像素位置的y坐标
# 判断像素位置是否有效
if x >= 0 and x < width and y >= 0 and y < height:
# 获取指定像素位置的RGB值
r, g, b = image.getpixel((x, y))
print(f"Pixel value at ({x}, {y}): R={r}, G={g}, B={b}")
else:
print("Invalid pixel position.")
# 显示图像
plt.imshow(image)
plt.axis('off')
plt.show()
# 关闭图像
image.close()
C实现
#include <stdio.h>
#inclu