我做了一個帶有兩個按鈕和軸的應用程式設計器 GUI。第一個(LoadimageButton)正在加載檔案影像,我可以標記點,直到我按下轉義鍵。第二個按鈕是列印點坐標(PositionButton)。
我注意到按下兩個按鈕后,我可以移動軸上的點并更改它們的位置或洗掉它們。問題是,當我按下洗掉(在背景關系選單中)時,按下 PositionButton 后出現此錯誤:
Error using images.roi.Point/get
Invalid or deleted object.
Error in tempDrwPnt1/PositionButtonPushed (line 61)
positions = cell2mat(get(app.pointhandles, 'position'))
Error while evaluating Button PrivateButtonPushedFcn.
洗掉點后如何重繪 app.pointhandles?
代碼:
function LoadimageButtonPushed(app, event)
imshow('peppers.png','Parent',app.ImageAxes);
userStopped = false;
app.pointhandles = gobjects();
while ~userStopped
roi = drawpoint(app.ImageAxes);
if ~isvalid(roi) || isempty(roi.Position)
% End the loop
userStopped = true;
else
% store point object handle
app.pointhandles(end 1) = roi;
end
end
addlistener(roi,'MovingROI',@allevents);
addlistener(roi,'ROIMoved',@allevents);
app.pointhandles(1) = [];
function allevents(src,evt)
evname = evt.EventName;
switch(evname)
case{'MovingROI'}
disp(['ROI moving previous position: ' mat2str(evt.PreviousPosition)]);
disp(['ROI moving current position: ' mat2str(evt.CurrentPosition)]);
case{'ROIMoved'}
disp(['ROI moved previous position: ' mat2str(evt.PreviousPosition)]);
disp(['ROI moved current position: ' mat2str(evt.CurrentPosition)]);
end
end
end
% Button pushed function: PositionButton
function PositionButtonPushed(app, event)
positions = cell2mat(get(app.pointhandles, 'position'))
end
uj5u.com熱心網友回復:
您可以在PositionButtonPushed函式中添加檢查每個pointhandles元素是否有效,如果有效則報告,否則將其洗掉
就像是
function PositionButtonPushed(app, event)
nPts = numel(app.pointhandles);
positions = NaN(nPts,2); % array to hold positions
for iPt = nPts:-1:1 % loop backwards so we can remove elements without issue
if isvalid( app.pointhandles(iPt) )
positions(iPt,:) = get(app.pointhandles(iPt),'position');
else
% No longer valid (been deleted), remove the reference
app.pointhandles(iPt) = [];
% Also remove from the positions output
positions(iPt,:) = [];
end
end
end
我現在沒有可用的兼容 MATLAB 版本來測驗它,但我假設內置函式isvalid適用于Point物件,否則您將不得不添加自己的有效性檢查。或者,您可以try獲取該位置,并else在 a 中執行洗掉(由上面處理) ,但如果您可以檢查特定(已知)問題catch,我通常建議您反對try/ 。catch
我經常使用類似的東西(例如軸),但將無效句柄的清理功能捆綁到它自己的函式中。在這種情況下,它可以讓您在獲取剩余有效點的位置之前添加一個函式呼叫。
我還通過 using 使這更加簡潔arrayfun,但在引擎蓋下它與上述回圈的方法相同:
function PositionButtonPushed(app, event )
app.checkHandleValidity(); % cleanup handles just in case
positions = cell2mat(get(app.pointhandles, 'position'));
end
function checkHandleValidity( app )
bValid = arrayfun( @isvalid, app.pointhandles ); % Check validity
app.pointhandles( ~bValid ) = []; % Remove invalid elements
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412039.html
標籤:
