How to deal with expired URL links when using imread URL? - matlab

I am working on the face scrub dataset, which has a long list of urls of pictures.
I used a for loop to fetch these photos. However, some of the urls had expired so my matlab code return an error saying 'Unable to determine the file format.' However I think the actual reason is that the url link does not have the image anymore. For example, one of the bad urls is:
http://www.gossip.is/administrator/components/com_n-myndir/uploads/16de47418d69b1c2991731dffaca8a78.jpg
How do I identify and ignore this error so my code can keep working on the rest of the list? I could use R instead if that make solving this problem easier.

You can implement a try/catch block to catch (original isnt'it) the error message and skip the image if the link is indeed broken.
When we use the following syntax:
try
A = imread('http://www.gossip.is/cgi-sys/suspendedpage.cgi');
catch ME
%// Just so we know what the identifier is.
ME
end
Matlab first tries to read the image given by the url. If it can't, we ask it to catch the error message (MException actually) and perform some other appropriate action.
The thing is, we need to know what is the exact error message in order to recognize it in the try/catch block.
When I entered the above code, I got the following structure for ME:
ME =
MException with properties:
identifier: 'MATLAB:imagesci:imread:fileFormat'
message: 'Unable to determine the file format.'
cause: {0x1 cell}
stack: [2x1 struct]
Therefore, once we know the exact identifier generating the error we can use strcmp to look for it in the try/catch block. For instance with the following code:
clear
clc
try
A = imread('http://www.gossip.is/cgi-sys/suspendedpage.cgi');
catch ME
if strcmp(ME.identifier,'MATLAB:imagesci:imread:fileFormat')
disp('Image link broken')
end
A = imread('peppers.png');
end
imshow(A);
Matlab displays 'Image link broken' and reads peppers.png, as expected.
Hope that helps!

Related

Displaying Data as a String in Simulink RT Display Port

My issue involves using the RS-232 Simulink RT blocks.
A model is uploaded to the target PC (xPC) and it transmits and receives data from a variable frequency drive (VFD) that controls a motor. The issue arises on the receiving end when I take data and try to send that data to a display block in my model as a string. Code would be helpful here:
disp = uint8(zeros(1,24));
display = uint8(zeros(1,length(disp)));
cmd = 0;
status = stat_lb;
%% Start-Up
% Initialization Period
if (status == 0 || status == 1)
cmd = 0;
msg = uint8('Start up');
display = [msg uint8(zeros( 1, length(disp)- length(msg) ))];
end
...
%Multiple status cases with unique displays.
...
disp = display
So, here the cmd portion functions as expected. As noted above, I want to display the display string on a display block in my Simulink model. As you can see, though, it is of type uint8, so I need to convert it to type string; however, when I pass it through either the ascii2str Simulink block or just place it in the function call (e.g. display = ascii2str(display)) I get the following error message:
Executing the 'CheckData' command produced the following error: Invalid parameter/value pair arguments
My thought is that this has something to do with the fact that I am using MEX and this function (ascii2str) is not supported. Anyways, I am wondering if anyone knows why I receive this error and if there is anything I can do to resolve it.
Oh, and one last thing: I can get the display to work if I just remove the ascii2str; however, the only problem with this is that the display is in uint8 form and not really helpful. So, if there is any other way that I can decode the uint8 to a string I am all ears.
Thanks!
I have found that there is no support for this feature in Simulink RT. One option is to use external functions, but I found it better for my application to simply output a number and have a table in the simulation that explained what each number meant.

Matlab exception sent by mail is not showing the line of the error

In my matlab script I am sending a mail to me with an exception that tells me, when an error happens, which kind of error it is.
The problem I am facing is the fact that the ME exception is not showing me where the error happens (which line and which part of the code) as matlab usually does. I can't see the error in the matlab terminal too (the program just stops running). The code that sends the mail with the error is below:
try
% my script which can fail....
demo
catch ME
% An error will put here.
errorMessage = sprintf('Error in demo. The error is: %s', ME.message);
%this function just sends the mail
sendmail2me(errorMessage);
What I missed?
The exception ME is an MException object which contains an identifier, the message, a cause and the stack. The identifier is only there to allow MATLAB an unique identification of an error. The message contains a description of the error.
The cause contains an array of MExceptions which have led to the current exception. This allows you to track the exceptions to find the root of your error. As the cause is a (possibly empty) array of MException objects, you could go through the cause in an array and write the information into the mail.
Most important for you is the stack. It is a struct containing three fields: file, name and line. File is the full path to the file/function where the error occurred. Name is (obviously) the name of the file and in line (again obviously) the line where the exception occurred is saved. The stack can also be an array if the error occurred in a function called from you function/script. It would therefore be best to go through stack in a for loop, and concatenate the error message and the contents of the stack.
try
demo;
catch ME
errormsg = sprintf('%s\n',ME.message);
for k=1:length(ME.stack)
errormsg = sprintf('%s\nError in %s (line %d)\n', ...
errormsg,ME.stack(k).name,ME.stack(k).line);
end
sendmail2me(errormsg);
end
You find more detailed information on Exceptions in the MATLAB help pages.

error in storing captured images in a structure

I want to capture 100 images from my webcam and then store them in a structure. I'm trying to do it like this but i'm getting the error, 'subscripted assignment dimensions mismatch'.
The code is this:
sep_images=struct('images',[]);
vid=videoinput('winvideo',1,'YUY2_320x240');
set(vid,'FramesPerTrigger',Inf);
set(vid,'ReturnedColorspace','rgb');
vid.FrameGrabInterval=1;
start(vid)
for num_frames= 1:100
im=getsnapshot(vid);
sep_images.images(num_frames)=im;
end
stop(vid);
and it is giving me the error in this statement, sep_images.images(num_frames)=im;.
If someone has the idea of how to do it? please let me know.
I think you intended the images field to be a cell.
Initialize like:
sep_images=struct('images',{[]})
Assign like:
sep_images.images{num_frames}=im;
Just remember to access it with curly braces too (i.e. I = sep_images.images{iframe}).

Object is Invalid or Deleted when pressing button and plotting

Please help. The error says that the object is deleted.
Error using handle.handle/get
Invalid or deleted object.
Error in C:\Program Files\MATLAB\R2011b\toolbox\matlab\graph2d\plotyy.p>localUpdatePosition (line 373)
Error in C:\Program Files\MATLAB\R2011b\toolbox\matlab\graph2d\plotyy.p>#(obj,evd (localUpdatePosition(obj,evd,ax(1),ax(2))) (line 212)
I really do not understand what was deleted but every time I perform the impz(signal), the plot isn't showing the correct graph unlike the plot in freqz(signal) and zplane(signal).
This is what really happens (26seconds video) - https://www.youtube.com/watch?v=HTR45lNIjuc
Line 212 contains this code handles.N = str2num(get(handles.edtOrder,'String'));
Line 373 contains this code zplane(handles.axPlots,handles.firVector,1)
Code for impulse response
if (get(handles.cbImpResp,'Value') == 1)
set(handles.txtPlotAvail,'Visible','off');
switch (handles.filterValue)
case 'FIR'
impz(handles.axPlots,handles.firVector,1)
case 'IIR'
impz(handles.axPlots,handles.vectorB,handles.vectorA)
case 'Multiple Bandpass'
end
else
set(handles.txtPlotAvail,'Visible','on');
end
The code is either mixing up your handles or overwriting old ones. There no way to debug this without the full source.
See http://www.mathworks.com/matlabcentral/answers/85117

Specifying timeout when reading URL image with MATLAB imread function

The MATLAB imread function provides the ability to read an image from a URL. This generally works OK, but occasionally I encounter an image that takes a very long time to respond.
For instance, at the time of posting the following URL appears to just be stuck in a 'connecting...' state for over 5 minutes before finally succeeding.
http://www.hollywoodheadache.com/wp-content/uploads/2007/12/tom-and-julia.jpg
Is there any way I can set a timeout within MATLAB?
Thanks
I don't know how to interrupt imread with a timer object. Besides, I suspect about its possibility. But I may recommend you to check whether you can access to the file first, and then, you get the file. I have written the following function to check the file and internet status:
function flag = does_url_exist(urlName)
url =java.net.URL(urlName);
try
link = openStream(url);
parse = java.io.InputStreamReader(link);
snip = java.io.BufferedReader(parse);
if ~isempty(snip)
flag = 1;
else
flag = 0;
end
catch exception
flag = 0;
end
end
Then it is as follows:
fname = 'http://www.hollywoodheadache.com/wp-content/uploads/2007/12/tom-and-julia.jpg';
if(does_url_exist(fname))
img = imread(fname);
end
Note that for internet connection checking, I took the initial code from this post. Also note that if you are sure that the file exists, it is not efficient to check it again since it increases the running time.