2011-11-15 15:54:49 a_liao1116 阅读数 251

匹配和平衡:例如 ((()()));

不平衡:)();

不匹配:());

检测算法提示:从左到右扫描一个合法的字符串,保证任何时候所遇到的右圆括号不会比左圆括号多。

 

 代码示例:

bool isBalanceOrMatch(char* arr, int n)
{
	int leftC = 0;
	int rightC = 0;

	for (int i=0; i<n; i++)
	{
		char c = arr[i];
		switch(c)
		{
		case '(':
			leftC++;
			break;
		case ')':
			rightC++;
		    break;
		default:
		    break;
		}
		if (rightC > leftC)
		{
			return false;
		}
	}
	return true;
}


 

2019-02-02 15:26:53 qq_40311281 阅读数 2109

实现所给硬币图像中的硬币检测及计数

要求完成功能:自行查找、阅读有关的采用Hough变换来检测图像中圆的资料,设计实现所给图像中圆形的检测,要求检测出图像中硬币个数以及各个硬币的直径。

本题难度系数:★★★★

GUI界面设计参考:MATLAB学习笔记(十一)——MATLAB图形用户界面设计

https://www.cnblogs.com/BlueMountain-HaggenDazs/p/4307777.html

我采用了霍夫变换对所给图形进行了检测和统计个数:

原图如下:

检测后的效果:

全部matlab代码如下:

Hough.m文件:

