使用python,但是不使用cv库以及PIL,设计并编写一个应用程序,达到对任意一个24位bmp格式的图片进行可指定大小的缩小放大的目的(类似transform),给出详细代码及使用方法...

使用 python 编写一个应用程序来缩放 24 位 bmp 格式的图片,不使用 cv 库和 PIL 库,需要用到 struct 库来读取二进制文件。

首先需要读取 bmp 文件的头部信息,通过读取文件前 54 个字节来获取图片的宽度和高度等信息。接下来,读取整个图片,并将其转换为像素矩阵。然后进行放大或缩小操作,最后将像素矩阵转换为新的 bmp 文件。

下面是一个可以缩放 24 位 bmp 格式图片的代码示例:

```python import struct import numpy as np

def read_bmp(file_name): # 读取 bmp 文件头部信息 with open(file_name, "rb") as f: data = f.read(54) head = struct.unpack("<ccIIIIIIHH", data) width = head[-4] height = head[-3] bits = head[-1] if bits != 24: raise ValueError("Only support 24 bits bmp image")

# 读取 bmp 文件像素数据
withopen(file_name, "rb") as f:
    f.seek(54)
    data = f.read()
pixels = np.frombuffer(data, np.uint8)
pixels = pixels.reshape((height, width, 3))

return pixels

def write_bmp(pixels, file_name): # 获取图片宽度和高度 height, width, _ = pixels.shape

# 计算填充字节数
padding = (4 - (width * 3) % 4) % 4
new_width = width + padding

# 创建 bmp 文件头部信息
head = [
    ord("B"), ord("M"),  # 文件类型
    new_width * height * 3 + 54,  # 文件大小
    0, 0,  # 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值