I have an image which contains a coin image. Shape of the coin may be rectangle, square, circle, oval and etc. I want to draw a rectangle over the开发者_Go百科 coin and segment the coin from it's background. I can't give x or y values of the rectangle, since coin may be in anywhere in the image. Does anyone know how to do this?
My answer below assumes that you have already identified the coin and you have a cleaned image (binary would be nice) that you can work with.
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
Now we need the extents of the image in order to know the size of the bounding rectangle. Since the array is non-zero where there's an image and zero elsewhere, the following gives the length of the sides.
sideX=sum(sum(img,1)>0);
sideY=sum(sum(img,2)>0);
Find the centroid of the image using kmeans
.
[indX,indY]=ind2sub(size(img),find(img(:)>0));
[~,centroid]=kmeans([indX,indY],1);
Now finally overlay the rectangle on top of the image.
imagesc(img);colormap(gray);hold on
rectangle('Position',([centroid,sideX,sideY]-[sideX,sideY,0,0]/2),'EdgeColor','w');hold off
Result:
If you have a noisy image (i.e., it's not uniformly zero outside the image, then you'd have to set a threshold to find the bounding box)
Start by reading the MathWorks advice on pattern recognition. Exactly how you solve the problem depends on many things, for example
what else is in the image apart from a coin?
are all the coins the same colour or different colours?
do you have a training set of images that with identified coin locations?
精彩评论