diff --git a/mahotas/tests/find_hough_line.py b/mahotas/tests/find_hough_line.py new file mode 100644 index 00000000..71907532 --- /dev/null +++ b/mahotas/tests/find_hough_line.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2018, Jasson <1917098992@qq.com> +# License: MIT (see COPYING file) +import collections +import math +import numpy as np + +def find_hough_lines(im): + ''' + line = find(img={square}) + detect lines in the image using the Hough transform + Parameters + ---------- + img : ndarray + input. the binary image conatins lines(the value equals one, the backgroud value equals zero). + Returns + ------- + line : ndarray of line in the image + ''' + c = LineDetectorByHough() + return c.find(im) +class Line(): + def __init__(self,r,angle): + self.r = r + self.angle = angle + def __eq__(self, other): + if self.r == other.r and self.angle == other.angle: + return True + else: + return False + def __hash__(self): + result = 31 + int(self.r) + result = 31 * result + int(self.angle * 100) + return result +class LineDetectorByHough: + countersDICT = collections.Counter() + def __init__(self): + pass + + def find(self,img): + rows, cols = img.shape + + points = 0 + for x in range(0, rows): + for y in range(0, cols): + if (img[x, y] == 1): + points = points + 1 + for angle in np.arange(0, 2 * np.pi, 2 * np.pi / 40): + # print 'angel=',x, y, angel + angle = round(angle, 2) + angle = angle % round(np.pi, 2) + r = round(self.calcR(x, y, angle),1) + #print 'r,angel=', r, angle + self.countersDICT[Line(r, angle)] += 1 + #print "points=", points + #print "line (r ,angle) count" + for (k, v) in self.countersDICT.items(): + if(v > rows/2): + return Line(k.r, k.angle) + def calcR(self,x,y,angle): + return x* math.cos(angle) + y * math.sin(angle) diff --git a/mahotas/tests/test_hough_transform_line.py b/mahotas/tests/test_hough_transform_line.py new file mode 100644 index 00000000..40aa71fd --- /dev/null +++ b/mahotas/tests/test_hough_transform_line.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2008-2014, Jasson <1917098992@qq.com> +# License: MIT (see COPYING file) +import unittest +import numpy as np +import math +from mahotas.tests.find_hough_line import find_hough_lines +from mahotas.tests.find_hough_line import LineDetectorByHough +from mahotas.tests.find_hough_line import Line +class test_hough_transform_line(unittest.TestCase): + + def test_simpleImg_hough_detect(self): + img = np.zeros((80, 80), bool) + img[6,:] = 1 + lines = find_hough_lines(img) + + self.assertEqual(lines,Line(6,0)) + + def test_counter(self): + c = LineDetectorByHough + + line = Line(10,np.pi/4) + c.countersDICT[line] += 1 + + line = Line(10,np.pi/4) + c.countersDICT[line] += 2 + + self.assertEqual(c.countersDICT[line], 3) + + def test_line_r_calc(self): + c = LineDetectorByHough() + self.assertEqual(c.calcR(10,10,np.pi/4), math.sqrt(10*10 + 10*10)) + + + +