Python で正規化カット (NCut) を使用した教師なし画像セグメンテーションのガイド
소개
이미지 분할은 시각적 데이터를 이해하고 분석하는 데 중요한 역할을 하며, 정규화 컷(NCut)은 그래프 기반 분할에 널리 사용되는 방법입니다. 이 기사에서는 슈퍼픽셀을 사용하여 분할 품질을 향상시키는 데 중점을 두고 Microsoft Research의 데이터 세트를 사용하여 Python에서 감독되지 않은 이미지 분할을 위해 NCut을 적용하는 방법을 살펴보겠습니다.
데이터세트 개요
이 작업에 사용되는 데이터 세트는 MSRC 개체 범주 이미지 데이터베이스 링크에서 다운로드할 수 있습니다. 이 데이터세트에는 원본 이미지와 의미론적 분할이 포함되어 있습니다("_GT"로 끝나는 이미지 파일로 표시됨). 이러한 이미지는 주제별 하위 집합으로 그룹화됩니다. 여기서 파일 이름의 첫 번째 숫자는 클래스 하위 집합을 나타냅니다. 이 데이터세트는 세분화 작업을 실험하는 데 적합합니다.
문제 설명
NCut 알고리즘을 사용하여 데이터세트의 이미지에 대해 이미지 분할을 수행합니다. 픽셀 수준에서의 분할은 계산 비용이 많이 들고 종종 노이즈가 발생합니다. 이를 극복하기 위해 SLIC(Simple Linear Iterative Clustering)을 사용하여 유사한 픽셀을 그룹화하고 문제 크기를 줄이는 슈퍼픽셀을 생성합니다. 세분화의 정확성을 평가하기 위해 다양한 측정항목(예: Intersection over Union, SSIM, Rand Index)을 사용할 수 있습니다.
구현
1. 필수 라이브러리 설치
이미지 처리에는 skimage, 수치 계산에는 numpy, 시각화에는 matplotlib를 사용합니다.
pip install numpy matplotlib pip install scikit-image==0.24.0 **2. Load and Preprocess the Dataset**
데이터 세트를 다운로드하고 추출한 후 이미지와 Ground Truth 분할을 로드합니다.
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에서 찾은 세그먼트 수는 실제 지상 진실 영역 수를 초과할 수 있습니다. 따라서 세분화 품질을 평가하기 위해서는 강력한 측정 지표가 필요합니다.
Intersection over Union(IoU)은 특히 컴퓨터 비전에서 분할 작업을 평가하는 데 널리 사용되는 측정항목입니다. 예측된 분할 영역과 실제 영역 간의 중첩을 측정합니다. 구체적으로 IoU는 예측 분할과 Ground Truth 간의 중첩 영역 대 합집합 영역의 비율을 계산합니다.
구조적 유사성 지수(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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











PythonはゲームとGUI開発に優れています。 1)ゲーム開発は、2Dゲームの作成に適した図面、オーディオ、その他の機能を提供し、Pygameを使用します。 2)GUI開発は、TKINTERまたはPYQTを選択できます。 TKINTERはシンプルで使いやすく、PYQTは豊富な機能を備えており、専門能力開発に適しています。

Pythonは学習と使用が簡単ですが、Cはより強力ですが複雑です。 1。Python構文は簡潔で初心者に適しています。動的なタイピングと自動メモリ管理により、使いやすくなりますが、ランタイムエラーを引き起こす可能性があります。 2.Cは、高性能アプリケーションに適した低レベルの制御と高度な機能を提供しますが、学習しきい値が高く、手動メモリとタイプの安全管理が必要です。

限られた時間でPythonの学習効率を最大化するには、PythonのDateTime、時間、およびスケジュールモジュールを使用できます。 1. DateTimeモジュールは、学習時間を記録および計画するために使用されます。 2。時間モジュールは、勉強と休息の時間を設定するのに役立ちます。 3.スケジュールモジュールは、毎週の学習タスクを自動的に配置します。

Pythonは開発効率でCよりも優れていますが、Cは実行パフォーマンスが高くなっています。 1。Pythonの簡潔な構文とリッチライブラリは、開発効率を向上させます。 2.Cのコンピレーションタイプの特性とハードウェア制御により、実行パフォーマンスが向上します。選択を行うときは、プロジェクトのニーズに基づいて開発速度と実行効率を比較検討する必要があります。

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

Pythonは、自動化、スクリプト、およびタスク管理に優れています。 1)自動化:OSやShutilなどの標準ライブラリを介してファイルバックアップが実現されます。 2)スクリプトの書き込み:Psutilライブラリを使用してシステムリソースを監視します。 3)タスク管理:スケジュールライブラリを使用してタスクをスケジュールします。 Pythonの使いやすさと豊富なライブラリサポートにより、これらの分野で優先ツールになります。

Pythonを1日2時間学ぶだけで十分ですか?それはあなたの目標と学習方法に依存します。 1)明確な学習計画を策定し、2)適切な学習リソースと方法を選択します。3)実践的な実践とレビューとレビューと統合を練習および統合し、統合すると、この期間中にPythonの基本的な知識と高度な機能を徐々に習得できます。

PythonとCにはそれぞれ独自の利点があり、選択はプロジェクトの要件に基づいている必要があります。 1)Pythonは、簡潔な構文と動的タイピングのため、迅速な開発とデータ処理に適しています。 2)Cは、静的なタイピングと手動メモリ管理により、高性能およびシステムプログラミングに適しています。
