close

最小交叉熵閾值法基於將圖像的直方圖模型化為兩個混合的高斯分佈:一個代表前景,另一個代表背景。該方法試圖找到一個閾值,使得分割後的前景和背景的熵之差最小。

以下是如何在Python中使用最小交叉熵閾值進行圖像分割的範例:

 

def minimum_cross_entropy_threshold(image):
    """
    Compute the minimum cross-entropy threshold for an image.
    """
    # Compute histogram
    hist = cv2.calcHist([image], [0], None, [256], [0,256]).flatten()
    hist = hist / hist.sum()  # Normalize to probabilities
    
    # Cumulative distribution
    cdf = np.cumsum(hist)
    
    # Compute cumulative means
    cumulative_means = np.cumsum(hist * np.arange(256))
    
    # Compute global mean
    global_mean = cumulative_means[-1]
    
    # Compute between class variance
    between_class_variance = (global_mean * cdf - cumulative_means) ** 2 / (cdf * (1 - cdf))
    
    # Avoid nan values
    between_class_variance[np.isnan(between_class_variance)] = 0
    
    # Find threshold that maximizes between class variance
    threshold = np.argmax(between_class_variance)
    
    return threshold

# Compute the minimum cross-entropy threshold
min_cross_entropy_thresh = minimum_cross_entropy_threshold(provided_img)

# Apply the threshold to the image
_, min_cross_entropy_img = cv2.threshold(provided_img, min_cross_entropy_thresh, 255, cv2.THRESH_BINARY)

# Display the original and minimum cross-entropy thresholded images
fig, ax = plt.subplots(1, 2, figsize=(10, 5))

ax[0].imshow(provided_img, cmap='gray')
ax[0].set_title('Original Image')
ax[0].axis('off')

ax[1].imshow(min_cross_entropy_img, cmap='gray')
ax[1].set_title('Minimum Cross-Entropy Thresholded Image')
ax[1].axis('off')

plt.tight_layout()
plt.show()

如上所示,左側是您提供的原始圖像,而右側是使用最小交叉熵閾值進行分割的結果。

最小交叉熵閾值法基於計算兩個高斯分佈的混合模型,並尋找使分割後的前景和背景的熵之差最小的閾值。從結果中,您可以看到此方法是如何區分圖像的前景和背景的。

這種方法適用於當圖像的直方圖可以被合理地模型化為兩個混合高斯分佈時。在某些情況下,這種方法可能比其他簡單的閾值法更為有效。

arrow
arrow
    文章標籤
    圖像前處理
    全站熱搜

    Rocky 發表在 痞客邦 留言(0) 人氣()