2013-04-05 17:02:07 +08:00
|
|
|
#!/usr/bin/python
|
2015-12-15 07:33:55 +08:00
|
|
|
|
2013-04-05 17:02:07 +08:00
|
|
|
'''
|
|
|
|
This example illustrates how to use Hough Transform to find lines
|
2015-12-15 07:33:55 +08:00
|
|
|
|
|
|
|
Usage:
|
|
|
|
houghlines.py [<image_name>]
|
2018-11-14 23:56:21 +08:00
|
|
|
image argument defaults to pic1.png
|
2013-04-05 17:02:07 +08:00
|
|
|
'''
|
2015-12-15 07:33:55 +08:00
|
|
|
|
2015-09-14 00:00:22 +08:00
|
|
|
# Python 2/3 compatibility
|
|
|
|
from __future__ import print_function
|
|
|
|
|
2017-12-11 17:55:03 +08:00
|
|
|
import cv2 as cv
|
2013-04-05 17:02:07 +08:00
|
|
|
import numpy as np
|
|
|
|
import sys
|
|
|
|
import math
|
|
|
|
|
2015-08-05 05:01:51 +08:00
|
|
|
if __name__ == '__main__':
|
2015-12-15 07:33:55 +08:00
|
|
|
print(__doc__)
|
2013-04-05 17:02:07 +08:00
|
|
|
|
2015-08-05 05:01:51 +08:00
|
|
|
try:
|
|
|
|
fn = sys.argv[1]
|
2015-12-15 07:33:55 +08:00
|
|
|
except IndexError:
|
2018-11-14 23:56:21 +08:00
|
|
|
fn = 'pic1.png'
|
2015-12-15 07:33:55 +08:00
|
|
|
|
2018-11-14 23:56:21 +08:00
|
|
|
src = cv.imread(cv.samples.findFile(fn))
|
2017-12-11 17:55:03 +08:00
|
|
|
dst = cv.Canny(src, 50, 200)
|
|
|
|
cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
|
2015-02-20 17:18:08 +08:00
|
|
|
|
2015-08-05 05:01:51 +08:00
|
|
|
if True: # HoughLinesP
|
2017-12-11 17:55:03 +08:00
|
|
|
lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
|
2015-08-05 05:01:51 +08:00
|
|
|
a,b,c = lines.shape
|
|
|
|
for i in range(a):
|
2017-12-11 17:55:03 +08:00
|
|
|
cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)
|
2013-04-05 17:02:07 +08:00
|
|
|
|
2015-08-05 05:01:51 +08:00
|
|
|
else: # HoughLines
|
2017-12-11 17:55:03 +08:00
|
|
|
lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)
|
2016-09-15 02:39:11 +08:00
|
|
|
if lines is not None:
|
2016-06-02 17:00:23 +08:00
|
|
|
a,b,c = lines.shape
|
|
|
|
for i in range(a):
|
|
|
|
rho = lines[i][0][0]
|
|
|
|
theta = lines[i][0][1]
|
|
|
|
a = math.cos(theta)
|
|
|
|
b = math.sin(theta)
|
|
|
|
x0, y0 = a*rho, b*rho
|
|
|
|
pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) )
|
|
|
|
pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) )
|
2017-12-11 17:55:03 +08:00
|
|
|
cv.line(cdst, pt1, pt2, (0, 0, 255), 3, cv.LINE_AA)
|
2016-06-13 15:00:42 +08:00
|
|
|
|
2017-12-11 17:55:03 +08:00
|
|
|
cv.imshow("detected lines", cdst)
|
2013-04-05 17:02:07 +08:00
|
|
|
|
2017-12-11 17:55:03 +08:00
|
|
|
cv.imshow("source", src)
|
|
|
|
cv.waitKey(0)
|