How to write the sample code for Python to manually implement Hough circle transformation
Today, I will show you how to write the sample code that Python manually implements Hough circle transformation. The content of the article is good. Now I would like to share it with you. Friends who feel in need can understand it. I hope it will be helpful to you. Let's read it along with the editor's ideas.
The principle of Hough circle transformation has been made very clear in many blogs, but there are few manual implementation, so this article directly pastes the manual implementation of the code.
The picture used here is a pile of coins:
First of all, find the edge by calculating the gradient, the code is as follows:
Def detect_edges (image): h = image.shape [0] w = image.shape [1] sobeling = np.zeros ((h, w), np.float64) sobelx = [[- 3,0,3], [- 10,0,10], [- 3,0,3]] sobelx = np.array (sobelx) sobely = [[- 3,10,-3], [0,0] 0], [3,10,3] sobely = np.array (sobely) gx = 0 gy = 0 testi = 0 for i in range (1, h-1): for j in range (1, w-1): edgex = 0 edgey = 0 for k in range (- 1,2): for l in range (- 1) 2): edgex + = image [k + I, l + j] * sobelx [1 + k, 1 + l] edgey + = image [k + I, l + j] * sobely [1 + k, 1 + l] gx = abs (edgex) gy = abs (edgey) sobeling [I, j] = gx + gy # if you want to imshow Run codes below first # if sobeling [iMagnej] > 255: # sobeling [iMagnej] = 255 # sobeling [iMagnej] = sobeling [iMagnej] / 255return sobeling
It is important to note that the values in the kernel used here are relatively large, so it is obtained that the values in some places in the result graph are more than 255. but it does not affect the display, but if you want to display them through cv2.imshow, you need to set the values above 255s to 255s (already marked with comments in the code). The results are as follows:
The next step is to transform the Hough circle. First look at the code:
Def hough_circles (edge_image, edge_thresh, radius_values): h = edge_image.shape [0] w = edge_image.shape [1] # print (hline w) edgimg = np.zeros ((h line w) Np.int64) for i in range (h): for j in range (w): if edge_ image [I] [j] > edge_thresh: edgimg [I] [j] = 255else: edgimg [I] [j] = 0 accum_array = np.zeros ((len (radius_values), h, w)) # return edgimg [] for i in range (h): print ('Hough Transform progress:', I,'/', h) for j in range (w): if edgimg [I] [j]! = 0: for rin range (len (radius_values)): rr = radius_ values [r] hdown = max (0 I-rr) for an in range (hdown I): B = round (j+math.sqrt (rr*rr-(a-I) * (a-I)) if b > = 0 and b = 0 and 2 * I-a = 0 and 2 * j-b = 0 and 2 * I-a = 0 and 2 * j-b hough_thresh: tmp = 0 for i in range (len (hlist)): if abs (w-wlist [I])