机器视觉实验三 工件尺寸和面积测量

【实验目的】

1.掌握工业零件尺寸和面积测量原理
2.掌握利用Matlab进行编程实现工业零件尺寸和面积测量的方法
3.掌握复杂机器视觉软件系统的设计方法

【实验内容】

1.利用Matlab对标准工业零件图像和自建工业零件图像进行尺寸测量
2.利用Matlab对标准工业零件图像和自建工业零件图像进行面积测量

【实验要求】

1.写出实现工业零件尺寸和面积测量的Matlab源代码
2.对测量结果进行统计和误差分析

实验程序

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

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

% Last Modified by GUIDE v2.5 16-May-2011 21:00:46

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Area_OpeningFcn, ...
                   'gui_OutputFcn',  @Area_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 Area is made visible.
function Area_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 Area (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = Area_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) 

%设置全局变量,可以在另外的函数中使用它们
global im;
global l1
global l2
%选择图片路径
 [filename,pathname]=...
     uigetfile({'*.jpg';'*.bmp';'*.tif';'*.png';'*.JPG'},'图片选择');
 
%合成路径+文件名
str=[pathname,filename];

%没有选择任何文件,报错对话框
  L=length(filename);
  if L<5
      errordlg('You do not choose any image','Notice');
      return;
  end;
test=filename(1,L-3:L);
  if test=='.jpg'|test=='.bmp'|test=='.tif'|test=='.png'|test=='.JPG'
        %读取图片
        im=imread(str);
        %关键,指定axes1为当前显示区域
        axes(handles.axes1);
        %显示图片
        imshow(im);
        [m,n]=size(im);
        inter_x = m*0.6;
        inter_y = n*0.071;
        text(inter_x, inter_y, [sprintf('%1f'),'原图像'],...
       'Color','g','FontSize',10,'FontWeight','bold');

  else 
          warndlg('format wrong','warn');%格式错误,警告
          return;
  end;
prompt={'输入参照物序号:','输入参照物面积:'};%设置提示字符串
               name='参数设置';%设置标题
               numlines=1;%指定输入数据的行数
               defAns={'1','283.5287'};%设定默认值
               Resize='on';%设定对话框尺寸可调节
              a=inputdlg(prompt,name,numlines,defAns,'on');%创建输入对话框
        l2=str2num(a{1});%获取对话框中的第一个参数
        l1=str2num(a{2});%获取对话框中的第二个参数
 
 
  % --- 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 l1
global l2
global im
global P
str=get(hObject,'string');
axes(handles.axes2);
hd=rgb2gray(im);%灰度化,被灰度化的图像必须是rgb的
ad=imadjust(hd,stretchlim(hd),[]); %图像增强
x=graythresh(ad);%计算图像的最佳阈值
J=im2bw(hd,x);%图像二值化
P=medfilt2(J,[5,5]);%对二值化图像进行中值滤波[5,5]
[L, num] = bwlabel(P, 8);%8连通域的标记

STATS=regionprops(L, 'all');
for i=1:num
    area(i)=STATS(i).Area ; %计算各区域的像素点。
end ;
M1=area
for i=1:num
        M=M1*(l1/area(l2));
end;
imshow(L);

%鼠标点击事件
for i=1:num
ginput(1);%鼠标点击图片得到坐标值
[x,y]=ginput(1);
x=floor(x);%将得到的坐标值转换成整数
y=floor(y);
s=L(y,x);
 if s==l2
    text(x,y, [sprintf('%1.3f',M(s)),'mm2'],...
       'Color','r','FontSize',10,'FontWeight','bold');% 参照物的显示面积为红色
 else  
    text(x,y, [sprintf('%1.3f_%d',M(s),s)],...
       'Color','b','FontSize',10,'FontWeight','bold');% 被测工件显示的面积为蓝色
end;
end;
[fn,pn,fid]=uiputfile('.txt','Save selected a txt-file');%创建txt文件。其中fn是lilename ,pn是pathname, fid是 
fid=fopen(fn,'w');%打开文件
fprintf(fid,'%gmm2_',M);%向txt文件中写入数据
%fid=fopen('面积保存 …….txt','w');%写入文件路径,可以设置弹出对话框
%[p,q]=size(M);
 %for i=1:1:p
%    for j=1:1:q
%       if j==p
%         fprintf(fid,'%gmm2_',M(i,j));
 %     else
%        fprintf(fid,'%gmm2_',M(i,j));
%       end;
%    end;
% end;
fclose(fid);%关闭文件


% --- 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)
global I
I=getimage(gcf); %获取坐标系中的图像文件数据
imwrite(I,'myphoto.jpg') %保存图像为文件
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
new_f_handle=figure('visible','off');
new_axes=copyobj(handles.axes1,new_f_handle); %axes1是GUI界面绘图的坐标系
set(new_axes,'units','default','position','default');
[filename,pathname fileindex]=uiputfile({'*.jpg';'*.bmp';'*.png'},'save picture as');
if ~filename
    return
else
    file=strcat(pathname,filename);
    switch fileindex %根据不同的选择保存为不同的类型
        case 1
            print(new_f_handle,'-djpeg',file);
        case 2
            print(new_f_handle,'-dbmp',file);
        case 3
            print(new_f_handle,'-dpng',file);
    end;
end;
delete(new_f_handle);

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

实验结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

本人能力有限,解释尚不清楚明了,如遇任何问题,大家可留言或私信。本程序为实验老师提供源程序,供大家学习使用。
本文希望对大家有帮助,当然上文若有不妥之处,欢迎指正。
分享决定高度,学习拉开差距
  • 8
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲁棒最小二乘支持向量机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值