使用Matlab在对象上绘制一个矩形

时间:2011-04-07 11:54:59

标签: matlab image-processing plot image-segmentation

我有一张包含硬币图像的图像。硬币的形状可以是矩形,正方形,圆形,椭圆形等。我想在硬币上画一个矩形并从它的背景中分割硬币。我无法给出矩形的x或y值,因为硬币可能位于图像的任何位置。有谁知道怎么做?

2 个答案:

答案 0 :(得分:1)

我的答案假设您已经识别出硬币,并且您可以使用清洁图像(二进制文件很好)。

coin=load('penny.mat'); %#load matlab's stock image
img=zeros(256,256);
img(65:192,65:192)=coin.P;%# this is an approximation to the sort of image that I think you have

enter image description here

现在我们需要图像的范围以便知道边界矩形的大小。由于数组非零,其中有图像,其他地方为零,以下给出了边长。

sideX=sum(sum(img,1)>0);
sideY=sum(sum(img,2)>0);

使用kmeans查找图像的质心。

[indX,indY]=ind2sub(size(img),find(img(:)>0));
[~,centroid]=kmeans([indX,indY],1);

现在最后将矩形覆盖在图像的顶部。

imagesc(img);colormap(gray);hold on
rectangle('Position',([centroid,sideX,sideY]-[sideX,sideY,0,0]/2),'EdgeColor','w');hold off

结果:

enter image description here

如果你有一个嘈杂的图像(即它在图像外部不均匀为零,那么你必须设置一个阈值来找到边界框)

答案 1 :(得分:0)

首先阅读MathWorks advice on pattern recognition。究竟如何解决问题取决于很多事情,例如

  • 除了硬币外,图像还有什么?

  • 所有的硬币都是相同的颜色还是不同的颜色?

  • 你有一套具有识别硬币位置的训练图片吗?