2014-10-07 131 views
1

我有一個代碼可以檢測圖像中的人臉並將邊界框圍繞圖像放置,如下所示。 enter image description hereMATLAB - 使用黑色圍着邊界框的顏色區域

但是我想更進一步,將邊界框外的區域着色爲黑色,以便只能看到臉部並且背景變黑。 原始代碼..

FDetect = vision.CascadeObjectDetector; 
I = imread('PresidentClinton.jpg'); 

%Returns Bounding Box values based on number of objects 
BB = step(FDetect,I); 

figure, 
imshow(I); hold on 
for i = 1:size(BB,1) 
rectangle('Position',BB(i,:),'LineWidth',5,'LineStyle','-','EdgeColor','r'); 
end 
title('Face Detection'); 
hold off; 

回答

1

這裏是您第一次創建相同的尺寸/類的目標圖像作爲原始圖像,並用黑色填充的簡單方法。那麼你得到的矩形座標,從原始圖像數據分配給目標圖像:

clear 
close all 

A = imread('peppers.png'); 
B = zeros(size(A),class(A)); % //Pre-define target image of identical size and class than original. 

%// You could also use this line: 
%//B = zeros(size(A),'like',A); 


hRect = rectangle('Position',[100 100 200 160],'LineWidth',3); %// Define rectangle 

RectPos = get(hRect, 'Position'); %// Get the coordinates of the rectangle. 

x = RectPos(1):RectPos(1)+RectPos(3); %// Define x- and y-span 
y = RectPos(2):RectPos(2)+RectPos(4); 

B(x,y,:) = A(x,y,:); %// Assign the selected part of the image to B 

figure 
subplot(1,2,1) 
imshow(A) 
subplot(1,2,2) 
imshow(B) 

給予這樣的事情:

enter image description here

當然也有其他的方式,但我認爲這一個是簡單易行的循環實現。

+0

所以這是你以後? – 2014-10-08 21:10:45