基於初始種子自動選取的區域生長(python+opencv)


 算法中,初始種子可自動選擇(通過不同的划分可以得到不同的種子,可按照自己需要改進算法),圖分別為原圖(自己畫了兩筆為了分割成不同區域)、灰度圖直方圖、初始種子圖、區域生長結果圖。另外,不管時初始種子選擇還是區域生長,閾值選擇很重要。

import cv2
import numpy as np
import  matplotlib.pyplot as plt

#初始種子選擇
def originalSeed(gray, th):
    ret, thresh = cv2.cv2.threshold(gray, th, 255, cv2.THRESH_BINARY)#二值圖,種子區域(不同划分可獲得不同種子)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))#3×3結構元

    thresh_copy = thresh.copy() #復制thresh_A到thresh_copy
    thresh_B = np.zeros(gray.shape, np.uint8) #thresh_B大小與A相同,像素值為0

    seeds = [ ] #為了記錄種子坐標

    #循環,直到thresh_copy中的像素值全部為0
    while thresh_copy.any():

        Xa_copy, Ya_copy = np.where(thresh_copy > 0) #thresh_A_copy中值為255的像素的坐標
        thresh_B[Xa_copy[0], Ya_copy[0]] = 255 #選取第一個點,並將thresh_B中對應像素值改為255

        #連通分量算法,先對thresh_B進行膨脹,再和thresh執行and操作(取交集)
        for i in range(200):
            dilation_B = cv2.dilate(thresh_B, kernel, iterations=1)
            thresh_B = cv2.bitwise_and(thresh, dilation_B)

        #取thresh_B值為255的像素坐標,並將thresh_copy中對應坐標像素值變為0
        Xb, Yb = np.where(thresh_B > 0)
        thresh_copy[Xb, Yb] = 0

        #循環,在thresh_B中只有一個像素點時停止
        while str(thresh_B.tolist()).count("255") > 1:
            thresh_B = cv2.erode(thresh_B,  kernel, iterations=1) #腐蝕操作

        X_seed, Y_seed = np.where(thresh_B > 0) #取處種子坐標
        if X_seed.size > 0 and Y_seed.size > 0:
            seeds.append((X_seed[0], Y_seed[0]))#將種子坐標寫入seeds
        thresh_B[Xb, Yb] = 0 #將thresh_B像素值置零
    return seeds

#區域生長
def regionGrow(gray, seeds, thresh, p):
    seedMark = np.zeros(gray.shape)
    #八鄰域
    if p == 8:
        connection = [(-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1)]
    elif p == 4:
        connection = [(-1, 0), (0, 1), (1, 0), (0, -1)]

    #seeds內無元素時候生長停止
    while len(seeds) != 0:
        #棧頂元素出棧
        pt = seeds.pop(0)
        for i in range(p):
            tmpX = pt[0] + connection[i][0]
            tmpY = pt[1] + connection[i][1]

            #檢測邊界點
            if tmpX < 0 or tmpY < 0 or tmpX >= gray.shape[0] or tmpY >= gray.shape[1]:
                continue

            if abs(int(gray[tmpX, tmpY]) - int(gray[pt])) < thresh and seedMark[tmpX, tmpY] == 0:
                seedMark[tmpX, tmpY] = 255
                seeds.append((tmpX, tmpY))
    return seedMark


path = "_rg.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#hist = cv2.calcHist([gray], [0], None, [256], [0,256])#直方圖

seeds = originalSeed(gray, th=253)
seedMark = regionGrow(gray, seeds, thresh=3, p=8)

#plt.plot(hist)
#plt.xlim([0, 256])
#plt.show()
cv2.imshow("seedMark", seedMark)
cv2.waitKey(0)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM