1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
   | import cv2 as cv import numpy as np import matplotlib.pyplot as plt from collections import deque
 
  def getGrayDiff(gray, current_seed, tmp_seed):     return abs(int(gray[current_seed[0], current_seed[1]]) - int(gray[tmp_seed[0], tmp_seed[1]]))
 
  def regional_growth(gray, seeds): 	     connects = [(-1, -1), (0, -1), (1, -1), (1, 0), \                 (1, 1), (0, 1), (-1, 1), (-1, 0)]     seedMark = np.zeros((gray.shape))     height, width = gray.shape     threshold = 6     seedque = deque()     label = 255     seedque.extend(seeds)
      while seedque :     	         current_seed = seedque.popleft()         seedMark[current_seed[0], current_seed[1]] = label         for i in range(8) :             tmpX = current_seed[0] + connects[i][0]             tmpY = current_seed[1] + connects[i][1]                          if tmpX < 0 or tmpY < 0 or tmpX >= height or tmpY >= width :                 continue
              grayDiff = getGrayDiff(gray, current_seed, (tmpX, tmpY))             if grayDiff < threshold and seedMark[tmpX, tmpY] != label :                 seedque.append((tmpX, tmpY))                 seedMark[tmpX, tmpY] = label     return seedMark
 
  def Event_Mouse(event, x, y, flags, param) : 	     if event == cv.EVENT_LBUTTONDOWN :     	         seeds.append((y, x))                  cv.circle(img, center = (x, y), radius = 2,                   color = (0, 0, 255), thickness = -1)
  def Region_Grow(img):     cv.namedWindow('img')     cv.setMouseCallback('img', Event_Mouse)     cv.imshow('img', img)
      while True :         cv.imshow('img', img)         if cv.waitKey(1) & 0xFF == ord('q') :             break     cv.destroyAllWindows()
 
      CT = cv.imread('images/CT.png', 1)     seedMark = np.uint8(regional_growth(cv.cvtColor(CT, cv.COLOR_BGR2GRAY), seeds))
      cv.imshow('seedMark', seedMark)     cv.waitKey(0)
      plt.figure(figsize=(12, 4))     plt.subplot(131), plt.imshow(cv.cvtColor(CT, cv.COLOR_BGR2RGB))     plt.axis('off'), plt.title(f'$input\_image$')     plt.subplot(132), plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB))     plt.axis('off'), plt.title(f'$seeds\_image$')     plt.subplot(133), plt.imshow(seedMark, cmap='gray', vmin = 0, vmax = 255)     plt.axis('off'), plt.title(f'$segmented\_image$')     plt.tight_layout()     plt.show()      if __name__ == '__main__':     img = cv.imread('./images/CT.png')     seeds = []     Region_Grow(img)
   |