hough變換 python+OpenCV的簡單實現

直線的hough變換

import cv2
import numpy as np

# 導入圖片,處理圖片,變爲灰圖
img = cv2.imread('lines.jpg')
drawing = np.zeros(img.shape[:], dtype=np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)

# hough直線變換
lines = cv2.HoughLines(edges, 0.8, np.pi / 180, 90)

# lines有很多條線,每條線是都是記賬本表示,將檢測的線畫出來
for line in lines:
    rho, theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a * rho
    y0 = b * rho
    x1 = int(x0 + 1000 * (-b))
    y1 = int(y0 + 1000 * (a))
    x2 = int(x0 - 1000 * (-b))
    y2 = int(y0 - 1000 * (a))

    cv2.line(drawing, (x1, y1), (x2, y2), (0, 0, 255))

# # 統計概率霍夫變換方法
# lines = cv2.HoughLinesP(edges, 0.8, np.pi / 180, 90, minLineLength=50, maxLineGap=10)
#
# # lines有很多條線,每條線是都是記賬本表示,將檢測的線畫出來
# for line in lines:
#     x1, y1, x2, y2 = line[0]
#     cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA)

# 展示圖片
cv2.imshow('origin_picture', img)
cv2.imshow('hough_picture', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

運行結果圖:

圓的hough變換

import cv2
import numpy as np

# 導入圖片,得到灰圖
img = cv2.imread('circles.jpg')
drawing = np.zeros(img.shape[:], dtype=np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)

# hough圓變換
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1, 20, param2=30)
circles = np.int0(np.around(circles))

# 將檢查處理的圓畫出來
for i in circles[0, :]:
    cv2.circle(drawing, (i[0], i[1]), i[2], (0, 255, 0), 2)  # 畫出外圓
    cv2.circle(drawing, (i[0], i[1]), 2, (0, 0, 255), 3)  # 畫出圓心

# 展示圖片
cv2.imshow('origin_picture', img)
cv2.imshow('hough_picture', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

運行結果圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章