如何在python中读取bmp文件头?

Rob*_*oob 2 python image image-processing bmp file-header

我需要用python读取bmp文件的标题。我这样试过,但它显然只返回一堆不可理解的字节:

f = open(input_filename,"rb")
data = bytearray(f.read())
f.close()
print(data[:14])
Run Code Online (Sandbox Code Playgroud)

我的想法是找到一个模块或一些快速的东西,以便在打开它时记录图像信息。我知道这个功能的MATLAB中,做正是我想要的:imfinfo()。但我在 python 中找不到对应物。

需要明确的是,这就是我使用 matlab 得到的结果:

       FileModDate: '20-Oct-2017 09:42:24'
          FileSize: 1311798
            Format: 'bmp'
     FormatVersion: 'Version 3 (Microsoft Windows 3.x)'
             Width: 1280
            Height: 1024
          BitDepth: 8
         ColorType: 'indexed'
   FormatSignature: 'BM'
NumColormapEntries: 256
          Colormap: [256x3 double]
           RedMask: []
         GreenMask: []
          BlueMask: []
   ImageDataOffset: 1078
  BitmapHeaderSize: 40
         NumPlanes: 1
   CompressionType: 'none'
        BitmapSize: 1310720
    HorzResolution: 0
    VertResolution: 0
     NumColorsUsed: 256
NumImportantColors: 0
Run Code Online (Sandbox Code Playgroud)

ekh*_*oro 10

您可以使用imghdr 模块(在 python stdlib 中):

>>> import imghdr
>>> print(imghdr.what(input_filename))
bmp
Run Code Online (Sandbox Code Playgroud)

这将从标题中提取图像类型,仅此而已。Python 标准库中没有其他东西可以获取更详细的信息——你需要一个第三方库来完成这样一个专门的任务。要了解其复杂性,请查看BMP 文件格式。根据那里概述的规范,编写一些纯 Python 代码来提取一些信息可能是可行的,但要使其适合任意位图图像文件并不容易。

更新

下面是一个使用struct 模块从位图标头中提取一些基本信息的简单脚本。有关如何解释各种值的信息,请参阅上面提到的 BMP 文件格式,并注意此脚本仅适用于最常见的格式版本(即 Windows BITMAPINFOHEADER):

import struct

bmp = open(fn, 'rb')
print('Type:', bmp.read(2).decode())
print('Size: %s' % struct.unpack('I', bmp.read(4)))
print('Reserved 1: %s' % struct.unpack('H', bmp.read(2)))
print('Reserved 2: %s' % struct.unpack('H', bmp.read(2)))
print('Offset: %s' % struct.unpack('I', bmp.read(4)))

print('DIB Header Size: %s' % struct.unpack('I', bmp.read(4)))
print('Width: %s' % struct.unpack('I', bmp.read(4)))
print('Height: %s' % struct.unpack('I', bmp.read(4)))
print('Colour Planes: %s' % struct.unpack('H', bmp.read(2)))
print('Bits per Pixel: %s' % struct.unpack('H', bmp.read(2)))
print('Compression Method: %s' % struct.unpack('I', bmp.read(4)))
print('Raw Image Size: %s' % struct.unpack('I', bmp.read(4)))
print('Horizontal Resolution: %s' % struct.unpack('I', bmp.read(4)))
print('Vertical Resolution: %s' % struct.unpack('I', bmp.read(4)))
print('Number of Colours: %s' % struct.unpack('I', bmp.read(4)))
print('Important Colours: %s' % struct.unpack('I', bmp.read(4)))
Run Code Online (Sandbox Code Playgroud)

输出:

>>> import imghdr
>>> print(imghdr.what(input_filename))
bmp
Run Code Online (Sandbox Code Playgroud)