数字图像处理-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