霍夫變換
查看圖像
import matplotlib.pyplot as plt
import numpy as np
import cv2
# 讀取圖像
img = cv2.imread('bright-close-up-colorful-2097221.jpg')
# 復制圖像
img_copy = np.copy(img)
# 顏色空間轉換:BGR——RGB
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 顯示圖像
plt.imshow(img_rgb)
plt.show()
結果:
01.png
邊緣檢測
# 灰度圖像
gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)
# 高斯濾波
gray_blur = cv2.GaussianBlur(gray, (5,5), 0)
plt.imshow(gray_blur,cmap="gray")
plt.show()
# 設置canny的參數
low_threshold = 120
high_threshold = 200
edges = cv2.Canny(gray_blur,low_threshold,high_threshold)
plt.figure(figsize=(10,8))
plt.imshow(edges,cmap="gray")
plt.show()
結果:
03.png
霍夫變換檢測直線
# 使用霍夫變換尋找直線
# 參數設置
rho = 1
theta = np.pi/180
threshold = 65
min_line_length = 250
max_line_gap = 6
# 尋找直線
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
line_image = np.copy(img_copy)
# 繪制直線
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),5)
plt.imshow(line_image)
plt.show()
結果:
04.png