使用MATLAB進行影像邊界提取


在影像中,邊界是指將物件與影像背景或影像內兩個不同區域分隔開的元素。邊界提供了有關影像中存在的物件形狀和結構的資訊。

邊界主要分為以下兩種型別:

內邊界

它是影像中物件的邊界,將其與影像背景隔開。內邊界基本上是物件的輪廓,並提供有關物件形狀的資訊。

因此,透過提取物件的內邊界,我們可以識別和分析影像中物件的形狀、大小和位置。

在MATLAB中,我們可以透過計算原始影像和腐蝕影像之間的差異來提取影像的內邊界,即:

Inner Boundary = Original Image – Eroded Image

其中,腐蝕影像是透過腐蝕收縮原始影像獲得的影像。

外邊界

包圍影像最外圍區域或影像中特定感興趣區域的邊界稱為外邊界。外邊界指定影像中多個物件或整個影像本身的輪廓。

因此,外邊界主要用於執行各種影像處理任務,例如裁剪、更改或移除背景等。

在MATLAB中,可以透過計算膨脹影像和原始影像之間的差異來獲得影像的外邊界,即:

Outer Boundary = Dilated Image – Original Image

其中,膨脹影像是透過膨脹獲得的原始影像的擴充套件版本。

在本文中,我們將學習如何使用MATLAB程式碼提取影像的邊界。以下MATLAB程式演示了影像內邊界和外邊界的提取。

示例

% MATLAB program to extract inner boundary of an image 
% Read the input image
img = imread('https://tutorialspoint.tw/electrical_machines/images/electrical_machines_logo.jpg');
% Convert the input image to grayscale
gray_img = rgb2gray(img);
% Specify the structuring element to perform erosion of image
se = strel('disk', 2);
% Perform erosion of the grayscale image
eroded_img = imerode(gray_img, se);
% Extract the inner boundary by subtracting the eroded image from gray image
inner_boundary = gray_img - eroded_img;
% Display the original image and the inner boundary
subplot(1, 2, 1); imshow(img); title('Original Image');
subplot(1, 2, 2); imshow(inner_boundary); title('Inner Boundary');

輸出

解釋

此MATLAB程式碼演示了影像的內邊界提取。在這個MATLAB程式中,我們使用“imread”函式讀取輸入影像,然後使用“rgb2gray”函式將其轉換為灰度影像。

之後,我們建立一個結構元素“se”來執行影像的腐蝕,為此我們使用“strel”函式。在這種情況下,我們建立的結構元素具有半徑為2的圓盤形狀。接下來,我們使用“imrode”函式執行影像的腐蝕。由於腐蝕,影像內的區域會收縮以消除外邊界。

然後,我們透過從原始影像“gray_img”中減去腐蝕影像“eroded_img”來提取內邊界,並將結果儲存在“inner_boundary”變數中。

最後,我們使用“imshow”函式顯示原始影像和內邊界。

示例

% MATLAB program to extract outer boundary of an image
% Read the input image
img = imread('https://tutorialspoint.tw/electrical_machines/images/electrical_machines_logo.jpg');
% Convert the RGB image to grayscale
gray_img = rgb2gray(img);
% Specify a structuring element to perform dilation of the image
se = strel('disk', 2);
% Perform dilation on the image to expand it
dilated_img = imdilate(gray_img, se);
% Extract the outer boundary by computing the difference between dilated image and original image
outer_boundary = dilated_img - gray_img;
% Display the original image and the outer boundary
subplot(1, 2, 1); imshow(img); title('Original Image');
subplot(1, 2, 2); imshow(outer_boundary); title('Outer Boundary');

輸出

解釋

在這個MATLAB程式中,我們提取了影像的外邊界。為此,我們首先使用“imread”函式讀取影像。然後,我們使用“rgb2gray”函式將輸入影像轉換為灰度影像。接下來,我們定義一個結構元素來對影像執行膨脹。之後,我們使用“imdilate”函式對影像執行膨脹。

接下來,我們透過計算膨脹影像“dilated_img”和原始影像“gray_img”之間的差異來提取外邊界,並將結果儲存在“outer_boundary”變數中。

最後,我們呼叫“imshow”函式來顯示原始影像和外邊界。

結論

這就是我們如何使用MATLAB程式設計輕鬆執行影像邊界提取的方法。MATLAB允許我們提取影像的內邊界和外邊界。要提取內邊界,則執行影像的腐蝕。而要提取外邊界,則執行影像的膨脹。

更新於:2023年8月7日

瀏覽量1K+

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告