Python+OpenCV实现阈值分割的方法详解

  import cv2

  import numpy as np

  import matplotlib.pyplot as plt

  #载入原图,转化为灰度图像,并通过cv2.resize()等比调整图像大小

  img_original=cv2.imread(r'E:pypython3.7 est2 est14yuzhicell.png',0)

  img_original=cv2.resize(img_original,(0,0),fx=0.3,fy=0.3)

  #初始化阈值,定义全局变量imgs

  thresh=130

  imgs=0

  #创建滑动条回调函数,参数thresh为滑动条对应位置的数值

  def threshold_segmentation(thresh):

  #采用5种阈值类型(thresholding type)分割图像

  retval1,img_binary=cv2.threshold(img_original,thresh,255,cv2.THRESH_BINARY)

  retval2,img_binary_invertion=cv2.threshold(img_original,thresh,255,cv2.THRESH_BINARY_INV)

  retval3,img_trunc=cv2.threshold(img_original,thresh,255,cv2.THRESH_TRUNC)

  retval4,img_tozero=cv2.threshold(img_original,thresh,255,cv2.THRESH_TOZERO)

  retval5,img_tozero_inversion=cv2.threshold(img_original,thresh,255,cv2.THRESH_TOZERO_INV)

  #由于cv2.imshow()显示的是多维数组(ndarray),因此我们通过np.hstack(数组水平拼接)

  #和np.vstack(竖直拼接)拼接数组,达到同时显示多幅图的目的

  img1=np.hstack([img_original,img_binary,img_binary_invertion])

  img2=np.hstack([img_trunc,img_tozero,img_tozero_inversion])

  global imgs

  imgs=np.vstack([img1,img2])

  #新建窗口

  cv2.namedWindow('Images')

  #新建滑动条,初始位置为130

  cv2.createTrackbar('threshold value','Images',130,255,threshold_segmentation)

  #第一次调用函数

  threshold_segmentation(thresh)

  #显示图像

  while(1):

  cv2.imshow('Images',imgs)

  if cv2.waitKey(1)==ord('q'):

  break

  cv2.destroyAllWindows()