我正在尝试从图像中分割出组织斑点。我进行了一些初步的预处理,并获得了以下结果。我担心的是边界上的噪音。如果我使用水平/垂直内核侵 eclipse ,那么我也会在中间释放一些数据。我不确定哪种方法能更好地获得结果,还是应该采用其他方法进行细分。

这是示例图片:

import numpy as np
import os
import matplotlib.pyplot as plt
from skimage import io
from skimage.filters import threshold_mean
from skimage.exposure import adjust_sigmoid, adjust_gamma
from skimage.morphology import opening
from skimage import morphology
import scipy.ndimage as ndi

def create_binary_mask(path_to_file):
    file = io.imread(path_to_file)

    #APPLY FILTERS FOR BETTER THRESHOLD
    img_med = ndi.median_filter(file, size=20) #REDUCE NOISE
    adjusted_gamma = adjust_gamma(img_med, 1.8, 2) #INCREASE GAMMA
    adjusted_sigmoid = adjust_sigmoid(adjusted_gamma, 0.01) #INCREASE CONTRAST

    #DO THE MEAN THRESHOLD
    thresh = threshold_mean(adjusted_sigmoid)
    binary = adjusted_sigmoid > thresh

    #REMOVE SMALL NOISE WITHIN THE IMAGE
    disk = morphology.disk(radius=7)
    opening = morphology.binary_opening(binary, disk)

    fig, axis = plt.subplots(1,4, figsize=(10,10))
    axis[0].imshow(file, cmap='gray')
    axis[0].set_title('Original File')
    axis[1].imshow(adjusted_sigmoid, cmap='gray')
    axis[1].set_title('Adjusted Sigmoid')
    axis[2].imshow(binary, cmap='gray')
    axis[2].set_title('Mean Threshold')
    axis[3].imshow(opening, cmap='gray')
    axis[3].set_title('After opening')
    plt.savefig('results.png')
    plt.show()


path_to_file = "sample_img.png"
create_binary_mask(path_to_file)

python - 如何消除边框上的噪点而不会丢失蒙版中间的数据-LMLPHP

最佳答案

一种简单的方法是对二进制图像执行形态学封闭,以将噪声连接到一个轮廓中。从这里我们可以找到轮廓并使用轮廓区域进行过滤。我们可以通过绘制轮廓来有效地消除边界上的噪点。这是将噪声与背景色一起着色的结果。如果要在面罩上将其删除,则可以使用黑色(0,0,0)对其进行绘画。

import cv2
import numpy as np

# Load image, grayscale, Gaussian blur, adaptive threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,61,5)

# Morph close to connect noise
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=5)

# Filter using contour area and fill in contour to remove noise
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 250000:
        cv2.drawContours(image, [c], -1, (43,43,43), -1)

cv2.imwrite('image.png', image)
cv2.waitKey()

10-07 23:56