检索 Python 中 .dpx 文件的分辨率

Retrieving the resolution of .dpx files in Python

我目前正在编写一个程序,用于搜索输入的文件夹并标记文件丢失或空文件等错误。我需要检查的错误之一是所有 .dpx 图像是否具有相同的分辨率。但是,我似乎无法找到一种方法来检查这一点。 PIL 无法打开文件,我找不到检查元数据的方法。有什么想法吗?

这是我目前用于执行此操作的代码:

im = Image.open(fullName)

if im.size != checkResolution:
    numErrors += 1
    reportMessages.append(ReportEntry(file, "WARNING",
                                      "Unusual Resolution"))

全名是文件的路径。 checkResolution 是作为元组的正确分辨率。 reportMessages 只是收集错误字符串,稍后在报告中打印。 运行当前节目returns:

Traceback (most recent call last):

   File "Program1V4", line 169, in <module>
     main(sys.argv[1:])

   File "Program1V4", line 108, in main
    im = Image.open(fullName)

  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1983, in open
    raise IOError("cannot identify image file")

 IOError: cannot identify image file

很遗憾,Pillow/PIL 还不理解 SMPTE 数字图片交换格式。

然而,ImageMagick supports it and ImageMagick can be controlled by Python or you simply call ImageMagick as an external command.

编译 C library 并从 Python 调用它需要更多的工作,但也有可能。很想知道 ImageMagick 是否在幕后使用这个库或者有自己的标准实现。

这可能不是最 pythonic 或最快的方法(不使用结构或 ctypes - 或者在 c 中做!),但我会直接从文件 header 中提取字段(不要忘记检查错误...):

# Open the DPX file 
fi = open(frame, 'r+b') 

# Retrieve the magic number from the file header - this idicates the endianness 
# of the numerical file data
magic_number = struct.unpack('I', currFile.read(4))[0] 

# Set the endianness for reading the values in
if not magic_number == 1481655379: # 'SDPX' in ASCII
    endianness = "<"
else:
    endianness = ">"

# Seek to x/y offset in header (1424 bytes in is the x pixel 
# count of the first image element, 1428 is the y count)
currFile.seek(1424, 0)

# Retrieve values (4 bytes each) from file header offset 
# according to file endianness
x_resolution = struct.unpack(endianness+"I", currFile.read(4))[0]
y_resolution = struct.unpack(endianness+"I", currFile.read(4))[0]

fi.close()

# Put the values into a tuple
image_resolution = (x_resolution, y_resolution)

# Print
print(image_resolution)

如果有多个图像元素,DPX 可能会成为一种很难解析的格式 - 上面的代码应该可以为您提供大多数用例(单个图像元素)所需的内容,而无需导入大旧图书馆。

掌握 DPX 的 SMPTE 标准并粗略浏览一下(2014 年的最新修订版)是非常值得的,因为它列出了 header.[=11= 中其他好东西的所有偏移量]