我一直在拍摄图像并在上面绘制轮廓。我需要在三个类别中计算像素的数量和它们的位置(在MATLAB中)
我尝试在MATLAB中使用inpolygon。它可以计算内部和外部的像素,但不计算边界上的像素。在边界上,它只计算直接通过小网格中心的那些。我还需要计算轮廓通过小网格的四个边缘中的任何一个的像素。
请帮助。 我提供了以下代码。
%Polygon Plotting
clc;clear all;close all;
I = imread('cameraman.tif');
I = imresize(I,[100 100]);
I = double(I(:,:,1));
imagesc(I,[0 255]);colormap(gray);
axis([1 size(I,1) 1 size(I,2)]);
[BW xi yi] = roipoly(); %select your own coordinates.
X=xi;
Y=yi;
hold on;
contour(BW,'r');
hold off;
xa = 1 : size(I,2);
ya = 1 : size(I,1);
[x,y] = meshgrid(xa,ya);
[in on] = inpolygon(x,y,X,Y);
count1 = sum(sum(in));
count2 = size(I,1)*size(I,2) - count1;
count3 = sum(sum(on));
%count1 = inside the polygon and on boundary
%count2 = outside the polygon
%count3 = on the boundary only
inside = zeros(count1,2);
outside = zeros(count2,2);
onthecurve = zeros(count3,2);
l=1;m=1;n=1;
for i = 1:size(I,1)
for j = 1:size(I,2)
if in(i,j)==1
inside(l,1)=i;
inside(l,2)=j;
l=l+1;
end
if in(i,j)==0
outside(m,1)= i;
outside(m,2)= j;
m = m+1;
end
if on(i,j)==1
onthecurve(n,1)= i;
onthecurve(n,2)= j;
n = n+1;
end
end
end
figure,
plot(inside(:,1),inside(:,2),'+g');
axis([1 size(I,1) 1 size(I,2)]);
hold on
plot(outside(:,1),outside(:,2),'+r');
hold on
plot(onthecurve(:,1),onthecurve(:,2),'+b');
hold off
如果图像显示不正确,请参阅链接: 1。Original Image & Contour 2。Green - inside, Red - outside
可以看出,轮廓上的点未标记为蓝色。实际上,count3几乎总是给出输出0.因此inpolygon在计算边界上的点时效率不高。
如何修改代码以便计算这些像素? 谢谢大家。
答案 0 :(得分:1)
您可以使用edge
检测黑白(BW
)图像(本例中为输入多边形)的边框。
%% Polygon Plotting
I = imread('cameraman.tif');
imshow(I);
inBW = roipoly(); % Select your own coordinates.
%% Make BW matrices
outBW = ~inBW; % Find 'out'
edBW = edge(inBW); % Find the 'edge'
inBW(edBW) = 0; % Remove edge from 'in'
outBW(edBW) = 0; % Remove edge from 'out'
%% Show result
imshow(double(cat(3, inBW, edBW, outBW)))
同时显示所有像素都包含在3组中:
prod(size(I)) - sum(sum(inBW + outBW + edBW))
应该变为零。
希望它有所帮助。