matlab在圖像中畫長方形(框)
function [state,result]=draw_rect(data,pointAll,windSize,showOrNot)
% 函數調用:[state,result]=draw_rect(data,pointAll,windSize,showOrNot)
% 函數功能:在圖像畫個長方形框
% 函數輸入:data為原始的大圖,可為灰度圖,可為彩色圖
% pointAll 框的左上角在大圖中的坐標(每行代表一個坐標),
% 注意:在圖中的坐標系為第一列為y,第二列為x(很奇怪的)
% windSize 框的大小 windSize=[112,92] 分別表示長寬
% showOrNot 是否要顯示,默認為顯示出來
% 函數輸出:state -- 表示程序結果狀態
% result - 結果圖像數據
% 函數歷史: v0.0 @2013-01-27 created by Aborn
if nargin < 4
showOrNot = 1;
end
rgb = [255 255 0]; % 邊框顏色
lineSize = 3; % 邊框大小,取1,2,3
windSize(1,1)=windSize(1,1);
windSize(1,2) = windSize(1,2);
if windSize(1,1) > size(data,1) ||...
windSize(1,2) > size(data,2)
state = -1; % 說明窗口太大,圖像太小,沒必要獲取
disp('the window size is larger then image...');
return;
end
result = data;
if size(data,3) == 3
for k=1:3
for i=1:size(pointAll,1) %畫邊框順序為:上右下左的原則
result(pointAll(i,1),pointAll(i,2):pointAll(i,2)+windSize(i,1),k) = rgb(1,k);
result(pointAll(i,1):pointAll(i,1)+windSize(i,2),pointAll(i,2)+windSize(i,1),k) = rgb(1,k);
result(pointAll(i,1)+windSize(i,2),pointAll(i,2):pointAll(i,2)+windSize(i,1),k) = rgb(1,k);
result(pointAll(i,1):pointAll(i,1)+windSize(i,2),pointAll(i,2),k) = rgb(1,k);
if lineSize == 2 || lineSize == 3
result(pointAll(i,1)+1,pointAll(i,2):pointAll(i,2)+windSize(i,1),k) = rgb(1,k);
result(pointAll(i,1):pointAll(i,1)+windSize(i,2),pointAll(i,2)+windSize(i,1)-1,k) = rgb(1,k);
result(pointAll(i,1)+windSize(i,2)-1,pointAll(i,2):pointAll(i,2)+windSize(i,1),k) = rgb(1,k);
result(pointAll(i,1):pointAll(i,1)+windSize(i,2),pointAll(i,2)-1,k) = rgb(1,k);
if lineSize == 3
result(pointAll(i,1)-1,pointAll(i,2):pointAll(i,2)+windSize(i,1),k) = rgb(1,k);
result(pointAll(i,1):pointAll(i,1)+windSize(i,2),pointAll(i,2)+windSize(i,1)+1,k) = rgb(1,k);
result(pointAll(i,1)+windSize(i,2)+1,pointAll(i,2):pointAll(i,2)+windSize(i,1),k) = rgb(1,k);
result(pointAll(i,1):pointAll(i,1)+windSize(i,2),pointAll(i,2)+1,k) = rgb(1,k);
end
end
end
end
end
state = 1;
if showOrNot == 1
figure;
imshow(result);
end
在main函數中調用如下:
% main.m
clc;
clear;
close all;
data = imread('man_1.jpg');
pointAll = [5,20];
windSize = [100,30];
[state,results]=draw_rect(data,pointAll,windSize);
return;
原圖像為:
結果圖像為:
特別注意:圖像中顯示的坐標系和我們平時用的不一樣!!!