سؤال

I am trying to run a program that opens a webcam, takes a screenshot, processes it, and shows the output. My code runs correctly and I am getting output, but when I close the output window I get this error every-time:

Matlab System Error: Matlab has encountered an internal problem and needs to close.

As I am new to Matlab can anyone help me? I am using Windows 8 operating system and Matlab R2013a.

This is the code:

    clear all;
    close all;
    clc;
    video=videoinput('winvideo',1);
    preview(video);
    while(true)
    data=getsnapshot(video);
    R=data(:,:,1);
    G=data(:,:,2);
    B=data(:,:,3);
    for i=1:768
        for j=1:1024
           if(R(i,j)<128)
               out(i,j)=1;
           else
               out(i,j)=0;
           end
       end
   end
   cla; % Prevent stuffing too many images into the axes.
   imshow(out);
   drawnow;
   end
هل كانت مفيدة؟

المحلول

Here's some simpler code that replicates the error on Windows or on Mac for me (R2013b, built-in FaceTime HD camera):

clear all;
close all;
% video = videoinput('macvideo',1);
video = videoinput('winvideo',1);
while true
    data = getsnapshot(video);
    cla;
    imshow(data);
    drawnow;
end

Run the above and close the the window after it draws the image and you may be able to get it to crash. The strange thing is that after I reliably made it crash a few times it stopped doing it.

What is going on?

The fact that the error went away randomly for me makes me suspect some sort of race condition. You code isn't particularly correct, but Matlab shouldn't be crashing hard like this, so it should be reported as a bug.

How can you fix this?

The problem is that you're closing a window that is being drawn to inside of an infinite while loop. You need to break the while loop when the figure is closed. And you might also want to perform some cleanup such as deleting the video object. Here's some nice fast code that shouldn't produce an error :

clear all;
close all;
clc;
if ispc
    video = videoinput('winvideo',1);
elseif ismac
    video = videoinput('macvideo',1);
else
    video = videoinput(imaq.VideoDevice);
end
% preview(video);

% Create figure and get handle to image data
data = getsnapshot(video);
R = data(:,:,1);
out = double(R < 128);
h = imshow(out);

while true
    data = getsnapshot(video);
    R = data(:,:,1);
    out = double(R < 128);
    if ishghandle(h)        % Only if figure still open
        set(h,'CData',out); % Replace image data
    else
        break;
    end
end
delete(video); % Clean up
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top