在圖片處理中,霍夫變換主要是用來檢測圖片中的幾何形狀,包括直線、圓、橢圓等。
在skimage中,霍夫變換是放在tranform模塊內,本篇主要講解霍夫線變換。
對于平面中的一條直線,在笛卡爾坐標系中,可用y=mx+b來表示,其中m為斜率,b為截距。但是如果直線是一條垂直線,則m為無窮大,所有通常我們在另一坐標系中表示直線,即極坐標系下的r=xcos(theta)+ysin(theta)。即可用(r,theta)來表示一條直線。其中r為該直線到原點的距離,theta為該直線的垂線與x軸的夾角。如下圖所示。
對于一個給定的點(x0,y0), 我們在極坐標下繪出所有通過它的直線(r,theta),將得到一條正弦曲線。如果將圖片中的所有非0點的正弦曲線都繪制出來,則會存在一些交點。所有經過這個交點的正弦曲線,說明都擁有同樣的(r,theta), 意味著這些點在一條直線上。
發上圖所示,三個點(對應圖中的三條正弦曲線)在一條直線上,因為這三個曲線交于一點,具有相同的(r, theta)。霍夫線變換就是利用這種方法來尋找圖中的直線。
函數:skimage.transform.hough_line(img)
返回三個值:
h: 霍夫變換累積器
theta: 點與x軸的夾角集合,一般為0-179度
distance: 點到原點的距離,即上面的所說的r.
例:
import skimage.transform as stimport numpy as npimport matplotlib.pyplot as plt # 構建測試圖片image = np.zeros((100, 100)) #背景圖idx = np.arange(25, 75) #25-74序列image[idx[::-1], idx] = 255 # 線條/image[idx, idx] = 255 # 線條/ # hough線變換h, theta, d = st.hough_line(image) #生成一個一行兩列的窗口(可顯示兩張圖片).fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(8, 6))plt.tight_layout() #顯示原始圖片ax0.imshow(image, plt.cm.gray)ax0.set_title('Input image')ax0.set_axis_off() #顯示hough變換所得數據ax1.imshow(np.log(1 + h))ax1.set_title('Hough transform')ax1.set_xlabel('Angles (degrees)')ax1.set_ylabel('Distance (pixels)')ax1.axis('image')
從右邊那張圖可以看出,有兩個交點,說明原圖像中有兩條直線。
如果我們要把圖中的兩條直線繪制出來,則需要用到另外一個函數:
skimage.transform.hough_line_peaks(hspace, angles, dists)
用這個函數可以取出峰值點,即交點,也即原圖中的直線。
返回的參數與輸入的參數一樣。我們修改一下上邊的程序,在原圖中將兩直線繪制出來。
import skimage.transform as stimport numpy as npimport matplotlib.pyplot as plt # 構建測試圖片image = np.zeros((100, 100)) #背景圖idx = np.arange(25, 75) #25-74序列image[idx[::-1], idx] = 255 # 線條/image[idx, idx] = 255 # 線條/ # hough線變換h, theta, d = st.hough_line(image) #生成一個一行三列的窗口(可顯示三張圖片).fig, (ax0, ax1,ax2) = plt.subplots(1, 3, figsize=(8, 6))plt.tight_layout() #顯示原始圖片ax0.imshow(image, plt.cm.gray)ax0.set_title('Input image')ax0.set_axis_off() #顯示hough變換所得數據ax1.imshow(np.log(1 + h))ax1.set_title('Hough transform')ax1.set_xlabel('Angles (degrees)')ax1.set_ylabel('Distance (pixels)')ax1.axis('image') #顯示檢測出的線條ax2.imshow(image, plt.cm.gray)row1, col1 = image.shapefor _, angle, dist in zip(*st.hough_line_peaks(h, theta, d)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - col1 * np.cos(angle)) / np.sin(angle) ax2.plot((0, col1), (y0, y1), '-r')ax2.axis((0, col1, row1, 0))ax2.set_title('Detected lines')ax2.set_axis_off()
新聞熱點
疑難解答