如何使用fill_holes函数填充分割区域?
我想要跟踪分割区域的灰度变化情况,为什么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 个回答
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)