# Matlab 基于机器视觉的硬币自动分类算法设计

liuxingrui4p 分享于 2015-02-16

（一）LDA算法 LDA的全称是Linear Discriminant Analysis（线性判别分析），是一种supervised learning。有些资料上也称为是 Fisher’s Linear Discriminant，因

``````1.硬币识别代码：
[filename,pathname]=uigetfile({'*.jpg';'*.gif'},'选择图片');
str=[pathname filename];
thresh=graythresh(im);                 %自动选择最优阈值
BW=im2bw(im,thresh);                %对图像进行二值化
BW=1-BW;                          %反色
I=BW;
Idil=imdilate(I,ones(3,3));              %3乘3元素膨胀去除内部噪声
Idil = bwareaopen(Idil,1500);           %忽略小于1500像素的噪声
[L,num]=bwlabel(Idil,8);
Num=0;
inMax=0;
for k=1:num;
[y x]=find(L==k);
nSize=length(y);
if (nSize>4200)                       %由区域生长发统计出数据4200
Num=Num+1;                      %一元个数
end
end
hsv = rgb2hsv(im);
h = hsv(:,:,1);                        %提取1通道的
h=histeq(h);                         %增强对比度，均衡直方图
bw = ~im2bw(h,0.1);                  %photoshop模拟，自选阈值，略过分割
bw= bwareaopen(bw,1000);
Iw=bw;
Idilw=imdilate(Iw,ones(12,12));         %12乘12元素膨胀阀
Idilw = bwareaopen(Idilw,1000);
[L,numa]=bwlabel(Idilw,8);            %numa是5角个数
numb = num - Num -numa;
Num                              %壹圆硬币数量
numa                              %伍角硬币数量
numb                              %壹角

2.区域生长算法：
[filename,pathname]=uigetfile({'*.jpg';'*.gif'},'选择图片');
str=[pathname filename];
thresh=graythresh(im);
BW=im2bw(im,thresh);
BW=1-BW;
I=BW;
I=imdilate(I,ones(3,3));
I = bwareaopen(I,1500);
imshow(I);
if isinteger(I)
I=im2double(I);
end
figure,imshow(I);,title('ORGimage')
[M,N]=size(I);
[y,x]=getpts;
x1=round(x);
y1=round(y);
seed=I(x1,y1);
J=zeros(M,N);
J(x1,y1)=1;
sum=seed;
suit=1;
count=1;
threshold=0.15;
while count>0
s=0;
count=0;
for i=1:M;
for j=1:N;
if J(i,j)==1
if (i-1)>0 & (i+1)<(M+1) & (j-1)>0 & (j+1)<(N+1)
for u=-1:1
for v=-1:1
if J(i+u,j+v)==0 & abs(I(i+u,j+v)-seed)<=threshold & 1/(1+1/15*abs(I(i+u,j+v)-seed))>0.8
J(i+u,j+v)=1;
count=count+1;
s=s+I(i+u,j+v);
end
end
end
end
end
end
end
suit=suit+count;
sum=sum+s;
seed=sum/suit;
end
figure,
imshow(J);                           %鼠标确定图像初始点
Idil=imdilate(J,ones(3,3));
Idil = bwareaopen(Idil,1500);
imshow(Idil);
[L,num]=bwlabel(Idil,8);
[y x]=find(L==1);
nSize=length(y);
nSize                               %nSize为所选连通域像素数目

3.GUI代码
function varargout = untitled(varargin)
% UNTITLED M-file for untitled.fig
%      UNTITLED, by itself, creates a new UNTITLED or raises the existing
%      singleton*.
%
%      H = UNTITLED returns the handle to a new UNTITLED or the handle to
%      the existing singleton*.
%
%      UNTITLED('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in UNTITLED.M with the given input arguments.
%
%      UNTITLED('Property','Value',...) creates a new UNTITLED or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before untitled_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to untitled_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one % instance to run (singleton)".
%

% Edit the above text to modify the response to help untitled

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
'gui_Singleton',  gui_Singleton, ...
'gui_OpeningFcn', @untitled_OpeningFcn, ...
'gui_OutputFcn',  @untitled_OutputFcn, ...
'gui_LayoutFcn',  [] , ...
'gui_Callback',   []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before untitled is made visible.
function untitled_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to untitled (see VARARGIN)

% Choose default command line output for untitled
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes untitled wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = untitled_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global Num;
global numa;
global numb;
[filename,pathname]=uigetfile({'*.jpg';'*.gif'},'选择图片');
str=[pathname filename];
axes(handles.axes1);
imshow(im);

thresh=graythresh(im);                 %自动选择最优阈值
BW=im2bw(im,thresh);                %对图像进行二值化
BW=1-BW;                          %反色
I=BW;
Idil=imdilate(I,ones(3,3));              %3乘3元素膨胀去除内部噪声
Idil = bwareaopen(Idil,1500);           %忽略小于1500像素的噪声
[L,num]=bwlabel(Idil,8);
Num=0;
inMax=0;
for k=1:num;
[y x]=find(L==k);
nSize=length(y);
if (nSize>4200)                       %由区域生长发统计出数据4200
Num=Num+1;                      %一元个数
end
end
hsv = rgb2hsv(im);
h = hsv(:,:,1);                        %提取1通道的
h=histeq(h);                         %增强对比度，均衡直方图
bw = ~im2bw(h,0.1);                  %photoshop模拟，自选阈值，略过分割
bw= bwareaopen(bw,1000);
Iw=bw;
Idilw=imdilate(Iw,ones(12,12));         %12乘12元素膨胀阀
Idilw = bwareaopen(Idilw,1000);
[L,numa]=bwlabel(Idilw,8);            %numa是5角个数
numb = num - Num -numa;
Num                              %壹圆硬币数量
numa                              %伍角硬币数量
numb                              %壹角
set(handles.edit1,'string',Num);
set(handles.edit2,'string',numa);
set(handles.edit3,'string',numb);
money=Num + numa * 0.5 + numb * 0.1;
set(handles.edit4,'string',money);

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double

% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserve
d - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

function edit4_Callback(hObject, eventdata, handles)
% hObject    handle to edit4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit4 as text
%        str2double(get(hObject,'String')) returns contents of edit4 as a double

% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
clear
close(gcf)
``````

HSV提取颜色信息，在程序中会做优化

UI效果

K-近邻算法的思想如下：首先，计算新样本与训练样本之间的距离，找到距离最近的K 个邻居；然后，根据这些邻居所属的类别来判定新样本的类别，如果它们都属于

×
• 登录
• 注册

×