漩渦#

影像漩渦是一種非線性的影像變形,會產生漩渦效果。此範例描述了此轉換在 skimage 中的實作方式,以及底層的扭曲機制。

影像扭曲#

當對影像套用幾何變換時,我們通常會使用反向映射,也就是說,對於輸出影像中的每個像素,我們會計算其在輸入影像中的對應位置。原因是,如果我們反過來做 (將每個輸入像素映射到其新的輸出位置),則輸出中的某些像素可能會留空。另一方面,每個輸出座標在輸入影像中 (或外部) 都恰好有一個對應的位置,即使該位置不是整數,我們也可以使用內插法來計算對應的影像值。

執行反向映射#

若要在 skimage 中執行幾何扭曲,您只需要將反向映射提供給 skimage.transform.warp() 函式。例如,考慮我們要將影像向左移動 50 像素的情況。此類移動的反向映射會是

def shift_left(xy):
    xy[:, 0] += 50
    return xy

對應的扭曲呼叫為

from skimage.transform import warp
warp(image, shift_left)

漩渦變換#

考慮輸出影像中的座標 \((x, y)\)。漩渦變換的反向映射會先計算相對於中心 \((x_0, y_0)\) 的極座標,

\[ \begin{align}\begin{aligned}\theta = \arctan((y-y0)/(x-x0))\\\rho = \sqrt{(x - x_0)^2 + (y - y_0)^2},\end{aligned}\end{align} \]

然後根據

\[ \begin{align}\begin{aligned}r = \ln(2) \, \mathtt{radius} / 5\\\phi = \mathtt{rotation}\\s = \mathtt{strength}\\\theta' = \phi + s \, e^{-\rho / r} + \theta\end{aligned}\end{align} \]

來轉換它們,其中 radius 表示漩渦的像素範圍,rotation 會加入旋轉角度,而 strength 則是漩渦量的參數。將 radius 轉換為 \(r\) 是為了確保轉換在指定的範圍內衰減至 \(\approx 1/1000^{\mathsf{th}}\)

plot swirl
import matplotlib.pyplot as plt

from skimage import data
from skimage.transform import swirl


image = data.checkerboard()
swirled = swirl(image, rotation=0, strength=10, radius=120)

fig, (ax0, ax1) = plt.subplots(
    nrows=1, ncols=2, figsize=(8, 3), sharex=True, sharey=True
)

ax0.imshow(image, cmap=plt.cm.gray)
ax0.axis('off')
ax1.imshow(swirled, cmap=plt.cm.gray)
ax1.axis('off')

plt.show()

腳本的總執行時間: (0 分鐘 0.132 秒)

由 Sphinx-Gallery 產生的圖庫