python图像转换——BMP位图文件

编写2个python 程序
1.编写 Python 程序,读取一个 24 位真彩色 BMP 文件,然后转化为灰色图像,最后存储为 8 位伪彩色 BMP 文件;
2.编写 Python 程序,读取一个 8 位伪彩色 BMP 文件,转化为 24 位真彩色 BMP 文件,最后存储。
注意:以上两个 Python 程序设计任务,要求使用面向对象的式来写(使用 class),不能使用 Python 图像模块/包/库,如 opencv、PIL 等。在定义 class 里的成员时,可使用 int.to_bytes、int.from_bytes等。

以下内容部分参考ChatGPT模型:


  1. 读取一个 24 位真彩色 BMP 文件,然后转化为灰色图像,最后存储为 8 位伪彩色 BMP 文件的思路:
  • 读取 BMP 文件的头部信息,获取图像的宽度、高度、颜色位数等信息。
  • 读取 BMP 文件中的像素数据,将其转化为灰度图像。
  • 将灰度图像转化为伪彩色图像。可以通过设置颜色表来实现,将灰度值映射到不同的颜色上。
  • 写入 BMP 文件头部和像素数据,生成 8 位伪彩色 BMP 文件。

以下是读取一个 24 位真彩色 BMP 文件,然后转化为灰色图像,最后存储为 8 位伪彩色 BMP 文件的示例代码:

import struct

# 读取 BMP 文件头部信息
with open('input.bmp', 'rb') as f:
    # BMP 文件头部信息占据 54 个字节
    bmp_header = f.read(54)
    # 解析 BMP 文件头部信息,获取图像的宽度、高度、颜色位数等信息
    width, height, color_depth = struct.unpack('<iii', bmp_header[18:30])

# 读取 BMP 文件中的像素数据
with open('input.bmp', 'rb') as f:
    # 跳过 BMP 文件头部信息
    f.seek(54)
    # 每行像素数据的字节数需要进行补齐
    row_size = width * color_depth // 8
    if row_size % 4 != 0:
        row_size += 4 - row_size % 4
    # 读取像素数据
    pixel_data = f.read(row_size * height)

# 将像素数据转化为灰度图像
gray_data = []
for i in range(0, len(pixel_data), 3):
    r, g, b = struct.unpack('<BBB', pixel_data[i:i+3])
    gray_value = int(0.299 * r + 0.587 * g + 0.114 * b)
    gray_data.append(gray_value)

# 将灰度图像转化为伪彩色图像
color_table = [(i, i, i) for i in range(256)]
color_data = []
for gray_value in gray_data:
    color_value = color_table[gray_value]
    color_data.extend(color_value)

# 写入 BMP 文件头部和像素数据,生成 8 位伪彩色 BMP 文件
with open('output.bmp', 'wb') as f:
    # 写入 BMP 文件头部信息
    f.write(bmp_header)
    # 写入颜色表
    for color_value in color_table:
        f.write(struct.pack('<BBBx', *color_value))
    # 写入像素数据
    for i in range(0, len(color_data), row_size):
        f.write(bytes(color_data[i:i+row_size]))
  1. 读取一个 8 位 BMP 位图文件的思路:
  • 读取 BMP 文件头部信息,获取图像的宽度、高度、颜色位数等信息。
  • 读取 BMP 文件中的颜色表和像素数据。

以下是读取一个 8 位 BMP 位图文件的示例代码:

import struct

# 读取 BMP 文件头部信息
with open('input.bmp', 'rb') as f:
    # BMP 文件头部信息占据 54 个字节
    bmp_header = f.read(54)
    # 解析 BMP 文件头部信息,获取图像的宽度、高度、颜色位数等信息
    width, height, color_depth = struct.unpack('<iii', bmp_header[18:30])

# 读取颜色表
with open('input.bmp', 'rb') as f:
    # 跳过 BMP 文件头部信息和像素数据
    f.seek(54)
    row_size = width * color_depth // 8
    if row_size % 4 != 0:
        row_size += 4 - row_size % 4
    color_table_size = 4 * 2 ** color_depth
    # 读取颜色表数据
    color_table = []
    for i in range(color_table_size):
        color_value = struct.unpack('<BBBx', f.read(4))
        color_table.append(color_value)

# 读取像素数据
with open('input.bmp', 'rb') as f:
    # 跳过 BMP 文件头部信息和颜色表
    f.seek(54 + color_table_size)
    pixel_data = f.read(row_size * height)

如果我的建议对您有帮助、请点击采纳、祝您生活愉快

https://blog.csdn.net/m0_46639841/article/details/123963755