Python手動實現Hough圓變換的示例代碼

Hough圓變換的原理很多博客都已經說得非常清楚瞭,但是手動實現的比較少,所以本文直接貼上手動實現的代碼。

這裡使用的圖片是一堆硬幣:

 首先利用通過計算梯度來尋找邊緣,代碼如下:

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[i,j]>255:
            #  sobeling[i, j]=255
            # sobeling[i, j] = sobeling[i,j]/255
    return sobeling

需要註意的是,這裡使用的kernel內的數值比較大,所以得到瞭結果圖中的某些位置的數值超過255,但並不影響顯示,但如果想通過cv2.imshow來顯示,就需要將超過255的地方設為255即可(已經在代碼中用註釋標出),結果如下:

接下來就是要進行Hough圓變換,先看代碼:

def hough_circles(edge_image, edge_thresh, radius_values):
    h = edge_image.shape[0]
    w = edge_image.shape[1]
    # print(h,w)
    edgimg = np.zeros((h, w), np.int64)
    for i in range(h):
        for j in range(w):
            if edge_image[i][j] > edge_thresh:
                edgimg[i][j] = 255
            else:
                edgimg[i][j] = 0
 
    accum_array = np.zeros((len(radius_values), h, w))
    # return edgimg , []
    for i in range(h):
        print('Hough Transform進度:', i, '/', h)
        for j in range(w):
            if edgimg[i][j] != 0:
                for r in range(len(radius_values)):
                    rr = radius_values[r]
                    hdown = max(0, i - rr)
                    for a in range(hdown, i):
                        b = round(j+math.sqrt(rr*rr - (a - i) * (a - i)))
                        if b>=0 and b<=w-1:
                            accum_array[r][a][b] += 1
                            if 2 * i - a >= 0 and 2 * i - a <= h - 1:
                                accum_array[r][2 * i - a][b] += 1
                        if 2 * j - b >= 0 and 2 * j - b <= w - 1:
                            accum_array[r][a][2 * j - b] += 1
                        if 2 * i - a >= 0 and 2 * i - a <= h - 1 and 2 * j - b >= 0 and 2 * j - b <= w - 1:
                            accum_array[r][2 * i - a][2 * j - b] += 1
 
    return edgimg, accum_array

其中輸入是我們之前得到的邊緣圖,以及確定強邊緣的閾值,以及一個包含著我們估計的半徑的數組;返回值是強邊緣圖以及參數域矩陣。代碼中首先遍歷邊緣圖,通過閾值留下那些較強的位置,這裡的閾值需要自己根據自己的輸入圖進行調節。接著就是進行Hough變換,這裡的候選半徑集合需要根據自己的輸入圖進行調節。在繪制參數域的過程中,隻遍歷瞭所需正方形區域(大小為 r*r)的 1/4,這是因為在坐出參數域上的一個點之後,由於圓的對稱性,就可以找到與之對稱的另外三個點,無需額外進行遍歷。

最後一步就是從參數域矩陣中提取出結果圓,代碼如下,其中篩選閾值需要根據你的輸入圖像自己調節:

def find_circles(image, accum_array, radius_values, hough_thresh):
    returnlist = []
    hlist = []
    wlist = []
    rlist = []
    returnimg = deepcopy(image)
    for r in range(accum_array.shape[0]):
        print('Find Circles 進度:', r, '/', accum_array.shape[0])
        for h in range(accum_array.shape[1]):
            for w in range(accum_array.shape[2]):
                if accum_array[r][h][w] > hough_thresh:
 
                    tmp = 0
                    for i in range(len(hlist)):
                        if abs(w-wlist[i])<10 and abs(h-hlist[i])<10:
                            tmp = 1
                            break
 
                    if tmp == 0:
                        #print(accum_array[r][h][w])
                        rr = radius_values[r]
                        flag = '(h,w,r)is:(' + str(h) + ',' + str(w) + ',' + str(rr) + ')'
                        returnlist.append(flag)
                        hlist.append(h)
                        wlist.append(w)
                        rlist.append(rr)
 
    print('圓的數量:', len(hlist))
 
    for i in range(len(hlist)):
        center = (wlist[i], hlist[i])
        rr = rlist[i]
 
        color = (0, 255, 0)
        thickness = 2
        cv2.circle(returnimg, center, rr, color, thickness)
 
    return returnlist, returnimg

註意一下在這一步中需要將那些圓心相近的圓剔除掉,隻保留一個結果。

接著是main函數,這沒啥好說的:

def main(argv):
    img_name = argv[0]
 
    img = cv2.imread('data/' + img_name + '.png', cv2.IMREAD_COLOR)
    # print(img.shape[0], img.shape[1])
    gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
    # print(gray_image.shape[0], gray_image.shape[1])
    img1 = detect_edges(gray_image)
    cv2.imwrite('output/' + img_name + "_after_find_detect.png", img1)
 
    thresh = 1500
    # 需要註意的是,在img1中有些地方的像素值是高於255的,這是由於之前的kernel內的數更大
    # 但這並不影響圖像的顯示
    # 因此這裡的thresh要大於255
    radius_values = []
    for i in range(10):
        radius_values.append(20 + i)
 
    edgeimg, accum_array = hough_circles(img1, thresh, radius_values)
    cv2.imwrite('output/' + img_name + "_after_binary.png", edgeimg)
    # Findcircle
    hough_thresh = 70
    resultlist, resultimg = find_circles(img, accum_array, radius_values, hough_thresh)
 
    print(resultlist)
    cv2.imwrite('output/' + img_name + "_circles.png", resultimg)
 
 
if __name__ == '__main__':
    sys.argv.append("coins")
    main(sys.argv[1:])
    # TODO

下面是我的運行結果:

到此這篇關於Python手動實現Hough圓變換的示例代碼的文章就介紹到這瞭,更多相關Python Hough圓變換內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: