关于初始种子自动选取的区域生长实例(python+opencv)

2022-10-09,,,,

算法中,初始种子可自动选择(通过不同的划分可以得到不同的种子,可按照自己需要改进算法),图分别为原图(自己画了两笔为了分割成不同区域)、灰度图直方图、初始种子图、区域生长结果图。

另外,不管时初始种子选择还是区域生长,阈值选择很重要。

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)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

《关于初始种子自动选取的区域生长实例(python+opencv).doc》

下载本文的Word格式文档,以方便收藏与打印。