import numpy as np
import cv2
from matplotlib import pyplot as plt
def imshow(imgname,img):
h ,w = img.shape[:2]
cv2.namedWindow(imgname, cv2.WINDOW_NORMAL)
cv2.resizeWindow(imgname, int(w * 0.3), int(h * 0.3))
cv2.imshow(imgname, img)
def waterSeg(img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
thresh = cv2.bitwise_not(thresh)
imshow('thresh',thresh)
# noise removal
# kernel = np.ones((3,3),np.uint8)
# opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2) # 形态开运算
# sure_bg = cv2.dilate(opening,kernel,iterations=3)
# cv2.imshow('sure_bg',sure_bg)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(thresh,cv2.DIST_L2,5)
# imshow('dist_transform',dist_transform)
# print(0.7*dist_transform.max())
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,cv2.THRESH_BINARY)
imshow('sure_fg',sure_fg)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(thresh,sure_fg)
imshow('unknown',unknown)
# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers + 1
# Now, mark the region of unknown with zero
markers[unknown==255] = 0
markersw = cv2.watershed(img,markers)
img[markersw == -1] = [255,0,0]
imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
# img = cv2.imread('20200608\\1592124020(1).jpg')
img = cv2.imread('handwrite\\1592629465(1).jpg')
waterSeg(img)
分水岭
最新推荐文章于 2025-06-01 00:43:35 发布