6

我想從圖像中提取的橢圓形區域(從圖像中的面部部分的部分)優選地在MATLAB裁剪橢圓:從圖像

enter image description here

例如,在該圖像中,我想提取紅色邊界內的區域。
任何人都可以幫助我嗎?

+0

請詳細說明,舉例,展示圖片等...... –

+0

您是否想手動或自動找到臉? –

+0

橢圓是如何給出的?是用'imellipse'插入的嗎?你會知道它的幾何形狀(位置+主軸和副軸)嗎?你可以在生成的'imellipse'對象上使用'createMask'方法。 –

回答

11

裁剪很容易,所有你需要做的是應用一個適當的面具。訣竅是創建這樣一個面具。

假設A是你的形象,試試這個:

%# Create an ellipse shaped mask 
c = fix(size(A)/2); %# Ellipse center point (y, x) 
r_sq = [76, 100] .^ 2; %# Ellipse radii squared (y-axis, x-axis) 
[X, Y] = meshgrid(1:size(A, 2), 1:size(A, 1)); 
ellipse_mask = (r_sq(2) * (X - c(2)) .^ 2 + ... 
    r_sq(1) * (Y - c(1)) .^ 2 <= prod(r_sq)); 

%# Apply the mask to the image 
A_cropped = bsxfun(@times, A, uint8(ellipse_mask)); 

裁切的圖像將被存儲在A_cropped。 玩中心的座標和半徑的值,直到你得到所需的結果。

編輯:我擴展了RGB圖像的解決方案(如果矩陣A是3-D)。

+0

我試過你的代碼。它給最後一行提供了錯誤:A_cropped(ellipse_mask)= A; ???在賦值A(:) = B中,A和B 中的元素數量必須相同。 – user671805

+0

你說得對。我修好了它。 –

+0

您的代碼現在可以使用。但現在我只是得到一個完全不透明的紅色橢圓,背景爲黑色。 – user671805

2

這是我用來將面裁剪成橢圓形的方法。它使背景透明。

[FileName,PathName] = uigetfile({'*.jpg;*.tif;*.png;*.gif','All Image Files'},'Please Select an Image'); 
image = imread([PathName FileName]); 
imshow(image) %needed to use imellipse 
user_defined_ellipse = imellipse(gca, []); % creates user defined ellipse object. 
wait(user_defined_ellipse);% You need to click twice to continue. 
MASK = double(user_defined_ellipse.createMask()); 
new_image_name = [PathName 'Cropped_Image_' FileName]; 
new_image_name = new_image_name(1:strfind(new_image_name,'.')-1); %removing the .jpg, .tiff, etc 
new_image_name = [new_image_name '.png']; % making the image .png so it can be transparent 
imwrite(image, new_image_name,'png','Alpha',MASK); 
msg = msgbox(['The image was written to ' new_image_name],'New Image Path'); 
waitfor(msg);