gpt-4.1-mini-2025-04-14· OpenAI
LMArena Human Preference 140K
python 读取8bit 灰度 png 用什么接口,要求不要转换格式
- User
python 读取8bit 灰度 png 用什么接口,要求不要转换格式
- Assistant
在Python中读取8bit灰度PNG图像且不转换格式,推荐使用Pillow库(PIL的升级版),它可以直接读取图像并保持原始的灰度格式(mode为
'L'),不会自动转换成RGB等格式。示例代码如下:
from PIL import Image # 读取8bit灰度PNG图像 img = Image.open('your_image.png') # 确认图像模式是'L',即8bit灰度 print(img.mode) # 输出应为 'L' # 如果需要获取像素数据为numpy数组 import numpy as np img_array = np.array(img) print(img_array.dtype) # 通常是 uint8 print(img_array.shape) # (height, width)说明:
Image.open()不会自动转换图像格式,原始的8bit灰度PNG会保持为'L'模式。- 如果图像本身是8bit灰度,
img.mode就是'L'。 - 你可以直接用
np.array()转换成numpy数组,数据类型是uint8,且不做任何格式转换。
如果你用OpenCV读取,默认会转换成BGR格式(3通道),不符合“不要转换格式”的要求。
总结:
用Pillow的Image.open()读取8bit灰度PNG,保持原始格式不转换。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.