Java教程

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

本文主要是介绍机器视觉实验三 工件尺寸和面积测量,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

【实验目的】

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);

实验结果

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

本人能力有限,解释尚不清楚明了,如遇任何问题,大家可留言或私信。本程序为实验老师提供源程序,供大家学习使用。

本文希望对大家有帮助,当然上文若有不妥之处,欢迎指正。

分享决定高度,学习拉开差距

这篇关于机器视觉实验三 工件尺寸和面积测量的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!