Python+OpenCV:基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)

以你之姓@ 2022-12-22 14:30 278阅读 0赞

Python+OpenCV:基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)

  1. ####################################################################################################
  2. # 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)
  3. def lmc_cv_image_segmentation_watershed():
  4. """
  5. 函数功能: 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)。
  6. """
  7. # 读取图像
  8. image = lmc_cv.imread('D:/99-Research/Python/Image/water_coins.jpg', flags=lmc_cv.IMREAD_UNCHANGED)
  9. rgb_image = lmc_cv.cvtColor(image, lmc_cv.COLOR_BGR2RGB)
  10. rgb_image_result = rgb_image.copy()
  11. gray_image = lmc_cv.cvtColor(rgb_image, lmc_cv.COLOR_RGB2GRAY)
  12. # 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)
  13. ret, thresh_image = lmc_cv.threshold(gray_image, 0, 255, lmc_cv.THRESH_BINARY_INV + lmc_cv.THRESH_OTSU)
  14. # noise removal
  15. kernel = np.ones((3, 3), np.uint8)
  16. opening_image = lmc_cv.morphologyEx(thresh_image, lmc_cv.MORPH_OPEN, kernel, iterations=2)
  17. # sure background area
  18. sure_bg_image = lmc_cv.dilate(opening_image, kernel, iterations=3)
  19. # Finding sure foreground area
  20. dist_transform = lmc_cv.distanceTransform(opening_image, lmc_cv.DIST_L2, 5)
  21. ret, sure_fg_image = lmc_cv.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
  22. # Finding unknown region
  23. sure_fg_image = np.uint8(sure_fg_image)
  24. unknown = lmc_cv.subtract(sure_bg_image, sure_fg_image)
  25. # Marker labelling
  26. ret, markers_image = lmc_cv.connectedComponents(sure_fg_image)
  27. # Add one to all labels so that sure background is not 0, but 1
  28. markers_image = markers_image + 1
  29. # Now, mark the region of unknown with zero
  30. markers_image[unknown == 255] = 0
  31. markers_image = lmc_cv.watershed(rgb_image_result, markers_image)
  32. rgb_image_result[markers_image == -1] = [255, 0, 0]
  33. # 显示图像
  34. pyplot.figure('Image Display')
  35. titles = ['Original Image', 'Thresh Image', 'ForeGround Image', 'BackGround Image', 'Distance Transform Image',
  36. 'Markers Image', 'Result Image']
  37. images = [rgb_image, thresh_image, sure_fg_image, sure_bg_image, dist_transform, markers_image, rgb_image_result]
  38. for i in range(7):
  39. pyplot.subplot(2, 4, i + 1)
  40. pyplot.imshow(images[i], 'gray')
  41. pyplot.title(titles[i])
  42. pyplot.xticks([])
  43. pyplot.yticks([])
  44. pyplot.show()
  45. # 根据用户输入保存图像
  46. if ord("q") == (lmc_cv.waitKey(0) & 0xFF):
  47. # 销毁窗口
  48. pyplot.close('all')
  49. return

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpdWJpbmc4NjA5_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,278人围观)

还没有评论,来说两句吧...

相关阅读