是从一组代表不同生长区域的种子像素开始,接下来将种子像素邻域里符合条件的像素合并到种子像素所代表的生长区域中,并将新添加的像素作为新的种子像素继续合并过程,直到找不到符合条件的新像素为止。该方法的关键是选择合适的初始种子像素以及合理的生长准则。
下面给大家展示一个区域生长的例子和Python代码
#首先是区域生长一些函数的定义:
class Point(object):
def __init__(self,x,y):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def getGrayDiff(img,currentPoint,tmpPoint):
return abs(int(img[currentPoint.x,currentPoint.y]) - int(img[tmpPoint.x,tmpPoint.y]))
def selectConnects(p):
if p != 0:
connects = [Point(-1, -1), Point(0, -1), Point(1, -1), Point(1, 0), Point(1, 1), \
Point(0, 1), Point(-1, 1), Point(-1, 0)]
else:
connects = [ Point(0, -1), Point(1, 0),Point(0, 1), Point(-1, 0)]
return connects
def regionGrow(img,seeds,thresh,p = 1):
height, weight = img.shape
seedMark = np.zeros(img.shape)
seedList = []
for seed in seeds:
seedList.append(seed)
label = 1
connects = selectConnects(p)
while(len(seedList)>0):
currentPoint = seedList.pop(0)
seedMark[currentPoint.x,currentPoint.y] = label
for i in range(8):
tmpX = currentPoint.x + connects[i].x
tmpY = currentPoint.y + connects[i].y
if tmpX < 0 or tmpY < 0 or tmpX >= height or tmpY >= weight:
continue
grayDiff = getGrayDiff(img,currentPoint,Point(tmpX,tmpY))
if grayDiff < thresh and seedMark[tmpX,tmpY] == 0:
seedMark[tmpX,tmpY] = label
seedList.append(Point(tmpX,tmpY))
return seedMark
首先我们创建一张含圆圈的图:
import numpy as np
import cv2
image = np.ones((256, 256))
cv2.circle(image, (256//2, 256//2), int(100), (0,0,0), -1)
cv2.circle(image, (256//2, 256//2), int(50), (255,255,255), -1)
cv2.imwrite('test.png', 255*image)
运行之后会输出一张图如下:
下面我们采用区域生长法只保留中间的白色圆圈
image_copy = image.copy()//255
seeds = [Point(256//2,256//2)]
binaryImg = regionGrow(image_copy,seeds,1)
cv2.imwrite('test1.png', 255 * binaryImg)
区域生长法需要设定种子点,我们将种子点设为图像的中心点,即白色圆圈的中心点,区域生长只能长出白色圆圈的部分,其他部分为0,就是黑色。
本文分享自 Python编程和深度学习 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!