區域生長與分水嶺演算法 影象分割
阿新 • • 發佈:2019-01-03
1.區域生長法
import numpy as np import cv2 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 img = cv2.imread(r'C:\Users\feiyu\Desktop\tmy.jpg',0) seeds = [Point(766,667),Point(666,667),Point(10,10)] binaryImg = regionGrow(img,seeds,10) cv2.imshow(' ',binaryImg) cv2.waitKey(0)
效果:
2.分水嶺法
import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread(r'C:\Users\feiyu\Desktop\tmy.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) kernel = np.ones((3,3),np.uint8) opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2) # sure background area sure_bg = cv2.dilate(opening,kernel,iterations=3)#膨脹 # Finding sure foreground area dist_transform = cv2.distanceTransform(opening,2,5) ret, sure_fg = cv2.threshold(dist_transform,0.15*dist_transform.max(),255,0)#引數改小了,出現不確定區域 # Finding unknown region sure_fg = np.uint8(sure_fg) unknown = cv2.subtract(sure_bg,sure_fg)#減去前景 import matplotlib.pyplot as plt plt.figure() plt.gray() plt.imshow(sure_fg) plt.show()