MATLAB - 使用黑色为边界框周围的区域着色

时间:2014-10-07 16:33:25

标签: matlab detection bounding-box

我有一个代码可以检测图像中的面部,并在图像周围放置一个边界框,如下所示。enter image description here

但我想更进一步,将边界框外的区域涂成黑色,这样只能看到脸部,背景变黑。 原始代码..

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 个答案:

答案 0 :(得分: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

当然还有其他方法,但我认为这个方法很简单,很容易在循环中实现。