直接呼叫原生的 cv 2 hough 函式 cv.houghline()
implement self 實作 def(): 再現
# -*- coding: utf-8 -*-
import cv2
import math
import numpy as np
def myhough(img):
thetas = np.deg2rad(np.arange(-90.0, 90.0,1)).astype(int)
cost = np.cos(thetas)
sint = np.sin(thetas)
row,column = np.nonzero(img)
rhoss = []
for i in range(len(thetas)):
r = row[i]
c = column[i]
rho = r*cost[i]+c*sint[i]
rho = rho.astype(int)
rhoss.append(rho)
return rhoss,thetas
img = cv2.imread("2.png")
img = cv2.resize(img,(1000,500))
img = cv2.GaussianBlur(img,(3,3),0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges,1,2,100)
r,h = myhough(edges)
cv = img.copy()
my = img.copy()
ano = img.copy()
for z,w in zip(r,h):
a = np.cos(w)
b = np.sin(w)
x0 = z * a
y0 = z * b
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * a)
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * a)
results = cv2.line(my, (x1, y1), (x2, y2), (0, 0, 255), 1)
for line in lines:
rho, theta = line[0]
'''
if(theta<90 or theta >270):
pt1 = (int(rho/np.cos(theta)),0)
pt2 = (int((rho-ano.shape[0]*np.sin(theta))/np.cos(theta)),ano.shape[0])
cv2.line(ano, pt1, pt2, (255))
else:
pt1 = (0,int(rho/np.sin(theta)))
pt2 = (ano.shape[1], int((rho-ano.shape[1]*np.cos(theta))/np.sin(theta)))
cv2.line(ano, pt1, pt2, (255), 1)
'''
a = np.cos(theta)
b = np.sin(theta)
x0 = rho * a
y0 = rho * b
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * a)
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * a)
result = cv2.line(cv, (x1, y1), (x2, y2), (0, 0, 255), 1)
cv2.imshow("01", results)
cv2.waitKey(0)
cv2.destroyWindow('01')