Related
I am working on GUI. I want to store data in extra fields created in handles structure. However, I don't know how to update handles structure properly when callback function ends. Please, give any advice.
My simplified program
Set number of signal (1-10). Each signal has 3 parameters.
Read parameter for selected signal from array created in handles structure
(default are zeros).
Edit parameter, update the array.
GUI
function simple_gui(hObject, h)
h.fig = figure(...
'Units','pix',...
'Position',[50 50 500 400],...
'Visible','default',...
'Name','GUI',...
'NumberTitle','off',...
'Resize','on');
table = {'1' , '2', '3' , '4', '5', '6', '7', '8', '9', '10' };
h.number = uicontrol(...
'Units','characters',...
'Max',10,...
'Min',1,...
'String',table,...
'Style','popupmenu',...
'Value',1,...
'Position',[37.4 28.3846153846154 19.4 1.61538461538462],...
'BackgroundColor',[1 1 1]);
h.edit1 = uicontrol(...
'Units','pix',...
'String','0',...
'Style','edit',...
'Position',[180 280 50 20],...
'BackgroundColor',[1 1 1],...
'FontSize',10);
h.edit2 = uicontrol(...
'Units','pix',...
'String','0',...
'Style','edit',...
'Position',[180 255 50 20],...
'Children',[],...
'FontSize',10);
h.edit3 = uicontrol(...
'Units','pix',...
'String','0',...
'Style','edit',...
'Position',[180 230 50 20],...
'FontSize',10);
Main code:
h.parameter1 = zeros(1,10);
h.parameter2 = zeros(1,10);
h.parameter3 = zeros(1,10);
h.signal_no = 0;
h.number.Callback = {#number_Callback, h};
h.edit1.Callback = {#parameter_change_Callback, h};
h.edit2.Callback = {#parameter_change_Callback, h};
h.edit3.Callback = {#parameter_change_Callback, h};
guidata(h.fig, h);
function number_Callback(hObject,eventdata, h)
h = guidata(hObject);
h.signal_no = hObject.Value;
k = h.signal_no;
h.edit1.String = h.parameter1(k);
h.edit2.String = h.parameter2(k);
h.edit3.String = h.parameter3(k);
guidata(hObject,h);
function parameter_change_Callback(hObject,eventdata, h)
h = guidata(hObject);
k = h.signal_no;
h.parameter1(k) = str2double(h.edit1.String);
h.parameter2(k) = str2double(h.edit2.String);
h.parameter3(k) = str2double(h.edit3.String);
guidata(hObject, h);
In summary:
Call guidata(handleObject, varToStore) (documentation) at the end of GUI callback functions to ensure updates to one modified variable are stored. Here, handleObject is either your figure's handle or a child of it, and varToStore is the updated variable you want stored; it is often a structure.
The syntax for retrieving stored data from a figure or child handle:
handles = guidata(gcbo); % gcbo will get the callback object (instance of handle class).
handles.propToUpdate = handles.propToUpdate+1;
guidata(gcbo,handles); % stores the updated struct
In addition:
You won't see the changes from your popupmenu reflected in your edit boxes in the GUI with the current code because you are assigning the numeric values to a edit handle's String field. You call str2double() when taking values this field, and just need to do the reverse (num2str()) to get the displayable values back in. Here's the updated code with a simplified callback declaration
h.number.Callback = #number_Callback;
function number_Callback(hObject,~)
h = guidata(hObject);
h.signal_no = hObject.Value;
k = h.signal_no;
h.edit1.String = num2str(h.parameter1(k));
h.edit2.String = num2str(h.parameter2(k));
h.edit3.String = num2str(h.parameter3(k));
guidata(hObject,h);
end
I created a small example program to demonstrate my problem (The variable "option1selcted" does not change its value):
classdef radioexample < handle
%radioexample2
% example for radiobuttuns
properties(Hidden)
% all elements of the GUI are properties of the class trechner
formMain; % "The MainWindow"
menuFile; % "The Menu Header"
% buttons
buttonTest
% radio items
radiogroup
radio1
radio2
% statis variable
option1selcted = true;
end
methods(Hidden)
function obj = radioexample
% Constructor Form Main
obj.formMain = figure('position',[400,400,600,260],'Visible','off');
set(obj.formMain,'Name','Rradioexample','NumberTitle','off',...
'MenuBar','none','Resize','Off');
% a menu for exit the program
obj.menuFile.main = uimenu('Label','File');
obj.menuFile.exit = uimenu(obj.menuFile.main,...
'Label','Exit','Callback',{#obj.close_Callback,obj});
% radiobutton to select the mode
obj.radiogroup = uibuttongroup(obj.formMain,...
'Visible','on',...
'Units','pixels',...
'BackGroundColor',[0.8 0.8 0.8],...
'Position',[220 80 100 100]);
%'SelectionChangedFcn',#obj.bselection);
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 1',...
'Position',[10 70 70 20],...
'Callback',#obj.opt1_Callback,...
'HandleVisibility','off');
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 2',...
'Position',[10 50 70 20],...
'Callback',#obj.opt2_Callback,...
'HandleVisibility','off');
obj.buttonTest = uicontrol('Style','pushbutton','String','Print radiostaus intop the Command Window',...
'Position',[40,200,260,60],...
'Callback',{#obj.test_Callback,obj,'test'},'Enable','On');
set(obj.formMain,'Visible','on');
fprintf('programm started');
end
end
methods(Static,Access=private)
function close_Callback(~,~,obj)
% close window
close(obj.f)
end
function opt1_Callback(hObject, evt)
fprintf('switched to radio1 mode\n');
obj.option1selcted = true; %<- does not change the variable?
end
function opt2_Callback(hObject, evt)
fprintf('switched to radio2 mode\n');
%msgbox('switched to radio2 mode','Success');
obj.option1selcted = false; %<- does not change the variable?
end
function test_Callback(~,~,obj,val)
fprintf('the status of the radiobutton is: %d\n', obj.option1selcted);
end
end
methods(Access=public,Hidden)
function disp(obj)
end
end
end
To test the status of the variable "option1selcted" the testbutton writes its status into the matlab command window.
You cannot change values of obj within a static method. Define the callback-functions within a non-static methods-block. You need to add another ~ for the input arguments. I fixed this issue in the callback of the button as well.
Here is the full code:
classdef radioexample < handle
%radioexample2
% example for radiobuttuns
properties(Hidden)
% all elements of the GUI are properties of the class trechner
formMain; % "The MainWindow"
menuFile; % "The Menu Header"
% buttons
buttonTest
% radio items
radiogroup
radio1
radio2
% statis variable
option1selcted = true;
end
methods(Hidden)
function obj = radioexample
% Constructor Form Main
obj.formMain = figure('position',[400,400,600,260],'Visible','off');
set(obj.formMain,'Name','Rradioexample','NumberTitle','off',...
'MenuBar','none','Resize','Off');
% a menu for exit the program
obj.menuFile.main = uimenu('Label','File');
obj.menuFile.exit = uimenu(obj.menuFile.main,...
'Label','Exit','Callback',{#obj.close_Callback,obj});
% radiobutton to select the mode
obj.radiogroup = uibuttongroup(obj.formMain,...
'Visible','on',...
'Units','pixels',...
'BackGroundColor',[0.8 0.8 0.8],...
'Position',[220 80 100 100]);
%'SelectionChangedFcn',#obj.bselection);
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 1',...
'Position',[10 70 70 20],...
'Callback',#obj.opt1_Callback,...
'HandleVisibility','off');
uicontrol(obj.radiogroup,...
'Style',...
'radiobutton',...
'BackGroundColor',[0.8 0.8 0.8],...
'String','Option 2',...
'Position',[10 50 70 20],...
'Callback',#obj.opt2_Callback,...
'HandleVisibility','off');
obj.buttonTest = uicontrol('Style','pushbutton','String','Print radiostaus intop the Command Window',...
'Position',[40,200,260,60],...
'Callback',{#obj.test_Callback,obj,'test'},'Enable','On');
set(obj.formMain,'Visible','on');
fprintf('programm started');
end
function opt1_Callback(~,hObject,evt)
fprintf('switched to radio1 mode\n');
obj.option1selcted = true;
end
function opt2_Callback(~,hObject,evt)
fprintf('switched to radio2 mode\n');
%msgbox('switched to radio2 mode','Success');
obj.option1selcted = false;
end
function test_Callback(~,~,~,obj,val)
fprintf('the status of the radiobutton is: %d\n', obj.option1selcted);
end
end
methods(Static,Access=private)
function close_Callback(~,~,obj)
% close window
close(obj.f)
end
end
methods(Access=public,Hidden)
function disp(obj)
end
end
end
I'm creating a tool for our engineering team to view data coming off our systems in the field. The underlying data isn't critical to it. Basically, it consists of vectors containing Y data at X time.
I'm plotting a series of vectors using subplot. Each plot has the ButtonDownFcn defined to launch a window that allows for deeper analysis. The problem is that when I click on the axes in the deployed application, nothing happens. There are no error messages or anything. When I click on the axes running it in Matlab, it works exactly as expected.
I'm not sure what's going on once the code is deployed that is preventing it from functioning properly. I'm a little lost on where to go. I've included my code and some sample data.
Test Data:
stats = struct('name','Car 54', ...
'date', '11-Aug-2014');
stats.SOC = struct('time', linspace(1,24,100)*3600', ...
'plugdata', [100*ones(20,1); NaN(70,1); (20:4:56)'], ...
'drivedata', [NaN(20,1); (100:-2:60)'; NaN(10,1); (40:-2:20)'; NaN(20,1); (30:-2:16)'; NaN(10,1)], ...
'eptodata', [NaN(41,1); (58:-2:40)'; NaN(11,1); (18:-2:5)'; NaN(13,1); NaN(7,1); NaN(11,1)], ...
'engchargedata', [NaN(69,1); (5:2:30)'; NaN(18,1)], ...
'otherdata', NaN(100,1));
Code:
function [output] = summarytablepopup(stats)
FH = figure('Name','Summary Table Popup', ...
'Units', 'normalized', ...
'Position', [0.05 0.05 0.9 0.8], ...
'Tag', 'sumTablePU', ...
'Toolbar', 'none', ...
'NumberTitle', 'off', ...
'WindowStyle', 'normal', ...
'Resize', 'on', ...
'CloseRequestFcn', #closereq, ...
'MenuBar', 'none', ...
'UserData', {});
movegui(FH,'onscreen')
noStats = numel(stats);
screensize = get(0,'ScreenSize');
mapIMG = imread([pwd '\icons\map.jpg']);
noGraphs = 5;
AH = NaN(noStats,1); % axes handles
TT = NaN(noStats,1); % name text handles
MB = NaN(noStats,1); % map button handles
TH = NaN(ceil(noStats/noGraphs),1); % tab handles
warning('off','all')
TGH = uitabgroup('Parent',FH); % tab group handle
for ii = 1:length(TH)
TH(ii) = uitab('parent',TGH,'title',sprintf('Page %d',ii));
end
warning('on','all')
for ii = 1:noStats
currentPage = ceil(ii/noGraphs);
vehiclename = stats(ii).name;
vehicledate = stats(ii).date;
if isfield(stats(ii),'SOC') && ~isempty(stats(ii).SOC) && isfield(stats(ii).SOC,'time') && ~isempty(stats(ii).SOC.time)
SOC = stats(ii).SOC;
time = SOC.time/3600;
subplot(5,1,mod(ii-1,noGraphs)+1,'Parent',TH(currentPage))
HH = plot(time, SOC.plugdata, 'g-x', ...
time, SOC.eptodata, 'b-x', ...
time, SOC.engchargedata, 'b-x', ...
time, SOC.drivedata, 'r-x', ...
time, SOC.otherdata, 'k-x');
AH(ii) = get(HH(1),'Parent');
set(HH,'Marker','.')
set(HH(3),'Color',[0 0.75 1])
set(HH(3),'MarkerFaceColor',[0 0.75 1])
else
subplot(5,1,mod(ii-1,noGraphs)+1,'Parent',TH(currentPage))
HH = plot([0 12 24],[NaN NaN NaN]);
AH(ii) = get(HH(1),'Parent');
%}
end
pos = get(AH(ii),'Position');
pos(1) = 0.25;
pos(3) = 0.72;
set(AH(ii),'Position',pos)
set(AH(ii),'UserData', ii)
set(AH(ii),'ButtonDownFcn', #divedeep)
set(AH(ii),'YLim',[0 100])
set(AH(ii),'YTick',[0 25 50 75 100])
set(AH(ii),'YTickLabel',{'0','25','50','75','100'})
set(AH(ii),'XLim',[0 24])
set(AH(ii),'XTick',[0 4 8 12 16 20 24])
set(AH(ii),'XTickLabel',{'0000','0400','0800','1200','1600','2000','2400'})
mapHeight = 0.1;
mappos = [0.18 pos(2)+pos(4)/2-mapHeight/2 mapHeight*screensize(4)/screensize(3) mapHeight];
MB(ii) = uicontrol('Parent', TH(currentPage), 'Style', 'pushbutton', ...
'Tag', sprintf('mapButton%d',ii), ...
'String', '', ...
'Units', 'normalized', ...
'Position', mappos, ...
'CData', mapIMG, ...
'Callback', #mapbutton);
if isfield(stats(ii),'location') && ~isempty(stats(ii).location) && isfield(stats(ii).location,'time') && ~isempty(stats(ii).location.time)
set(MB(ii),'Enable','on')
else
set(MB(ii),'Enable','off')
end
textHeight = 0.05;
textpos = [0.01 pos(2)+pos(4)/2-textHeight/2 0.15 textHeight];
TT(ii) = uicontrol('Parent', TH(currentPage), 'Style', 'text', ...
'Tag', sprintf('text%d',ii), ...
'String', vehiclename, ...
'FontSize', 12, ...
'Units', 'normalized', ...
'Position', textpos);
end
uiwait(FH)
function mapbutton(source, event)
tag = get(source,'Tag');
splittag = strsplit(tag,'n');
jj = str2num(splittag{2});
loc = stats(jj).location;
if ~isempty(loc)
len = numel(loc.time);
map = [linspace(1,0,len)', linspace(0,1,len)', zeros(len,1)];
MFH = figure;
MPH = plot(loc.lon, loc.lat, 'r:');
hold on;
MSH = scatter(loc.lon, loc.lat, 50, 'o', 'filled', 'CData', map);
plot_google_map
else
msgbox('No location information available for this vehicle. Really should disable this button.')
end
end
function electric(source, event)
ratio = get(SH,'Value')/100*(0.9-startheight)+0.05;
set(PH, 'Position', [panpos(1) ratio panpos(3) panpos(4)])
end
function divedeep(source, event)
HEDtimeplot([],stats(get(source,'UserData')));
end
function closereq(source,event)
uiresume(source)
delete(source)
end
end
I would like to convert a video file using rgb2gray on the videoframes, thing is i'm not completely sure how.
I have got this script file, playing the video file using a slider:
%-------------------------------------------------------------------
function frametracking()
%# read all frames at once
filename = uigetfile('*.avi');
vid = VideoReader(filename);
numImgs = get(vid, 'NumberOfFrames');
frames = read(vid);
% Make the UI
mx = numImgs-1;
hFig = figure('Menubar','none');
uicontrol('Style','slider', 'Parent',hFig, ...
'Callback',#slider_callback, ...
'Units','pixels', 'Position',[150 0 260 20], ...
'Value',1, 'Min',1, 'Max',mx, 'SliderStep',[1 10]./mx);
pB1 = uicontrol(hFig, 'Position',[150 20 130 20], ...
'Units','pixels', ...
'String','Select file', ...
'Callback',#button1_callback);
pB2 = uicontrol(hFig, 'Position',[280 20 130 20], ...
'Units','pixels', ...
'String','Calibrate', ...
'Callback',#button2_callback);
eT1 = uicontrol(hFig, 'Style','edit',...
'Units','pixels',...
'Position',[490 400 60 20],...
'CallBack',#edit1_callback,...
'String','');
eT2 = uicontrol(hFig, 'Style','edit',...
'Units','pixels',...
'Position',[490 370 60 20],...
'CallBack',#edit2_callback,...
'String','');
eT3 = uicontrol(hFig, 'Style','edit',...
'Units','pixels',...
'Position',[490 370 60 20],...
'CallBack',#edit3_callback,...
'String','');
hAx = axes('Parent',hFig,'units','pixels',...
'Position',[80 80 400 400]);
grayframe = rgb2gray(frames(:,:,:,1));
hMainImg = imshow(grayframe(:,:,:,1), 'Parent',hAx);
%# callback functions
function slider_callback(src,~)
val = round(get(src,'Value')); %# starting index
%# update the thumbnails
for ii = 1 : numel(hMainImg)
set(hMainImg(ii), 'CData',frames(:,:,:,ii+val-1))
drawnow
end
end
function click_callback(src,~)
%# update the main image
% grayframe = rgb2gray(frames(:,:,:,1));
set(hMainImg, 'CData',get(src,'CData'));
drawnow
end
function button1_callback(src,~)
end
end
%-------------------------------------------------------------------
At line 40 i've added: grayframe = rgb2gray(frames(:,:,:,1));, this makes the first frame gray. How do I make this count for all frames? My goal is to track an object in the videoframe, so I want to convert the frames to binary images aswell, and apply a additional filter like edge detection or something similar.
Thanks in advance
for i=1:numImgs
frames(:,:,:,i)=rgb2gray(frames(:,:,:,i));
end
I'd rather get rid of rgb2gray and vectorize it
GRAYframes = uint8(mean(RGBframes,3));
1- construct a VideoReader object
2- read each frame and convert it to grayscale using RGB2GRAY
3- playback the video
clear
clc
obj = VideoReader('xylophone.mp4');
nFrames = obj.NumberOfFrames;
vidHeight = obj.Height;
vidWidth = obj.Width;
mov(1:nFrames) =struct('cdata',zeros(vidHeight,vidWidth,1,'uint8'),...
'colormap',[]);
% Read one frame at a time.
for k = 1 : nFrames
mov(k).cdata =rgb2gray( read(obj,k));
end
implay(mov);
I have got a GUI, which imports the data from a *.xls file and plots graph. The last thing I cannot do is the data refreshing, because my xls file updates each 15 sec. I want my GUI to update input data each 20 seconds. How can I do that? And also I would like to have a button which will have an ability to pause/run data updating.
function viewSTUEP
global hPlot hChoice raw
handles.F = figure('Name','viewSTUEP', 'Position',[100 20 900 550], ...
'Color',[0.8 0.8 0.8], 'NumberTitle','off', 'Resize','off');
uicontrol('Style','pushbutton', 'Position',[690 510 94 30], ...
'FontSize',12, 'String','Load', 'Callback',#LoadData);
uicontrol('Style','pushbutton', 'Position',[790 510 94 30], ...
'FontSize',12, 'String','Save plot', 'Callback',#SaveAs);
uicontrol('Style', 'pushbutton', 'Position', [690 475 94 30], ...
'FontSize',12, 'String','Update', 'Callback',#UpdatePlot);
uicontrol('Style','pushbutton', 'Position',[790 475 94 30], ...
'FontSize',12, 'String','Close', 'Callback',{#Close,handles});
set(handles.F, 'CloseRequestFcn', {#Close,handles})
set(gcf, 'Toolbar', 'figure');
clear raw, raw(1,:) = {''};
hPlot = axes('Position',[0.06 0.08 0.68 0.9], 'Visible','on');
uicontrol('Style','text', 'Position',[690 432 130 35], ...
'BackgroundColor',[0.8 0.8 0.8], 'FontSize',12, ...
'HorizontalAlignment','left', 'String','Columns for plot:');
hChoice = uicontrol('Style','listbox', 'Position',[690 420 204 22], ...
'FontSize',12, 'String',raw(1,:), 'Min',1, 'Max',1);
function Close(hObject, eventdata, handles)
delete(handles.F);
function LoadData(hObject, eventdata)
global hChoice raw xdat
[fname, pname] = uigetfile('*.xls','Select a data file');
if fname ~= 0
filename = strcat(pname, fname);
[numeric,text,raw] = xlsread(filename);
num = length(raw(1,:));
if (num > 21) num = 21; end
posY = 442 - (20*num);
set(hChoice, 'String',raw(1,:));
set(hChoice, 'Max',num);
set(hChoice, 'Position',[690 posY 204 (20*num)]);
xdat = datenum(0,0,0,0,0,cell2mat(raw(2:end,6)));
end
function UpdatePlot(hObject, eventdata)
global hPlot hChoice raw xdat
if ~isempty(raw)
cols = get(hChoice,'Value');
plot(hPlot, xdat,cell2mat(raw(2:end,cols(1))), 'LineWidth',2), datetick('x','HH:MM')
grid on
if (length(cols) > 1)
colors = 'brgcmyk'; c = 2;
hold(hPlot, 'on')
for k = cols(2:end)
plot(hPlot, xdat,cell2mat(raw(2:end,k)),colors(c),'LineWidth',2)
c = c+1; if (c > 7) c = 1; end
end
hold(hPlot, 'off')
end
legend(hPlot, raw(1,cols), 'Interpreter','none','Location','SouthEast')
xlabel(hPlot, 'Time in minutes:');
ylabel(hPlot, 'Temperature in C:');
end
function SaveAs(hObject, eventdata, handles)
[Save,savename] = uiputfile('*.eps','Save plot as: ')
fname=fullfile(savename,Save);
print('-depsc','-r300','-noui',fname)
I think you should use a timer object - see here