如何用Python将BMP图像自动转换为0/1构成的二维列表?
Python实现BMP图像转0/1二维嵌套列表方案
前置依赖
需要安装Pillow图像处理库,安装命令:pip install pillow
实现代码
from PIL import Image def bmp_to_binary_list(bmp_path, threshold=128): # 读取BMP图像并转为灰度模式,灰度值范围为0-255 img = Image.open(bmp_path).convert('L') width, height = img.size binary_nested_list = [] for y in range(height): current_row = [] for x in range(width): pixel_value = img.getpixel((x, y)) # 灰度值高于阈值判定为白色,记为1;低于阈值判定为黑色,记为0 current_row.append(1 if pixel_value > threshold else 0) binary_nested_list.append(current_row) return binary_nested_list # 调用示例 if __name__ == '__main__': # 替换为你的BMP文件路径 res = bmp_to_binary_list("./your_image.bmp") # 输出全量二维列表可直接打印res print(res)
自定义规则调整
- 若需要0对应白色、1对应黑色,将代码中
1 if pixel_value > threshold else 0改为0 if pixel_value > threshold else 1即可 - 若你使用的本身就是二值BMP文件,可将
convert('L')改为convert('1'),无需设置阈值直接读取像素值判断 - 若需要输出固定尺寸的列表,可在读取图像后添加
img = img.resize((目标宽度, 目标高度))调整图像尺寸后再生成列表
内容的提问来源于stack exchange,提问作者Pavol Bujna
相关产品推荐
相关产品推荐

