实验五第二题

This commit is contained in:
2024-11-16 19:22:43 +08:00
parent 8dc570f602
commit 7d922845cf
2 changed files with 38 additions and 2 deletions
+36
View File
@@ -7,3 +7,39 @@
# 6、计算分水岭:根据合并图像,应用分水岭变换算法来计算分水岭,即将图像分割成不同的分水岭区域。
# 7、降噪和后处理:对分割结果进行降噪和后处理,例如去除小的分割区域、填充空洞等,以获得最终的分割结果。
import cv2 as cv
import numpy as np
img = cv.imread('test1.png', cv.IMREAD_GRAYSCALE)
img = cv.blur(img, (5, 5))
img = cv.convertScaleAbs(img, alpha=1.0, beta=2.0)
cv.imshow('origin', img)
grad_x = cv.Sobel(img, cv.CV_32F, 1, 0, ksize=3)
grad_y = cv.Sobel(img, cv.CV_32F, 0, 1, ksize=3)
grad = cv.magnitude(grad_x, grad_y)
ret, markers = cv.threshold(grad, 50, 255, cv.THRESH_BINARY)
markers = np.uint8(markers)
dist_transform = cv.distanceTransform(255 - markers, cv.DIST_L2, 5)
combined = cv.subtract(dist_transform, grad)
image_rgb = cv.cvtColor(cv.imread('test1.png'), cv.COLOR_BGR2RGB)
markers = np.int32(markers)
markers[grad == 0] = 0
markers += 1
cv.watershed(image_rgb, markers)
markers = np.where(markers == -1, 255, markers)
markers = np.uint8(markers)
output = np.zeros_like(image_rgb)
output[markers == 255] = [0, 0, 255]
output[markers == 1] = [18, 0, 230]
output[markers == 0] = [255, 255, 255]
cv.imshow('Segmentation Result', output)
cv.waitKey(0)
cv.destroyAllWindows()