function varargout = Hough(varargin)
% HOUGH MATLAB code for Hough.fig
%      HOUGH, by itself, creates a new HOUGH or raises the existing
%      singleton*.
%
%      H = HOUGH returns the handle to a new HOUGH or the handle to
%      the existing singleton*.
%
%      HOUGH('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in HOUGH.M with the given input arguments.
%
%      HOUGH('Property','Value',...) creates a new HOUGH or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Hough_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Hough_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 Hough
% Last Modified by GUIDE v2.5 10-Jan-2019 20:43:12
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Hough_OpeningFcn, ...
                   'gui_OutputFcn',  @Hough_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 Hough is made visible.
function Hough_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 Hough (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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


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


% --- 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 img
[filename, pathname]= ...
    uigetfile({'*.*';'*.bmp';'*.tif';'*.png';'*.jpg'},'select picture');
str= [pathname filename];
img= imread(str);
axes(handles.axes1);
imshow(img);

% --- 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 img;
global Gray;
 img=imresize(img,0.5);
[m,n,l] = size(img);
if l == 3
    Gray = rgb2gray(img);    %如果为彩色图 则转化为灰度图
else
    Gray=img;
end
axes(handles.axes1);
imshow(Gray);

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


% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global Gray;
global BW1;
BW1=im2bw(Gray,graythresh(Gray));   %转化为二值图像
axes(handles.axes2);
imshow(BW1)


% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global BW1;
BW1=imopen(BW1,strel('disk',3));  %转化为二值图像
axes(handles.axes2);
imshow(BW1)


% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global BW1;
BW1=imfill(~BW1,'holes');  %填充图像空洞   
axes(handles.axes2);
imshow(BW1)


% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%sobel算子边缘检测
global BW1;
BW1 = edge(BW1,'sobel');  
axes(handles.axes2);
imshow(BW1)


% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton9 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global BW1;
global para;
%hough检测
step_r = str2num(get(handles.edit1, 'String'));
step_angle = str2num(get(handles.edit2, 'String'));
minr =str2num(get(handles.edit3, 'String'));
maxr = str2num(get(handles.edit4, 'String')); 
thresh = str2num(get(handles.edit5, 'String'));

[Hough_Space,Hough_Circle,para] = hough_circle(BW1,step_r,step_angle,minr,maxr,thresh);  
axes(handles.axes2);
imshow(Hough_Circle);


% --- Executes on button press in pushbutton10.
function pushbutton10_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton10 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global para;
global circleParaXYR;
circleParaXYR=para;  
%通过位置求圆心和半径
[r,c]=size(circleParaXYR);
for i=1:r
    a='handles.edit';
    b=5+i;
    c=[a num2str(b)];
    d=[a num2str(5+r+1)];
  set(eval(c),'string',['(' num2str(floor(circleParaXYR(i,1))) ',' num2str(floor(circleParaXYR(i,2))) ')', num2str(2*floor(circleParaXYR(i,3)))]);
  set(eval(d),'string',num2str(r));
end
 

% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton11 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%标出圆  
global img;
global circleParaXYR;
axes(handles.axes2);
imshow(img);
hold on;  
 plot(circleParaXYR(:,2), circleParaXYR(:,1), 'r+');  
 for k = 1 : size(circleParaXYR, 1)  
  t=0:0.01*pi:2*pi;  
  x=cos(t).*circleParaXYR(k,3)+circleParaXYR(k,2);y=sin(t).*circleParaXYR(k,3)+circleParaXYR(k,1);  
  plot(x,y,'r-');  
 end  



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



function edit5_Callback(hObject, eventdata, handles)
% hObject    handle to edit5 (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 edit5 as text
%        str2double(get(hObject,'String')) returns contents of edit5 as a double


% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit5 (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 edit6_Callback(hObject, eventdata, handles)
% hObject    handle to edit6 (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 edit6 as text
%        str2double(get(hObject,'String')) returns contents of edit6 as a double


% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit6 (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 edit7_Callback(hObject, eventdata, handles)
% hObject    handle to edit7 (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 edit7 as text
%        str2double(get(hObject,'String')) returns contents of edit7 as a double


% --- Executes during object creation, after setting all properties.
function edit7_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit7 (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 edit8_Callback(hObject, eventdata, handles)
% hObject    handle to edit8 (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 edit8 as text
%        str2double(get(hObject,'String')) returns contents of edit8 as a double


% --- Executes during object creation, after setting all properties.
function edit8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit8 (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 edit9_Callback(hObject, eventdata, handles)
% hObject    handle to edit9 (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 edit9 as text
%        str2double(get(hObject,'String')) returns contents of edit9 as a double


% --- Executes during object creation, after setting all properties.
function edit9_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit9 (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 edit10_Callback(hObject, eventdata, handles)
% hObject    handle to edit10 (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 edit10 as text
%        str2double(get(hObject,'String')) returns contents of edit10 as a double


% --- Executes during object creation, after setting all properties.
function edit10_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit10 (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 edit11_Callback(hObject, eventdata, handles)
% hObject    handle to edit11 (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 edit11 as text
%        str2double(get(hObject,'String')) returns contents of edit11 as a double


% --- Executes during object creation, after setting all properties.
function edit11_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit11 (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 edit12_Callback(hObject, eventdata, handles)
% hObject    handle to edit12 (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 edit12 as text
%        str2double(get(hObject,'String')) returns contents of edit12 as a double


% --- Executes during object creation, after setting all properties.
function edit12_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit12 (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 m_file_Callback(hObject, eventdata, handles)
% hObject    handle to m_file (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function m_file_save_Callback(hObject, eventdata, handles)
% hObject    handle to m_file_save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%保存文件
[FileName,PathName] = uiputfile({'*.jpg','JPEG(*.jpg)';
                                 '*.bmp','Bitmap(*.bmp)';
                                 '*.gif','GIF(*.gif)';
                                 '*.*',  'All Files (*.*)'},'Save Picture','Untitled');
if FileName==0
    return;
else
    h=getframe(handles.axes2);
    imwrite(h.cdata,[PathName,FileName]);
    warndlg('保存成功','保存成功');
end

hough_circle.m文件:

function [hough_space,hough_circle,para] = hough_circle(BW,step_r,step_angle,r_min,r_max,p)  
  
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
% input  
% BW:二值图像;  
% step_r:检测的圆半径步长  
% step_angle:角度步长,单位为弧度  
% r_min:最小圆半径  
% r_max:最大圆半径  
% p:阈值,0,1之间的数 通过调此值可以得到图中圆的圆心和半径  
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
% output  
% hough_space:参数空间,h(a,b,r)表示圆心在(a,b)半径为r的圆上的点数  
% hough_circl:二值图像,检测到的圆  
% para:检测到的圆的圆心、半径  
  
circleParaXYR=[];  
para=[];  
  
[m,n] = size(BW);  
size_r = round((r_max-r_min)/step_r)+1;%四舍五入  
size_angle = round(2*pi/step_angle);  
  
hough_space = zeros(m,n,size_r);  
  
[rows,cols] = find(BW);%查找非零元素的行列坐标  
ecount = size(rows);%非零坐标的个数  
  
% Hough变换  
% 将图像空间(x,y)对应到参数空间(a,b,r)  
  
% a = x-r*cos(angle)  
% b = y-r*sin(angle)  
  
for i=1:ecount  
    for r=1:size_r %半径步长数  
        for k=1:size_angle %按一定弧度把圆几等分  
            a = round(rows(i)-(r_min+(r-1)*step_r)*cos(k*step_angle));  
            b = round(cols(i)-(r_min+(r-1)*step_r)*sin(k*step_angle));  
            if(a>0&a<=m&b>0&b<=n)  
            hough_space(a,b,r) = hough_space(a,b,r)+1;%h(a,b,r)的坐标,圆心和半径  
            end  
        end  
    end  
end  
  
  
% 搜索超过阈值的聚集点。对于多个圆的检测,阈值要设的小一点!通过调此值,可以求出所有圆的圆心和半径  
max_para = max(max(max(hough_space)));%返回值就是这个矩阵的最大值  
index = find(hough_space>=max_para*p);%一个矩阵中,想找到其中大于max_para*p数的位置  
length = size(index);%符合阈值的个数  
hough_circle = false(m,n);  
%hough_circle = zeros(m,n);  
%通过位置求半径和圆心。  
for i=1:ecount  
    for k=1:length  
        par3 = floor(index(k)/(m*n))+1;  
        par2 = floor((index(k)-(par3-1)*(m*n))/m)+1;  
        par1 = index(k)-(par3-1)*(m*n)-(par2-1)*m;  
        if((rows(i)-par1)^2+(cols(i)-par2)^2<(r_min+(par3-1)*step_r)^2+5&...  
                (rows(i)-par1)^2+(cols(i)-par2)^2>(r_min+(par3-1)*step_r)^2-5)  
              hough_circle(rows(i),cols(i)) = true;   %检测的圆  
        end  
    end  
end                 
  
% 从超过峰值阈值中得到  
for k=1:length  
    par3 = floor(index(k)/(m*n))+1;%取整  
    par2 = floor((index(k)-(par3-1)*(m*n))/m)+1;  
    par1 = index(k)-(par3-1)*(m*n)-(par2-1)*m;  
    circleParaXYR = [circleParaXYR;par1,par2,par3];  
    hough_circle(par1,par2)= true; %这时得到好多圆心和半径,不同的圆的圆心处聚集好多点,这是因为所给的圆不是标准的圆  
    %fprintf(1,'test1:Center %d %d \n',par1,par2);  
end  
  
%集中在各个圆的圆心处的点取平均,得到针对每个圆的精确圆心和半径!  
while size(circleParaXYR,1) >= 1  
    num=1;  
    XYR=[];  
    temp1=circleParaXYR(1,1);  
    temp2=circleParaXYR(1,2);  
    temp3=circleParaXYR(1,3);  
    c1=temp1;  
    c2=temp2;  
    c3=temp3;  
    temp3= r_min+(temp3-1)*step_r;  
   if size(circleParaXYR,1)>1       
     for k=2:size(circleParaXYR,1)  
      if (circleParaXYR(k,1)-temp1)^2+(circleParaXYR(k,2)-temp2)^2 > temp3^2  
         XYR=[XYR;circleParaXYR(k,1),circleParaXYR(k,2),circleParaXYR(k,3)];  %保存剩下圆的圆心和半径位置  
      else    
      c1=c1+circleParaXYR(k,1);  
      c2=c2+circleParaXYR(k,2);  
      c3=c3+circleParaXYR(k,3);  
      num=num+1;  
      end   
    end  
   end   
      %fprintf(1,'sum %d %d radius %d\n',c1,c2,r_min+(c3-1)*step_r);  
      c1=round(c1/num);  
      c2=round(c2/num);  
      c3=round(c3/num);  
      c3=r_min+(c3-1)*step_r;  
      %fprintf(1,'num=%d\n',num)  
      %fprintf(1,'Center %d %d radius %d\n',c1,c2,c3);     
      para=[para;c1,c2,c3]; %保存各个圆的圆心和半径的值  
      circleParaXYR=XYR;  
end 

以上完整源码仅供参考,此次任务小组合作完成,所以博主对以上代码一些部分不是很了解,谢谢合作。

2020-01-16 15:55:09 cold___play 阅读数 27

栈的应用

  1. 栈是嵌套调用机制的实现基础

  2. 使用栈以非递归方式实现递归算法

在这里插入图片描述

判断表达式中圆括号是否匹配

在这里插入图片描述

package pers.zhang.stack;

/**
 * @author zhang
 * @date 2020/1/16 - 14:42
 *
 * 栈应用:括号匹配
 */
public class Exp_bracket {
    //判断expstr表达式中的圆括号是否匹配,若匹配,返回空串,否则返回错误信息
    public static String isValid(String expstr){
        SeqStack<String> stack = new SeqStack<String>(expstr.length());  //顺序栈

        for (int i = 0; i < expstr.length(); i++){
            char ch = expstr.charAt(i);
            switch(ch){
                case '(':
                    stack.push(ch + "");//左括号入栈
                    break;
                case ')':
                    if (stack.isEmpty() || !stack.pop().equals("("))  //遇见右括号时,出栈
                        return "期望(";//判断出栈字符是否为左括号
            }
        }
        return (stack.isEmpty()) ? "" : "期望)";           //返回空串表示没有错误
    }

    public static void main(String args[])
    {
        String expstr = "((1+2)*3+4)";
        System.out.println(expstr + "  " + isValid(expstr));
    }
}

/*
程序多次运行时,若expstr分别表示不同的表达式字符串,运行结果如下:
((1+2)*3+4) 
((1+2)*3+4  期望)
((1+2)*3+4))(  期望(
*/

使用栈计算表达式值

在这里插入图片描述
在这里插入图片描述
1.将中缀表达式转换为后缀表达式
在这里插入图片描述
2.后缀表达式求值
在这里插入图片描述```java
package pers.zhang.stack;

/**

  • @author zhang

  • @date 2020/1/16 - 14:52

  • 栈应用:表达式求值
    */
    public class Expression {

    //返回expstr的后缀表达式
    public static String toPostfix(String expstr){
    SeqStack stack = new SeqStack(expstr.length()); //创建运算符栈,顺序栈
    String postfix = “”;//记载后缀表达式
    int i = 0;
    while (i < expstr.length())
    {
    char ch = expstr.charAt(i);
    switch (ch){
    case ‘+’: //遇到+、-运算符,与栈顶元素比较
    case ‘-’:
    while (!stack.isEmpty() && !stack.get().equals("("))
    postfix += stack.pop();
    stack.push(ch + “”); //当前运算符入栈
    i++;
    break;
    case '’: //遇到、/ 运算符
    case ‘/’:
    while (!stack.isEmpty() && (stack.get().equals("*") || stack.get().equals("/")))
    postfix += stack.pop();
    stack.push(ch+"");
    i++;
    break;
    case ‘(’:
    stack.push(ch + “”); //遇到左括号,入栈
    i++;
    break;
    case ‘)’:
    String out = stack.pop(); //遇到右括号,出栈,若栈空返回null
    while (out!=null && !out.equals("(")){ //判断出栈字符是否为左括号
    postfix += out;
    out = stack.pop();
    }
    i++; break;
    default:
    while (i<expstr.length() && ch>=‘0’ && ch<=‘9’){ //遇到数字时,加入到后缀表达式
    postfix += ch;
    i++;
    if (i < expstr.length())
    ch = expstr.charAt(i);
    }
    postfix += " "; //添加空格作为数值之间的分隔符
    }
    }
    while (!stack.isEmpty())
    postfix += stack.pop();
    return postfix;
    }

    //计算后缀表达式的值
    public static int value(String postfix){
    LinkedStack stack = new LinkedStack(); //创建操作数栈,链式栈
    int i = 0, result = 0;
    while (i < postfix.length()){ //逐个检查后缀表达式中的字符
    char ch = postfix.charAt(i);
    if (ch >= ‘0’ && ch <= ‘9’){ //遇到数字字符
    result = 0;
    while (ch != ’ '){ //字符串转化为数值
    result = result * 10 + Integer.parseInt(ch + “”);
    i++;
    ch = postfix.charAt(i);
    }
    i++;
    stack.push(new Integer(result)); //操作数入栈
    }else{
    int y = stack.pop().intValue(); //出栈两个操作数
    int x = stack.pop().intValue();
    switch (ch){ //根据运算符分别计算
    case ‘+’:
    result = x + y;
    break;
    case ‘-’:
    result = x - y;
    break;
    case ‘*’:
    result = x * y;
    break;
    case ‘/’:
    result = x / y;
    break; //整除,除数为0时将抛出异常
    }
    stack.push(new Integer(result)); //运算结果入栈
    i++;
    }
    }
    return stack.pop().intValue(); //返回运算结果
    }

    public static void main(String args[]){
    String expstr="121+10*(53-49+20)/((35-25)2+10)+11";
    String postfix = toPostfix(expstr);
    System.out.println("expstr= " + expstr);
    System.out.println("postfix= " + postfix);
    System.out.println("value= " + value(postfix));
    }
    }
    /

    程序运行结果如下:
    expstr= 121+10*(53-49+20)/((35-25)*2+10)+11
    postfix= 121 10 53 49 -20 +*35 25 -2 *10 +/+11 +
    value= 140

expstr= 121+10*(53-49+20)/((35-25)*2+10)+11/0
postfix= 121 10 53 49 -20 +*35 25 -2 *10 +/+11 0 /+
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Expression.value(Expression.java:79)
at Expression.main(Expression.java:93)

*/

2018-03-30 21:34:25 zhulinzhulinlin 阅读数 444

在直线检测的基础上理解了霍夫变换,圆检测也是利用霍夫变换的原理。
在直角坐标系中圆的方程为:
(xa)2+(yb)2=r2(x-a)^2+(y-b)^2=r^2
极坐标系方程:x=a+rcosθx=a+rcos\theta y=b+rsinθy=b+rsin\theta
将极坐标方程转化为参数空间的方程:
a=xrcosθa=x-rcos\theta b=yrsinθb=y-rsin\theta
在此我们假定已知要找寻的圆的纵坐标 Y,则将上述三维参数空间转化为二维参数空间,方程3为:
a=xrcosθa =x-rcos\thetar=(yY)/sinθr =(y-Y)/sin\theta
对于上述已经转成二维参数空间,则可以利用直线检测的方法进行检测

步骤

1.进行边缘检测,使用的边缘检测算法不能丢失重要的边缘信息
2.确定二维累加矩阵的精度,即a和r的取值范围,可由要提取的圆特征决定。
3.遍历图像中像素值不为0的点(不同的边缘算法边缘像素值可能为0可能为255),再遍历可能的θ\theta取值,带入方程3进行计算,再对相应的累加矩阵进行加1操作。
4.寻找局域最大值得出要找的的圆。

2018-10-19 19:39:46 LYKymy 阅读数 266

理论

  • 在线检测情况下,线由两个参数(r,θ)定义。 在圆圈情况下,我们需要三个参数来定义圆:
  • 其中(xcenter,ycenter)定义中心位置(绿点),r是半径,这允许我们完全定义一个圆,如下所示:
  • 为了提高效率,OpenCV实现了一种比标准Hough变换稍微复杂的检测方法:Hough梯度方法,它由两个主要阶段组成。 第一阶段涉及边缘检测并找到可能的圆心,第二阶段找到每个候选中心的最佳半径。

代码

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void help()
{
    cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
            "Usage:\n"
            "./houghcircles <image_name>, Default is ../data/board.jpg\n" << endl;
}
int main(int argc, char** argv)
{
    cv::CommandLineParser parser(argc, argv,
        "{help h ||}{@image|../data/board.jpg|}"
    );
    if (parser.has("help"))
    {
        help();
        return 0;
    }
    string filename = parser.get<string>("@image");
    if (filename.empty())
    {
        help();
        cout << "no image_name provided" << endl;
        return -1;
    }
    Mat img = imread(filename, 0);
    if(img.empty())
    {
        help();
        cout << "can not open " << filename << endl;
        return -1;
    }
    Mat cimg;
    medianBlur(img, img, 5);
    cvtColor(img, cimg, COLOR_GRAY2BGR);
    vector<Vec3f> circles;
    HoughCircles(img, circles, HOUGH_GRADIENT, 1, 10,
                 100, 30, 1, 30 // change the last two parameters
                                // (min_radius & max_radius) to detect larger circles
                 );
    for( size_t i = 0; i < circles.size(); i++ )
    {
        Vec3i c = circles[i];
        circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, LINE_AA);
        circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, LINE_AA);
    }
    imshow("detected circles", cimg);
    waitKey();
    return 0;
}

解释

(1)src_gray:输入图像(灰度)。

(2)circles:存储3个值的集合的向量:每个检测到的圆的xc,yc,r。

(3)HOUGH_GRADIENT:定义检测方法。 目前,这是OpenCV中唯一可用的。

(4)dp = 1:分辨率的反比。

(5)min_dist = src_gray.rows / 8:检测到的中心之间的最小距离。

(6)param_1 = 200:内部Canny边缘检测器的上限阈值。

(7)param_2 = 100 *:中心检测的阈值。

(8)min_radius = 0:要检测的最小半径。 如果未知,则默认为零。

(9)max_radius = 0:要检测的最大半径。 如果未知,则默认为零。

  • 加载图像
  • 将其转换为灰度:
  • 应用高斯模糊以减少噪音并避免假圆检测:
  • 继续应用霍夫圆变换:
  • 绘制检测到的圆圈:
  • 显示检测到的圆圈:
  • 等待用户退出程序

效果

没有更多推荐了,返回首页