霍夫變換(Hough Transform)是圖像處理中的一種特征提取技術,它通過一種投票算法檢測具有特定形狀的物體。Hough變換是圖像處理中從圖像中識別幾何形狀的基本方法之一。Hough變換的基本原理在于利用點與線的對偶性,將原始圖像空間的給定的曲線通過曲線表達形式變為參數空間的一個點。這樣就把原始圖像中給定曲線的檢測問題轉化為尋找參數空間中的峰值問題。也即把檢測整體特性轉化為檢測局部特性。比如直線、橢圓、圓、弧線等。
簡單說opencv中霍夫變換可以幫助我們查找到一幅圖像當中的直線或者圓。
import cv2
import numpy as np
from matplotlib import pyplot as pltimg = cv2.imread('002.tif', 0)
rows, cols = img.shape
img_p = img.copy()
img_C = img.copy()edges = cv2.Canny(img, 50, 170, apertureSize=3)
# 精度:取值范圍0.1-2(默認值1)
accuracy = 2
# 閾值:取值范圍1-255(小于200意義不大,默認值200)
threshold = 200# 霍夫曼直線變換
lines = cv2.HoughLines(edges, accuracy, np.pi/180, threshold)
for line in lines:rho, theta = line[0]a = np.cos(theta)b = np.sin(theta)x0 = a*rhoy0 = b*rhox1 = int(x0 + 1000*(-b))y1 = int(y0 + 1000*(a))x2 = int(x0 - 1000*(-b))y2 = int(y0 - 1000*(a))cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)# 概率霍夫直線變換
lines = cv2.HoughLinesP(edges, accuracy, np.pi/180, threshold, minLineLength=0, maxLineGap=0)
for line in lines:x1, y1, x2, y2 = line[0]# 繪制直線cv2.line(img_p, (x1, y1), (x2, y2), (0, 255, 0), 2)_, thresh= cv2.threshold(img, 150, 255, cv2.THRESH_TOZERO)
# 霍夫圓變換
# dp累加器分辨率與圖像分辨率的反比默認1.5,取值范圍0.1-10
dp = 2
# minDist檢測到的圓心之間的最小距離。如果參數太小,則除了真實的圓圈之外,還可能會錯誤地檢測到多個鄰居圓圈。 如果太大,可能會錯過一些圈子。取值范圍10-500
minDist = 20
circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, dp, minDist, param1=45, param2=45, minRadius=0, maxRadius=50)
circles = np.uint16(np.around(circles))
for i in circles[0, :]:# 繪制外圓cv2.circle(img_C, (i[0], i[1]), i[2], (0, 255, 0), 2)# 繪制圓心cv2.circle(img_C, (i[0], i[1]), 2, (0, 0, 255), 2)cv2.imshow('img', img)
cv2.imshow("img-p", img_p)
cv2.imshow("img_C", img_C)
cv2.waitKey()


