如何在Matplotlib中获取指定坐标像素颜色并转为NumPy数组?
解决方案
1. 将PIL图像转换为NumPy数组
直接用numpy.array()就能把PIL的Image对象转换成NumPy数组,数组维度对应(图像高度, 图像宽度, 通道数)——RGB图是3通道,灰度图是单通道,所有像素值会自动存入数组中。
2. 访问指定位置的像素
注意数组索引和图像坐标的对应关系:图像的(x, y)坐标对应数组的[y, x]索引(数组第一个维度是垂直方向的像素行,第二个是水平方向的像素列)。
3. 判断像素是黑色还是白色
对于RGB像素,可通过通道值或灰度均值判断:
- 黑色像素的RGB值接近
(0, 0, 0) - 白色像素的RGB值接近
(255, 255, 255)
完整示例代码
import numpy from PIL import Image import matplotlib.pyplot as plt # 打开并缩小图片 img = Image.open(r'C:\Users\User\OneDrive\Desktop\database\db1.jpg') small_img = img.resize((16, 16), Image.BILINEAR) # 将PIL图像转为NumPy数组,所有像素值已存入其中 img_array = numpy.array(small_img) # 访问x=6、y=6位置的像素(数组索引为[y, x]) target_pixel = img_array[6, 6] print(f"目标像素RGB值: {target_pixel}") # 判断黑白:计算灰度均值,阈值可根据图片实际情况调整 gray_value = numpy.mean(target_pixel) if gray_value < 50: print("该像素为黑色") elif gray_value > 200: print("该像素为白色") else: print("该像素为灰色或其他颜色") # 验证数组信息 print(f"像素数组形状: {img_array.shape}") # 可选:对比显示原图和数组还原的图像,验证转换正确性 plt.subplot(121) plt.imshow(small_img) plt.title("PIL Image") plt.subplot(122) plt.imshow(img_array) plt.title("NumPy Array Image") plt.show()
补充说明
- 如果图片是灰度图,转成数组后会是
(16,16)的单通道数组,访问像素直接用img_array[6,6]即可,判断逻辑更简单(值越小越黑,越大越白)。 - 示例中的阈值(50、200)可根据图片的明暗程度自行调整,确保判断准确。
内容的提问来源于stack exchange,提问作者abcd
相关产品推荐
相关产品推荐

