如何获得物体的高度和宽度?

时间:2015-08-12 15:57:29

标签: matlab image-processing

我想计算单个物体的高度和宽度,但我得到0值。

这是一个由我正在查看的对象组成的图像:

enter image description here

我尝试了以下代码:

clear all;
close all;
clc;
%% start
filename = 'untitled.png'; 
I = imread(filename);
info = imfinfo(filename);
thres = graythresh(I);
I2 = ~(im2bw(I, thres));
cmp = bwconncomp(I2);
S = regionprops(cmp, {'BoundingBox'});
bbox = vertcat(S.BoundingBox);
x = bbox(:,3);
y = bbox(:,4);
res = info.ResolutionUnit;
resX = info.XResolution;
resY = info.YResolution;
if strcmp(res, 'Inch')
lebar = 2.54 * x / resX;
tinggi = 2.54 * y / resY;
else
lebar = x / resX;
tinggi = y / resY;
end
fprintf('X Resolution = %.2f %s\n', resX, res);
fprintf('Y Resolution = %.2f %s\n', resY, res);
disp('Size of Object:');
fprintf('Width = %.2f cm\n', lebar);
fprintf('Height = %.2f cm\n', tinggi);

另外如何删除图像中的矩形?

1 个答案:

答案 0 :(得分:0)

更正后的代码

clear all;
close all;
clc;
%% start
filename = 'untitled.png'; 
I = imread(filename);
info = imfinfo(filename);
thres = graythresh(I);
I2 = im2bw(I, thres);
cmp = bwconncomp(I2);
S = regionprops(cmp, {'BoundingBox'});
bbox = vertcat(S.BoundingBox);
x = bbox(:,3);
y = bbox(:,4);
res = info.ResolutionUnit;
resX = info.XResolution;
resY = info.YResolution;
if strcmp(res, 'Inch')
lebar = 2.54 * x / resX;
tinggi = 2.54 * y / resY;
else
lebar = x / resX;
tinggi = y / resY;
end
fprintf('X Resolution = %.4f %s\n', resX, res);
fprintf('Y Resolution = %.4f %s\n', resY, res);
disp('Size of Object:');
fprintf('Width = %.4f cm\n', lebar);
fprintf('Height = %.4f cm\n', tinggi);
%% end