MATLAB Answers

How to add camera preview in matlab gui without using image acquisition tool box?

39 views (last 30 days)
Hi..i want to add camera live view in matlab gui without using imaqtool box. I have this code cam=webcam(1); preview(cam);
It works in the matlab command window. I want to get the camera live when clicking a how to implement this in gui? Please help me out

Accepted Answer

Walter Roberson
Walter Roberson on 2 Oct 2016
The usb webcam preview() function uses the USB Webcam support package, but not the Image Acquisition toolbox.
You can call upon preview() in your code from a GUI callback.
If you want the preview to appear in a specific place, then there is a way to do it that appears to be undocumented. First, create an axes of the appropriate size and position -- the preview has to be inside an axes. Secondly, create an image() of the appropriate size within that axes:
fig = figure();
ax = axes('Parent', fig, 'Units', 'normalized', 'Position', [0 0 1 1]);
cam = webcam(1);
camsize = str2double( strsplit(cam.Resolution, 'x'));
im = image(zeros(camsize), 'Parent', ax);
Everything above except the appropriate image sizing could be done ahead of time in GUIDE and saved.
With those done, we get to the undocumented part that needs to be done at run-time:
preview(cam, im); %pass the image object to preview!
This tells preview to send the content updates to the given image object.
Walter Roberson
Walter Roberson on 4 Oct 2016
For HG1 (R2014a and earlier)
fig = figure();
ax = axes('Parent', fig, 'Units', 'normalized', 'Position', [0 0 1 1]);
%the above can be done ahead of time -- the figure and axis can be created in GUIDE
cam = webcam(1);
pv = preview(cam); %handle to an image
pvparent = get(pv, 'Parent'); %object that holds the preview
pvfig = ancestor(pvparent, 'figure'); %the figure that contains the image
set(pv, 'Parent', ax); %move the preview to the desired axes
set(ax, 'Visible', 'off', 'YDir', 'reverse', 'XDir', 'reverse'); %where it will show up upside-down and backwards
set(pvfig, 'Visible', 'off'); %set the preview figure invisible
Now, do not close or delete the preview figure or else MATLAB will crash!!
When you are ready to get rid of the preview, then
set(pv, 'Parent', pvparent); %move it back where it was
However, if you
then MATLAB will still crash :(
... But further testing shows that it does that for normal previews that have not been moved. So instead,
set(pvfig, 'Visible', 'on')
and click the appropriate control area to close it.

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!