我编写了以下代码,我使用加载按钮加载图像,然后使用绘图按钮在图像上绘制不同的矩形并将它们保存到文本文件中。
我在我的图片上制作了3个按钮。
1.load(它在GUI上加载图像) 2.Draw(通过按下它,用户可以在图像上绘制可拖动的矩形。 3.Save(使用此按钮,用户可以保存文本文件中的所有矩形)。
加载
function loadButton_Callback(hObject, eventdata, handles)
% hObject handle to loadButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
I=imread('http://ichef.bbci.co.uk/corporate2/images/width/live/p0/0l/3r/p00l3rnt.jpg/624');
imshow(I);
rectangles=cell(1,1);
count=0;
handles.rectangles=rectangles;
handles.count=count;
guidata(hObject,handles);
绘图
function drawButton_Callback(hObject, eventdata, handles)
% hObject handle to drawButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rectangles=handles.rectangles;
count=handles.count;
count=count+1;
h=imrect;
rectangles{count,1}=h;
handles.count=count;
handles.rectangles=rectangles;
guidata(hObject,handles);
保存
function saveButton_Callback(hObject, eventdata, handles)
% hObject handle to saveButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rectangles=handles.rectangles;
for i=1:length(rectangles)
dlmwrite('P:\bla.txt',rectangles{i}.getPosition,'-append','delimiter',' ','newline','pc');
end
以上代码适用于以下问题。如果我删除一个矩形,则出现以下错误?
**Invalid or deleted object**.
答案 0 :(得分:1)
在保存之前,您应该检查矩形是否是有效的句柄对象(即未删除):
function saveButton_Callback(hObject, eventdata, handles)
rectangles=handles.rectangles;
delete('P:\bla.txt');
fclose(fopen('P:\bla.txt', 'w')); % To be able to append
for k=1:length(rectangles)
if isvalid(rectangles{k})
dlmwrite( ...
'P:\bla.txt', rectangles{k}.getPosition, ...
'-append', ...
'delimiter', ' ', ...
'newline', 'pc' ...
);
end;
end;
与此问题无关,但有一天可能会节省你数小时的拔毛:不要使用i
作为变量,因为它是MATLAB中的虚构单位。