溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python手動(dòng)實(shí)現(xiàn)Hough圓變換的示例代碼怎么寫

發(fā)布時(shí)間:2022-01-18 13:50:35 來(lái)源:億速云 閱讀:172 作者:kk 欄目:開發(fā)技術(shù)

今天給大家介紹一下Python手動(dòng)實(shí)現(xiàn)Hough圓變換的示例代碼怎么寫。文章的內(nèi)容小編覺得不錯(cuò),現(xiàn)在給大家分享一下,覺得有需要的朋友可以了解一下,希望對(duì)大家有所幫助,下面跟著小編的思路一起來(lái)閱讀吧。

Hough圓變換的原理很多博客都已經(jīng)說(shuō)得非常清楚了,但是手動(dòng)實(shí)現(xiàn)的比較少,所以本文直接貼上手動(dòng)實(shí)現(xiàn)的代碼。

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

Python手動(dòng)實(shí)現(xiàn)Hough圓變換的示例代碼怎么寫

 首先利用通過(guò)計(jì)算梯度來(lái)尋找邊緣,代碼如下:

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內(nèi)的數(shù)值比較大,所以得到了結(jié)果圖中的某些位置的數(shù)值超過(guò)255,但并不影響顯示,但如果想通過(guò)cv2.imshow來(lái)顯示,就需要將超過(guò)255的地方設(shè)為255即可(已經(jīng)在代碼中用注釋標(biāo)出),結(jié)果如下:

Python手動(dòng)實(shí)現(xiàn)Hough圓變換的示例代碼怎么寫

接下來(lái)就是要進(jìn)行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進(jìn)度:', 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

其中輸入是我們之前得到的邊緣圖,以及確定強(qiáng)邊緣的閾值,以及一個(gè)包含著我們估計(jì)的半徑的數(shù)組;返回值是強(qiáng)邊緣圖以及參數(shù)域矩陣。代碼中首先遍歷邊緣圖,通過(guò)閾值留下那些較強(qiáng)的位置,這里的閾值需要自己根據(jù)自己的輸入圖進(jìn)行調(diào)節(jié)。接著就是進(jìn)行Hough變換,這里的候選半徑集合需要根據(jù)自己的輸入圖進(jìn)行調(diào)節(jié)。在繪制參數(shù)域的過(guò)程中,只遍歷了所需正方形區(qū)域(大小為 r*r)的 1/4,這是因?yàn)樵谧鰠?shù)域上的一個(gè)點(diǎn)之后,由于圓的對(duì)稱性,就可以找到與之對(duì)稱的另外三個(gè)點(diǎn),無(wú)需額外進(jìn)行遍歷。

最后一步就是從參數(shù)域矩陣中提取出結(jié)果圓,代碼如下,其中篩選閾值需要根據(jù)你的輸入圖像自己調(diào)節(jié):

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 進(jìn)度:', 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('圓的數(shù)量:', 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

注意一下在這一步中需要將那些圓心相近的圓剔除掉,只保留一個(gè)結(jié)果。

接著是main函數(shù),這沒啥好說(shuō)的:

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內(nèi)的數(shù)更大
    # 但這并不影響圖像的顯示
    # 因此這里的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

下面是我的運(yùn)行結(jié)果:

Python手動(dòng)實(shí)現(xiàn)Hough圓變換的示例代碼怎么寫

python是什么意思

Python是一種跨平臺(tái)的、具有解釋性、編譯性、互動(dòng)性和面向?qū)ο蟮哪_本語(yǔ)言,其最初的設(shè)計(jì)是用于編寫自動(dòng)化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發(fā)獨(dú)立的項(xiàng)目和大型項(xiàng)目。

以上就是Python手動(dòng)實(shí)現(xiàn)Hough圓變換的示例代碼怎么寫的全部?jī)?nèi)容了,更多與Python手動(dòng)實(shí)現(xiàn)Hough圓變換的示例代碼怎么寫相關(guān)的內(nèi)容可以搜索億速云之前的文章或者瀏覽下面的文章進(jìn)行學(xué)習(xí)哈!相信小編會(huì)給大家增添更多知識(shí),希望大家能夠支持一下億速云!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI