搜尋
首頁後端開發Python教學在 Python 中使用標準化剪切 (NCut) 進行無監督影像分割的指南

A Guide to Unsupervised Image Segmentation using Normalized Cuts (NCut) in Python

介紹

影像分割在理解和分析視覺資料方面起著至關重要的作用,而歸一化剪切(NCut)是一種廣泛使用的基於圖的分割方法。在本文中,我們將探索如何使用 Microsoft Research 的資料集在 Python 中應用 NCut 進行無監督影像分割,並專注於使用超像素來提高分割品質。
資料集概述
用於此任務的資料集可以從以下連結下載:MSRC 物件類別影像資料庫。此資料集包含原始影像及其語義分割為九個物件類別(由以“_GT”結尾的圖像檔案表示)。這些圖像被分組為主題子集,其中檔案名稱中的第一個數字指的是類別子集。此資料集非常適合試驗分割任務。

問題陳述

我們使用 NCut 演算法對資料集中的影像進行影像分割。像素級分割的計算成本很高,而且通常有雜訊。為了克服這個問題,我們使用 SLIC(簡單線性迭代聚類)來產生超像素,它將相似的像素分組並減少問題的大小。為了評估分割的準確性,可以使用不同的指標(例如,並集交集、SSIM、蘭德指數)。

執行

1。安裝所需的庫
我們使用 skimage 進行影像處理,使用 numpy 進行數值計算,使用 matplotlib 進行視覺化。

pip install numpy matplotlib
pip install scikit-image==0.24.0
**2. Load and Preprocess the Dataset**

下載並擷取資料集後,載入圖片和地面實況分割:

wget http://download.microsoft.com/download/A/1/1/A116CD80-5B79-407E-B5CE-3D5C6ED8B0D5/msrc_objcategimagedatabase_v1.zip -O msrc_objcategimagedatabase_v1.zip
unzip msrc_objcategimagedatabase_v1.zip
rm msrc_objcategimagedatabase_v1.zip

現在我們準備開始編碼了。

from skimage import io, segmentation, color, measure
from skimage import graph
import numpy as np
import matplotlib.pyplot as plt

# Load the image and its ground truth
image = io.imread('/content/MSRC_ObjCategImageDatabase_v1/1_16_s.bmp')
ground_truth = io.imread('/content/MSRC_ObjCategImageDatabase_v1/1_16_s_GT.bmp')

# show images side by side
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(image)
ax[0].set_title('Image')
ax[1].imshow(ground_truth)
ax[1].set_title('Ground Truth')
plt.show()

3。使用 SLIC 產生超像素並建立區域鄰接圖

在應用 NCut 之前,我們使用 SLIC 演算法來計算超像素。使用產生的超像素,我們基於平均顏色相似度建立區域鄰接圖(RAG):

from skimage.util import img_as_ubyte, img_as_float, img_as_uint, img_as_float64

compactness=30 
n_segments=100 
labels = segmentation.slic(image, compactness=compactness, n_segments=n_segments, enforce_connectivity=True)
image_with_boundaries = segmentation.mark_boundaries(image, labels, color=(0, 0, 0))
image_with_boundaries = img_as_ubyte(image_with_boundaries)
pixel_labels = color.label2rgb(labels, image_with_boundaries, kind='avg', bg_label=0

緊湊性控制形成超像素時像素的顏色相似度和空間接近度之間的平衡。它決定了保持超像素緊湊(在空間方面更接近)與確保它們按顏色更均勻分組的重視程度。
較高的值:較高的緊湊度值會導致演算法優先創建空間緊湊且大小均勻的超像素,而較少關注顏色相似性。這可能會導致超像素對邊緣或顏色漸變不太敏感。
較低的值:較低的緊湊度值允許超像素在空間尺寸上變化更大,以便更準確地考慮顏色差異。這通常會導致超像素更緊密地遵循影像中物件的邊界。

n_segments 控制 SLIC 演算法嘗試在影像中產生的超像素(或段)的數量。本質上,它設定了分割的分辨率。
較高的值:較高的 n_segments 值會建立更多的超像素,這表示每個超像素會更小,分割會更細緻。當圖像具有複雜紋理或小物體時,這非常有用。
較低的值:較低的 n_segments 值會產生更少、更大的超像素。當您想要對影像進行粗分割,將較大的區域分組為單一超像素時,這非常有用。

4。應用標準化剪切 (NCut) 並可視化結果

# using the labels found with the superpixeled image
# compute the Region Adjacency Graph using mean colors
g = graph.rag_mean_color(image, labels, mode='similarity')

# perform Normalized Graph cut on the Region Adjacency Graph
labels2 = graph.cut_normalized(labels, g)
segmented_image = color.label2rgb(labels2, image, kind='avg')
f, axarr = plt.subplots(nrows=1, ncols=4, figsize=(25, 20))

axarr[0].imshow(image)
axarr[0].set_title("Original")

#plot boundaries
axarr[1].imshow(image_with_boundaries)
axarr[1].set_title("Superpixels Boundaries")

#plot labels
axarr[2].imshow(pixel_labels)
axarr[2].set_title('Superpixel Labels')

#compute segmentation
axarr[3].imshow(segmented_image)
axarr[3].set_title('Segmented image (normalized cut)')

5。評估指標
無監督分割的關鍵挑戰是 NCut 不知道影像中類別的確切數量。 NCut 找到的分段數量可能超過實際的地面實況區域數量。因此,我們需要強大的指標來評估細分品質。

並集交集 (IoU) 是一種廣泛使用的評估分割任務的指標,特別是在電腦視覺領域。它測量預測分割區域和地面真實區域之間的重疊。具體來說,IoU 計算預測分割和真實資料之間的重疊面積與其併集面積的比率。

結構相似性指數 (SSIM) 是一種用於透過比較兩個影像的亮度、對比度和結構來評估影像感知品質的指標。

To apply these metrics we need that the prediction and the ground truth image have the same labels. To compute the labels we compute a mask on the ground and on the prediction assign an ID to each color found on the image
Segmentation using NCut however may find more regions than ground truth, this will lower the accuracy.

def compute_mask(image):
  color_dict = {}

  # Get the shape of the image
  height,width,_ = image.shape

  # Create an empty array for labels
  labels = np.zeros((height,width),dtype=int)
  id=0
  # Loop over each pixel
  for i in range(height):
      for j in range(width):
          # Get the color of the pixel
          color = tuple(image[i,j])
          # Check if it is in the dictionary
          if color in color_dict:
              # Assign the label from the dictionary
              labels[i,j] = color_dict[color]
          else:
              color_dict[color]=id
              labels[i,j] = id
              id+=1

  return(labels)
def show_img(prediction, groundtruth):
  f, axarr = plt.subplots(nrows=1, ncols=2, figsize=(15, 10))

  axarr[0].imshow(groundtruth)
  axarr[0].set_title("groundtruth")
  axarr[1].imshow(prediction)
  axarr[1].set_title(f"prediction")
prediction_mask = compute_mask(segmented_image)
groundtruth_mask = compute_mask(ground_truth)

#usign the original image as baseline to convert from labels to color
prediction_img = color.label2rgb(prediction_mask, image, kind='avg', bg_label=0)
groundtruth_img = color.label2rgb(groundtruth_mask, image, kind='avg', bg_label=0)

show_img(prediction_img, groundtruth_img)

Now we compute the accuracy scores

from sklearn.metrics import jaccard_score
from skimage.metrics import structural_similarity as ssim

ssim_score = ssim(prediction_img, groundtruth_img, channel_axis=2)
print(f"SSIM SCORE: {ssim_score}")

jac = jaccard_score(y_true=np.asarray(groundtruth_mask).flatten(),
                        y_pred=np.asarray(prediction_mask).flatten(),
                        average = None)

# compute mean IoU score across all classes
mean_iou = np.mean(jac)
print(f"Mean IoU: {mean_iou}")

Conclusion

Normalized Cuts is a powerful method for unsupervised image segmentation, but it comes with challenges such as over-segmentation and tuning parameters. By incorporating superpixels and evaluating the performance using appropriate metrics, NCut can effectively segment complex images. The IoU and Rand Index metrics provide meaningful insights into the quality of segmentation, though further refinement is needed to handle multi-class scenarios effectively.
Finally, a complete example is available in my notebook here.

以上是在 Python 中使用標準化剪切 (NCut) 進行無監督影像分割的指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用Python查找文本文件的ZIPF分佈如何使用Python查找文本文件的ZIPF分佈Mar 05, 2025 am 09:58 AM

本教程演示如何使用Python處理Zipf定律這一統計概念,並展示Python在處理該定律時讀取和排序大型文本文件的效率。 您可能想知道Zipf分佈這個術語是什麼意思。要理解這個術語,我們首先需要定義Zipf定律。別擔心,我會盡量簡化說明。 Zipf定律 Zipf定律簡單來說就是:在一個大型自然語言語料庫中,最頻繁出現的詞的出現頻率大約是第二頻繁詞的兩倍,是第三頻繁詞的三倍,是第四頻繁詞的四倍,以此類推。 讓我們來看一個例子。如果您查看美國英語的Brown語料庫,您會注意到最頻繁出現的詞是“th

如何在Python中下載文件如何在Python中下載文件Mar 01, 2025 am 10:03 AM

Python 提供多種從互聯網下載文件的方法,可以使用 urllib 包或 requests 庫通過 HTTP 進行下載。本教程將介紹如何使用這些庫通過 Python 從 URL 下載文件。 requests 庫 requests 是 Python 中最流行的庫之一。它允許發送 HTTP/1.1 請求,無需手動將查詢字符串添加到 URL 或對 POST 數據進行表單編碼。 requests 庫可以執行許多功能,包括: 添加表單數據 添加多部分文件 訪問 Python 的響應數據 發出請求 首

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

python中的圖像過濾python中的圖像過濾Mar 03, 2025 am 09:44 AM

處理嘈雜的圖像是一個常見的問題,尤其是手機或低分辨率攝像頭照片。 本教程使用OpenCV探索Python中的圖像過濾技術來解決此問題。 圖像過濾:功能強大的工具圖像過濾器

如何使用Python使用PDF文檔如何使用Python使用PDF文檔Mar 02, 2025 am 09:54 AM

PDF 文件因其跨平台兼容性而廣受歡迎,內容和佈局在不同操作系統、閱讀設備和軟件上保持一致。然而,與 Python 處理純文本文件不同,PDF 文件是二進製文件,結構更複雜,包含字體、顏色和圖像等元素。 幸運的是,借助 Python 的外部模塊,處理 PDF 文件並非難事。本文將使用 PyPDF2 模塊演示如何打開 PDF 文件、打印頁面和提取文本。關於 PDF 文件的創建和編輯,請參考我的另一篇教程。 準備工作 核心在於使用外部模塊 PyPDF2。首先,使用 pip 安裝它: pip 是 P

如何在django應用程序中使用redis緩存如何在django應用程序中使用redis緩存Mar 02, 2025 am 10:10 AM

本教程演示瞭如何利用Redis緩存以提高Python應用程序的性能,特別是在Django框架內。 我們將介紹REDIS安裝,Django配置和性能比較,以突出顯示BENE

引入自然語言工具包(NLTK)引入自然語言工具包(NLTK)Mar 01, 2025 am 10:05 AM

自然語言處理(NLP)是人類語言的自動或半自動處理。 NLP與語言學密切相關,並與認知科學,心理學,生理學和數學的研究有聯繫。在計算機科學

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。