数字图像处理-Python读取BMP文件

更新时间:2023-07-19 05:09:54 阅读: 评论:0

数字图像处理-Python读取BMP⽂件import numpy as np
import struct
熨平
from PIL import Image
class ImageFile():
def getBMP(lf, filepath):
# 先将位图打开
f = open(filepath,'rb')            # 打开对应的⽂件
# 下⾯部分⽤来读取BMP位图的基础信息
f_type = ad(2))            # 这个就可以⽤来读取⽂件类型需要读取2个字节
file_size_byte = f.read(4)          # 这个可以⽤来读取⽂件的⼤⼩需要读取4个字节
f.ll()+4)                  # 跳过中间⽆⽤的四个字节
file_oft_byte = f.read(4)        # 读取位图数据的偏移量
绿色标语
f.ll()+4)                  # 跳过⽆⽤的两个字节
file_wide_byte = f.read(4)          # 读取宽度字节
file_height_byte = f.read(4)        # 读取⾼度字节
f.ll()+2)                  # 跳过中间⽆⽤的两个字节
file_bitcount_byte = f.read(4)      # 得到每个像素占位⼤⼩
#下⾯就是将读取的字节转换成指定的类型
f_size, = struct.unpack('i', file_size_byte)
f_oft, = struct.unpack('i', file_oft_byte)
f_wide, = struct.unpack('i', file_wide_byte)
f_height, = struct.unpack('i', file_height_byte)
f_bitcount, = struct.unpack('i', file_bitcount_byte)
print("类型:", f_type, "⼤⼩:", f_size, "位图数据偏移量:", f_oft, "宽度:", f_wide, "⾼度:", f_height, "位图:", f_bitcount)
# 然后来读取颜⾊表
color_table = np.empty(shape=[256, 4], dtype=int)
f.ek(54) #跳过⽂件信息头和位图信息头
for i in range(0, 256):
b=struct.unpack('B', f.read(1))[0]
张国荣喜欢谁g = struct.unpack('B', f.read(1))[0]
r = struct.unpack('B', f.read(1))[0]
alpha = struct.unpack('B', f.read(1))[0]
color_table[i][0] = r
color_table[i][1] = g
color_table[i][2] = b
color_table[i][3] = 255
# 下⾯部分⽤来读取BMP位图数据区域,将数据存⼊numpy数组
# ⾸先对⽂件指针进⾏偏移
伶俐的反义词f.ek(f_oft)
霸王鲨>金鲤鱼# 因为图像是8位伪彩⾊图像,所以⼀个像素点占⼀个字节,即8位伤感说说
img = np.empty(shape=[f_height, f_wide, 4], dtype=int)
cout = 0
"""
然后就是来读取位图数据了,读取位图数据的时候,我们⼀定要注意,
数据的排列⽅式是从左到右,从下到上!
还有⼀个while循环,是⽤来判断⾏像素是否为4的倍数,
如果不是我们还要将填充的⽤字节给读取扔掉
"""
for y in range(0, f_height):
for x in range(0,f_wide):
中国男装十大名牌cout = cout + 1
index = struct.unpack('B', f.read(1))[0]
img[f_height - y - 1, x] = color_table[index]
while cout % 4 != 0:
cout = cout+1
f.clo()
return img
def ndarry2image(lf, ndarry):
# ndarray 转图⽚
ndarry = ndarry.astype("uint8")
# ndarry = cv2.cvtColor(ndarry, cv2.COLOR_BGR2RGB)
ndarry = Image.fromarray(ndarry)
ndarry = qpixmap()
return ndarry

本文发布于:2023-07-19 05:09:54,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1087322.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:读取   数据   字节   位图   像素   是否   信息   需要
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图