使用Python读取CR2(Raw Canon Image)头文件

2024-03-28 11:03:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试提取从CR2(原始图片的佳能格式)中拍摄图片的日期/时间。

我知道CR2 specification,我知道我可以使用Python struct模块从二进制缓冲区提取片段。

简言之,规范指出在标签0x0132 / 306中,我可以找到长度为20的字符串——日期和时间。

我试图通过以下方式获取标签:

struct.unpack_from(20*'s', buffer, 0x0132)

但我知道

('\x00', '\x00', "'", '\x88, ...[and more crap])

有什么想法吗?

编辑

非常感谢您的努力!答案是惊人的,我学到了很多关于处理二进制数据的知识。


Tags: 模块字符串规范格式方式时间二进制图片
3条回答

0x0132不是偏移量,而是日期的标记号。CR2或TIFF分别是基于目录的格式。你必须根据你正在寻找的(已知的)标签来查找条目。

编辑: 好的,首先,您必须读取文件数据是使用小端格式还是大端格式保存的。前八个字节指定头,头的前两个字节指定尾数。Python的struct模块允许您通过在格式字符串前面加上“<;”或“>;”来处理小数据和大数据。因此,假设data是包含CR2图像的缓冲区,您可以通过

header = data[:8]
endian_flag = "<" if header[:2] == "II" else ">"

格式规范指出,第一个图像文件目录以相对于文件开头的偏移量开始,偏移量在头的最后4个字节中指定。因此,要获得第一个IFD的偏移量,可以使用类似于此的行:

ifd_offset = struct.unpack("{0}I".format(endian_flag), header[4:])[0]

你现在可以继续读第一本IFD了。您将在目录中指定的文件偏移量处找到条目数,该偏移量为两个字节宽。因此,您可以使用以下方法读取第一个IFD中的条目数:

number_of_entries = struct.unpack("{0}H".format(endian_flag), data[ifd_offset:ifd_offset+2])[0]

字段项的长度为12字节,因此可以计算IFD的长度。在条目数*12字节后,还有一个4字节长的偏移量,告诉您在哪里查找下一个目录。这基本上就是你处理TIFF和CR2图像的方式。

这里的“魔力”是要注意,对于12字节字段条目中的每一个,前两个字节将是标记ID,这就是您寻找标记0x0132的地方。因此,如果您知道第一个IFD从文件中的IFD_偏移开始,您可以通过以下方式扫描第一个目录:

current_position = ifd_offset + 2
for field_offset in xrange(current_position, number_of_entries*12, 12):
    field_tag = struct.unpack("{0}H".format(endian_flag), data[field_offset:field_offset+2])[0]
    field_type = struct.unpack("{0}H".format(endian_flag), data[field_offset+2:field_offset+4])[0]
    value_count = struct.unpack("{0}I".format(endian_flag), data[field_offset+4:field_offset+8])[0]
    value_offset = struct.unpack("{0}I".format(endian_flag), data[field_offset+8:field_offset+12])[0]

    if field_tag == 0x0132:
        # You are now reading a field entry containing the date and time
        assert field_type == 2 # Type 2 is ASCII
        assert value_count == 20 # You would expect a string length of 20 here
        date_time = struct.unpack("20s", data[value_offset:value_offset+20])
        print date_time

很明显,您需要将该解包重构为一个公共函数,并可能将整个格式包装成一个好的类,但这超出了本例的范围。您还可以通过将多个格式字符串组合成一个字符串来缩短解包过程,生成一个更大的元组,其中包含可以解包到不同变量中的所有字段,为了清楚起见,我省略了这些字段。

你考虑过你所说的IFD块之前应该(根据规范)的头吗?

我查看了规范,它说第一个IFD块跟在16字节的头后面。因此,如果我们读取字节16和17(偏移量0x10十六进制),我们应该得到第一个IFD块中的条目数。然后我们只需要搜索每个条目,直到找到一个匹配的标记id(在我读到它时),它给了我们日期/时间字符串的字节偏移量。

这对我有效:

from struct import *

def FindDateTimeOffsetFromCR2( buffer, ifd_offset ):
    # Read the number of entries in IFD #0
    (num_of_entries,) = unpack_from('H', buffer, ifd_offset)
    print "ifd #0 contains %d entries"%num_of_entries

    # Work out where the date time is stored
    datetime_offset = -1
    for entry_num in range(0,num_of_entries-1):
        (tag_id, tag_type, num_of_value, value) = unpack_from('HHLL', buffer, ifd_offset+2+entry_num*12)
        if tag_id == 0x0132:
            print "found datetime at offset %d"%value
            datetime_offset = value
    return datetime_offset

if __name__ == '__main__':
    with open("IMG_6113.CR2", "rb") as f:
        buffer = f.read(1024) # read the first 1kb of the file should be enough to find the date / time
        datetime_offset = FindDateTimeOffsetFromCR2(buffer, 0x10)
        print unpack_from(20*'s', buffer, datetime_offset)

我的示例文件的输出是:

ifd #0 contains 14 entries
found datetime at offset 250
('2', '0', '1', '0', ':', '0', '8', ':', '0', '1', ' ', '2', '3', ':', '4', '5', ':', '4', '6', '\x00')

[编辑]-一个经过修订/更彻底的示例

from struct import *

recognised_tags = { 
    0x0100 : 'imageWidth',
    0x0101 : 'imageLength',
    0x0102 : 'bitsPerSample',
    0x0103 : 'compression',
    0x010f : 'make',    
    0x0110 : 'model',
    0x0111 : 'stripOffset',
    0x0112 : 'orientation', 
    0x0117 : 'stripByteCounts',
    0x011a : 'xResolution',
    0x011b : 'yResolution',
    0x0128 : 'resolutionUnit',
    0x0132 : 'dateTime',
    0x8769 : 'EXIF',
    0x8825 : 'GPS data'};

def GetHeaderFromCR2( buffer ):
    # Unpack the header into a tuple
    header = unpack_from('HHLHBBL', buffer)

    print "\nbyte_order = 0x%04X"%header[0]
    print "tiff_magic_word = %d"%header[1]
    print "tiff_offset = 0x%08X"%header[2]
    print "cr2_magic_word = %d"%header[3]
    print "cr2_major_version = %d"%header[4]
    print "cr2_minor_version = %d"%header[5]
    print "raw_ifd_offset = 0x%08X\n"%header[6]

    return header

def FindDateTimeOffsetFromCR2( buffer, ifd_offset, endian_flag ):
    # Read the number of entries in IFD #0
    (num_of_entries,) = unpack_from(endian_flag+'H', buffer, ifd_offset)
    print "Image File Directory #0 contains %d entries\n"%num_of_entries

    # Work out where the date time is stored
    datetime_offset = -1

    # Go through all the entries looking for the datetime field
    print " id  | type |  number  |  value   "
    for entry_num in range(0,num_of_entries):

        # Grab this IFD entry
        (tag_id, tag_type, num_of_value, value) = unpack_from(endian_flag+'HHLL', buffer, ifd_offset+2+entry_num*12)

        # Print out the entry for information
        print "%04X | %04X | %08X | %08X "%(tag_id, tag_type, num_of_value, value),
        if tag_id in recognised_tags:
            print recognised_tags[tag_id]

        # If this is the datetime one we're looking for, make a note of the offset
        if tag_id == 0x0132:
            assert tag_type == 2
            assert num_of_value == 20
            datetime_offset = value

    return datetime_offset

if __name__ == '__main__':
    with open("IMG_6113.CR2", "rb") as f:
        # read the first 1kb of the file should be enough to find the date/time
        buffer = f.read(1024) 

        # Grab the various parts of the header
        (byte_order, tiff_magic_word, tiff_offset, cr2_magic_word, cr2_major_version, cr2_minor_version, raw_ifd_offset) = GetHeaderFromCR2(buffer)

        # Set the endian flag
        endian_flag = '@'
        if byte_order == 0x4D4D:
            # motorola format
            endian_flag = '>'
        elif byte_order == 0x4949:
            # intel format
            endian_flag = '<'

        # Search for the datetime entry offset
        datetime_offset = FindDateTimeOffsetFromCR2(buffer, 0x10, endian_flag)

        datetime_string = unpack_from(20*'s', buffer, datetime_offset)
        print "\nDatetime: "+"".join(datetime_string)+"\n"

我发现来自https://github.com/ianare/exif-py的EXIF.py从.CR2文件读取EXIF数据。似乎是因为.CR2文件基于.TIFF文件EXIF.py是兼容的。

    import EXIF
    import time

    # Change the filename to be suitable for you
    f = open('../DCIM/100CANON/IMG_3432.CR2', 'rb')
    data = EXIF.process_file(f)
    f.close()
    date_str = data['EXIF DateTimeOriginal'].values

    # We have the raw data
    print date_str

    # We can now convert it
    date = time.strptime(date_str, '%Y:%m:%d %H:%M:%S')
    print date

这个指纹:

    2011:04:30 11:08:44
    (2011, 4, 30, 11, 8, 44, 5, 120, -1)

相关问题 更多 >