gpt4 book ai didi

matlab - 旋转的 polyshape 对象的宽度和高度 - Matlab

转载 作者:行者123 更新时间:2023-12-04 15:31:12 24 4
gpt4 key购买 nike

基于此question我正在尝试计算对象的宽度和高度。我通过将检查的对象转换为 polyshape 并旋转来做到这一点。如何提取旋转后的 polyshape 对象的宽度和高度?有没有办法使用 regionprop 来做到这一点,它会更有效吗?

代码:

clc;
clear;
close all;

Image = rgb2gray(imread('pillsetc.png'));
BW = imbinarize(Image);
BW = imfill(BW,'holes');
BW = bwareaopen(BW, 100);
[B,L] = bwboundaries(BW,'noholes');

imshow(Image);
hold on;

k=3;
stat = regionprops(BW,'Centroid','Orientation','MajorAxisLength');
b = B{k};
yBoundary = b(:,2);
xBoundary = b(:,1);
centroidObject = stat(k).Centroid;
xCentre = centroidObject(:,2);
yCentre = centroidObject(:,1);
plot(yCentre, xCentre, 'r*')

orientationDegree = stat(k).Orientation
hlen = stat(k).MajorAxisLength/2;
cosOrient = cosd(stat(k).Orientation);
sinOrient = sind(stat(k).Orientation);
xcoords = xCentre + hlen * [cosOrient -cosOrient];
ycoords = yCentre + hlen * [-sinOrient sinOrient];

plot(yBoundary, xBoundary, 'r', 'linewidth', 3);
pgon = polyshape(yBoundary, xBoundary);
polyRot = rotate(pgon,(90+orientationDegree),centroidObject);
plot(polyRot);

[xlim,ylim] = boundingbox(polyRot);
Height = xlim(2) - xlim(1);
Width = ylim(2) - ylim(1);

最佳答案

我会使用最小 Feret 直径计算返回的角度来旋转多边形。通常,这个旋转的盒子是面积最小的盒子(异常(exception)似乎很少见)。 “方向”特征是根据最佳拟合椭圆计算的,不一定会产生小框。

除了旋转整个对象多边形之外,您还可以只旋转凸包,它通常包含较少的点,因此效率更高。 Feret 计算已经使用了凸包,因此从 regionprops 请求它不会产生额外成本。

这是执行我所描述的代码:

Image = rgb2gray(imread('pillsetc.png'));
BW = imbinarize(Image);
BW = imfill(BW,'holes');
BW = bwareaopen(BW, 100);

stat = regionprops(BW,'ConvexHull','MinFeretProperties');

% Compute Feret diameter perpendicular to the minimum diameter
for ii=1:numel(stat)
phi = stat(ii).MinFeretAngle; % in degrees
p = stat(ii).ConvexHull * [cosd(phi),-sind(phi); sind(phi),cosd(phi)];
minRect = max(p) - min(p); % this is the size (width and height) of the minimal bounding box
stat(ii).MinPerpFeretDiameter = minRect(2); % add height to the measurement structure
end

注意上面代码中minRect的第一个值是对象的宽度(最小边界框的最小边),相当于stat(ii).MinFeretDiameter。这两个值并不相同,因为它们的计算方式不同,但它们非常接近。 minRect 的第二个值保存为“MinPerpFeretDiameter”,是高度(或者更确切地说是最小边界框的最长边)。

关于matlab - 旋转的 polyshape 对象的宽度和高度 - Matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61246205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com