如何使用fill_holes函数填充分割区域?

0 投票
1 回答
47 浏览
提问于 2025-04-12 18:53

我想要跟踪分割区域的灰度变化情况,为什么ndi.binary_fill_holes这个函数没有带来太大的变化呢?

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sigma = 3
img_smooth = ndi.gaussian_filter(gray, sigma)
thresh = threshold_otsu(img_smooth)
new = img_smooth > thresh
fill = ndi.binary_fill_holes(new)

fig, ax = plt.subplots(1, 2, figsize=(10,7))
ax[0].imshow(mem, interpolation='none', cmap='gray')
ax[1].imshow(fill, interpolation='none', cmap='gray')
ax[0].set_title('Thresh')
ax[1].set_title('Fill')

原始图像:

1

灰度平滑处理后的图像:

2m 3m

填充后的图像:

4

1 个回答

0

我对scipy不太熟悉。我尝试用opencv的形态学操作来完成这个任务。下面是带有注释的代码,希望能对你有所帮助。

import cv2
import numpy as np

#Read input image and convert to gray
image = cv2.imread('red_ball.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#Apply filter and threshold image.
gray = cv2.GaussianBlur(gray, (11, 11), 0)
ret, thresholded_image = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

#Apply morphological open and close operation to remove noise and close gaps
#Can read more in https://docs.opencv.org/4.x/d9/d61/tutorial_py_morphological_ops.html
kernel = np.ones((7,7),np.uint8)
thresholded_image = cv2.morphologyEx(thresholded_image, cv2.MORPH_CLOSE, kernel,iterations=5)
final_mask = cv2.morphologyEx(thresholded_image, cv2.MORPH_OPEN, kernel,iterations=5)
#Final mask of the segmented balls
cv2.imwrite("final_mask.jpg",final_mask)

#Segmented image using the final mask
segmented_image = cv2.bitwise_and(image, image, mask=final_mask)
cv2.imwrite("segmented_image.jpg",segmented_image)

输出的掩膜: 在这里输入图片描述

分割后的图像: 在这里输入图片描述

撰写回答