在按照您的文章提供的代码测试的时候遇到下图的问题
import numpy as np
import cv2
from struct import unpack
#读取BMP文件的位图信息头40个字节
class ReadBMPFile:
def __init__(self,filePath):
file = open(filePath, "rb") #rb指读入文件python不对文件中的字符预处理,而用r时,会将换行符\r\n处理成为\n,方便处理
#读取BMP文件的文件头 14字节
self.bfType = unpack("<h",file.read(2))[0] #0x4d42 对应BM表示 unpack()返回的是一个元组[0]表示元组中第一个元素
self.bfSize = unpack("<i",file.read(4))[0] #位图文件大小
self.bfReserved1 = unpack("<h",file.read(2))[0] #保留字段 必须设为0
self.bfReserved2 = unpack("<h",file.read(2))[0] #保留字段 必须设为0
self.bfOffBits = unpack("<i",file.read(4))[0] #偏移量 从文件头到位图数据需要偏移多少字节(位图信息头、调色板长度等不是固定的,这时就需要这个参数了)
self.biSize = unpack("<i",file.read(4))[0] # 所需要的字节数
self.biWidth = unpack("<i",file.read(4))[0] # 图像的宽度 单位 像素
self.biHeight = unpack("<i",file.read(4))[0] # 图像的高度 单位 像素
self.biPlanes = unpack("<h",file.read(2))[0] # 说明颜色平面数 总设为1
self.biBitCount = unpack("<h",file.read(2))[0] # 说明比特数,一个像素所占位数(24位)
self.biCompression = unpack("<i", file.read(4))[0] # 图像压缩的数据类型,0为不压缩
self.biSizeImage = unpack("<i", file.read(4))[0] # 图像大小
self.biXPelsPerMeter = unpack("<i", file.read(4))[0]# 水平分辨率
self.biYPelsPerMeter = unpack("<i", file.read(4))[0]# 垂直分辨率
self.biClrUsed = unpack("<i", file.read(4))[0] # 实际使用的彩色表中的颜色索引数
self.biClrImportant = unpack("<i", file.read(4))[0] # 对图像显示有重要影响的颜色索引的数目
self.bmp_data = []
if self.biBitCount!=24 :
print("输入的图像比特值为 :"+ str(self.biBitCount) + "\t与程序不匹配")
for height in range(self.biHeight) :
bmp_data_row = []
# 四字节填充位检测
count = 0
for width in range(self.biWidth) :
bmp_data_row.append([unpack("<B",file.read(1))[0],unpack("<B",file.read(1))[0],unpack("<B",file.read(1))[0]])
count+=3
#bmp 四字节对齐原则
while count % 4!= 0 :
count+=1
file.read(1)
self.bmp_data.append(bmp_data_row)
self.bmp_data.reverse()
file.close()
self.R = []
self.G = []
self.B = []
for row in range(self.biHeight) :
R_row = []
G_row = []
B_row = []
for col in range(self.biWidth):
R_row.append(self.bmp_data[row][col][0])
G_row.append(self.bmp_data[row][col][1])
B_row.append(self.bmp_data[row][col][2])
self.R.append(R_row)
self.G.append(G_row)
self.B.append(B_row)
bmpFile = ReadBMPFile('castle.bmp')
r = bmpFile.R
g = bmpFile.G
b = bmpFile.B
R = np.array(r, dtype = np.uint8)
G = np.array(g, dtype = np.uint8)
B = np.array(b, dtype = np.uint8)
# a = np.array(bmpFile.bmp_data,dtype = np.uint8)
img = cv2.merge([R,G,B])
print(type(img))
cv2.imshow("review",img)
k = cv2.waitKey(0) # waitkey代表读取键盘的输入,括号里的数字代表等待多长时间,单位ms。 0代表一直等待
if k ==27: # 键盘上Esc键的键值
cv2.destroyAllWindows()
如上
暂时没有思路解决该问题,想请教
使图片正常显示