在 Python 中確定影像型別?


在本節中,我們將瞭解我們擁有的影像檔案的型別。所以,考慮一種情況,在一個目錄中我們有數百個影像檔案,我們想要獲取所有 jpeg(或任何特定影像檔案型別)的檔案型別。所有這些我們都將使用 Python 以程式設計方式完成。

Python 提供庫來確定影像型別,其中一個庫是 imghdr。

Python 的 imghdr 包確定檔案中或位元組流中包含的影像型別。

安裝

如果您使用的是 Python 3.6 或更高版本,則 imghdr 模組是一個標準包,並將隨 Python 安裝一起提供。可能性非常大。

要在您的機器上安裝 imghdr,只需在您的命令終端中執行以下命令:

pip install imghdr

安裝成功後,要驗證 imghdr 是否已正確安裝,只需在您的 Python shell 中匯入該模組。

>>> import imghdr
>>>

如果您沒有收到任何錯誤,則表示 imghdr 已安裝在您的機器上。

語法

imghdr 包定義了以下函式:

imghdr.what(filename[, h])

其中

  • **檔名**:測試檔名指定的影像資料,並返回一個字串,描述影像型別。

  • **h**:這是可選的,如果存在 h,則忽略檔名,並假定 h 包含要測試的位元組流。

以下是使用 imghdr 包識別的允許的影像型別。


影像格式
'rgb'
SGI ImgLib 檔案
'gif'
GIF 87a 和 89a 檔案
'pbm'
行動式點陣圖檔案
'pgm'
行動式灰度圖檔案
'ppm'
行動式畫素圖檔案
'tiff'
TIFF 檔案
'rast'
Sun 光柵檔案
'xbm'
X 點陣圖檔案
'jpeg'
JFIF 或 Exif 格式的 JPEG 資料
'bmp'
BMP 檔案
'png'
行動式網路圖形

但是我們可以透過附加到此變數來擴充套件 imghdr 包可以識別的檔案型別列表。

imghdr.tests

此函式包含執行各個測試的函式列表。每個函式都接受兩個引數:位元組流和一個類似檔案的開啟物件。但是,當使用位元組流呼叫 what() 時,類似檔案的物件將為 None。

測試函式將返回影像型別作為字串,如果失敗則返回 None。

>>> import imghdr
>>> imghdr.what('clock.jpg')
'jpeg'

下面只是一個 imghdr 包的實現示例,如果存在某些特定的影像副檔名,則執行特定操作。

def identify_filetype(url, imageName, folderName):
   session = _setupSession()
   try:
      # time out is another parameter tuned
      image = session.get(url, timeout = 5)
      with open(os.path.join(folderName, imageName),'wb') as fout:
      fout.write(image.content)
      fileExtension = imghdr.what(os.path.join(folderName, imageName))
      if fileExtension is None:
         os.remove(os.path.join(folderName, imageName))
      else:
         newName = imageName + '.' + str(fileExtension)
         os.rename(os.path.join(folderName, imageName), os.path.join(folderName, newName))
except Exception as e:
print ("failed to download one pages with url of " + str(url))

更新於:2019年7月30日

4K+ 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.