6. I/O 外掛程式基礎架構#
外掛程式由兩個檔案組成:原始碼和描述符 .ini
。假設我們想使用 matplotlib
為 imshow
提供外掛程式。我們將外掛程式命名為 mpl
skimage/io/_plugins/mpl.py
skimage/io/_plugins/mpl.ini
.py
和 .ini
檔案的名稱必須對應。在 .ini
檔案中,我們提供外掛程式的元數據
[mpl] <-- name of the plugin, may be anything
description = Matplotlib image I/O plugin
provides = imshow <-- a comma-separated list, one or more of
imshow, imsave, imread, _app_show
“provides” 行列出外掛程式提供的所有函數。由於我們的外掛程式提供 imshow
,因此我們必須在 mpl.py
中定義它
# This is mpl.py
import matplotlib.pyplot as plt
def imshow(img):
plt.imshow(img)
請注意,預設情況下,imshow
是非阻塞的,因此必須提供特殊的函數 _app_show
來阻塞 GUI。我們可以修改我們的外掛程式以提供它,如下所示
[mpl]
provides = imshow, _app_show
# This is mpl.py
import matplotlib.pyplot as plt
def imshow(img):
plt.imshow(img)
def _app_show():
plt.show()
_plugins
目錄中的任何外掛程式都會在匯入時由 skimage.io
自動檢查。您可以列出系統上的所有外掛程式
>>> import skimage as ski
>>> ski.io.find_available_plugins()
{'gtk': ['imshow'],
'matplotlib': ['imshow', 'imread', 'imread_collection'],
'pil': ['imread', 'imsave', 'imread_collection'],
'test': ['imsave', 'imshow', 'imread', 'imread_collection'],}
或僅列出已載入的外掛程式
>>> ski.io.find_available_plugins(loaded=True)
{'matplotlib': ['imshow', 'imread', 'imread_collection'],
'pil': ['imread', 'imsave', 'imread_collection']}
外掛程式是使用 use_plugin
命令載入的
>>> ski.io.use_plugin('pil') # Use all capabilities provided by PIL
或
>>> ski.io.use_plugin('pil', 'imread') # Use only the imread capability of PIL
請注意,如果多個外掛程式提供某些功能,則使用最後載入的外掛程式。
若要查詢外掛程式的功能,請使用 plugin_info
>>> ski.io.plugin_info('pil')
>>>
{'description': 'Image reading via the Python Imaging Library',
'provides': 'imread, imsave'}