基於連通分量標記的自動裁剪 (MATLAB實現)


在數字影像處理中,**基於連通分量標記的自動裁剪**是一種裁剪技術,它利用標記的連通分量來確定影像中的不同區域。然後,透過提取每個連通分量的周圍區域來自動裁剪影像。

基於連通分量標記的自動裁剪的主要優勢在於,它允許分離和提取影像中感興趣的各個區域。

演算法

執行基於連通分量標記的自動裁剪的分步過程如下所示

步驟 1 - 必要時處理影像。此步驟可能包括應用濾波器、對比度調整、RGB 到灰度轉換等。

步驟 2 - 建立二值影像。這是透過使用閾值操作完成的。在二值影像中,影像中感興趣的區域表示為前景。

步驟 3 - 對二值影像執行連通分量標記。

步驟 4 - 透過分析標記的連通分量來查詢感興趣的屬性,例如面積、邊界框等。在 MATLAB 中,此操作可以使用“regionprops()”函式執行。

步驟 5 - 根據特定條件選擇要裁剪的所需連通分量。

步驟 6 - 使用 MATLAB 中的“imcrop()”函式對每個選定的分量執行裁剪。

步驟 7 - 使用 MATLAB 中的“imshow()”函式顯示裁剪後的影像。

現在,讓我們藉助 MATLAB 程式來了解這種基於連通分量標記的影像自動裁剪。

示例

% MATLAB program to demonstrate auto cropping based on labeling the connected components
% Call imread() function to read the input image
img = imread('https://tutorialspoint.tw/assets/questions/media/14304-1687425323.jpg');
% Convert the input image to grayscale
grayimg = rgb2gray(img);
% Create a binary image using a threshold
% Set the threshold value as per need
threshold = 0.35;
binaryimg = imbinarize(grayimg, threshold);
% Perform connected component labeling
labeledimg = bwlabel(binaryimg);
% Extract the properties of connected components
prop = regionprops(labeledimg, 'BoundingBox');
% Select and crop each connected component
for i = 1 : numel(prop)
   boundingbox = prop(i).BoundingBox;
   croppedimg = imcrop(img, boundingbox);
   % Display the cropped image
   imshow(croppedimg); title('Cropped Image');
end

結論

在這個 MATLAB 程式中,我們呼叫“imread”函式讀取輸入影像。然後,使用“rgb2gray”函式處理輸入影像以將其轉換為灰度影像。接下來,我們呼叫“imbinarize”函式使用閾值建立灰度影像的二值影像。然後,我們呼叫“bwlabel”函式執行連通分量標記。之後,我們使用“regionprops”函式查詢連通分量的屬性。在這個示例程式中,我們提取了分量的邊界框。接下來,我們執行“for”迴圈來處理每個連通分量,並使用“imcrop”函式從原始影像中裁剪該區域。最後,我們呼叫“imshow”函式顯示裁剪後的影像。

更新於:2023年7月18日

瀏覽量:76

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.