import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('./resource/opencv/image/sudoku.png', cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
for i in range(len(lines)):
# for rho, thetha in lines[10]:
rho = lines[i][0][0]
thetha = lines[i][0][1]
a = np.cos(thetha)
b = np.sin(thetha)
x0 = a*rho
y0 = b*rho
line_length = 1000 # 线长
x1 = int(x0 + line_length*(-b))
y1 = int(y0 + line_length*(a))
x2 = int(x0 - line_length*(-b))
y2 = int(y0 - line_length*(a))
cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 1)
# 因为gray和edges都是单通道的,为了可以和原图拼接合并,需要merge成3通道图像数据
gray = cv2.merge((gray, gray, gray))
edges = cv2.merge((edges,edges,edges))
# 图像拼接
res = np.hstack((gray,edges,img))
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
渐进概率式霍夫变换
cv2.HoughLinesP(image: Mat, rho, theta, threshold, lines=…, minLineLength=…, maxLineGap=…)
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('./resource/opencv/image/sudoku.png', cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray, 50, 150, apertureSize=3)
minLineLength = 100
maxLineGap = 10
# HoughLinesP(image: Mat, rho, theta, threshold, lines=..., minLineLength=..., maxLineGap=...)
lines = cv2.HoughLinesP(canny, 1, np.pi/180, 100, minLineLength, maxLineGap)
print(lines.shape)
print(lines[0])
for i in range(len(lines)):
for x1,y1,x2,y2 in lines[i]:
cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 1)
gray = cv2.merge((gray, gray, gray))
canny = cv2.merge((canny,canny,canny))
res = np.hstack((gray, canny, img))
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
在含有坐标点集合中寻找是否存在直线:
cv2.HoughLinesPointSet(_point, lines_max, threshold, min_rho, max_rho, rho_step, min_theta, max_theta, theta_step, _lines=…)
import numpy as np
import cv2
img = cv2.imread('./resource/opencv/image/logo/opencv-logo2.png', cv2.IMREAD_GRAYSCALE)
img = cv2.medianBlur(img, 5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=30, maxRadius=0)
print(circles)
circles = np.uint16(circles)
print(circles)
for i in circles[0, :]:
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
cv2.imshow('detected circles', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()