You need to enable JavaScript to run this app. 如何用Python将BMP图像自动转换为0/1构成的二维列表?
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 22:15:02