基于OpenCV的初始种子自动选取与区域生长算法实现
本文介绍一种基于OpenCV的区域生长图像分割方法,重点解决初始种子点的自动选取问题。通过二值化与形态学操作生成种子坐标,并结合连通分量算法进行区域生长。文章提供了完整的Python代码示例及处理结果图,展示了从原始图像到最终分割效果的全过程,并强调了阈值选择对算法性能的关键影响。
初始种子自动选取与区域生长流程
该算法的核心在于初始种子点的自动选取机制。通过不同的阈值划分策略,可以获得不同的种子分布,用户可根据实际需求对算法进行改进。实验过程展示了四幅关键图像:原始输入图像(为演示分割效果手动绘制)、灰度图像的直方图分布、生成的初始种子标记图,以及最终的区域生长分割结果。
阈值选择的关键性分析
在区域生长算法中,无论是初始种子的选择策略,还是生长过程中的阈值设定,都起着至关重要的作用。合理的阈值选择直接决定了分割的准确性和区域的完整性。
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)




总结与参考
以上关于初始种子自动选取的区域生长实例(Python+OpenCV)的全部内容分享完毕,希望能为读者提供有价值的参考。欢迎大家支持本站,获取更多技术资源。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













