opencv 分水岭分割图像

 

import cv2  
import numpy as np  
  
# 加载图像  
img = cv2.imread('image.jpg', 0)  
  
# 对图像进行分水岭算法的梯度变换  
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=3)  
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=3)  
mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True)  
  
# 计算梯度方向直方图  
hist_2d = cv2.calcHist([gx, gy], [0], None, [256], [0, 256])  
  
# 找到自相关图中的“山脊”  
_, contours, hierarchy = cv2.connectedComponents(mag)  
  
# 分割前景和背景  
_, threshold = cv2.threshold(hist_2d, 0.7*np.max(hist_2d), 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)  
  
# 绘制前景和背景的边界  
img[threshold==255] = [0, 0, 255]  
  
# 显示结果  
cv2.imshow('Original Image', img)  
cv2.imshow('Segmented Image', img[threshold==255])  
cv2.waitKey(0)  
cv2.destroyAllWindows()

 

 

 

###################

posted @ 2023-05-25 20:55  西北逍遥  阅读(10)  评论(0编辑  收藏  举报