How can i get object using his handle in Matlab? - matlab

I try to make a small image aquisition and procesing tool in Matlab.
My code:
himage=preview(source)
himage is a handle to image object, then i need to show image handles by himage. I have to try imshow function.
I have handle to image object, i know how to access to object properties using his handle but how can i get object by his handle?

If your preview function contains a call to imshow somewhere, you capture the handle like so:
himage = imshow(source)

Related

How do I save images with face detection bounding box using the Batch Image Processor app in Matlab

I'm a newbie to Matlab and I'm trying to perform face detection on a batch of images. I'm using this simple face detection code which works with the Image Processing Toolbox and the Computer Vision Toolbox. I'm using the Batch Image Processor App and wrote my code as a function that I apply to a batch of images. What I need as an outcome are the four values of each bounding box (this works), and I want to save each image with the bounding box drawn, in order to check if the face is detected correctly (which doesn't work). This is the function:
function results = facedetection(im)
FDetect = vision.CascadeObjectDetector('FrontalFaceLBP','MergeThreshold', 5);
BBface = step(FDetect,im);
figure,
imbb = imshow(im); hold on
for i = 1:size(BBface,1)
rectangle('Position',BBface(i,:),'LineWidth',2,'LineStyle','-
','EdgeColor','r');
end
hold off;
imwrite(imbb,'test.jpg'); %this is the line that doesn't work
results.face=BBface; %this gives me the values of each bounding box
end
When I apply this function it provides me with the values of the bounding box, and in the imshow it shows the image with the bounding box around the face. However, the imwrite function doesn't work and gives the following error:
Error using imwrite (line 420) Expected DATA to be one of these types:
numeric, logical
Instead its type was matlab.graphics.primitive.Image.
Error in facedetection (line 13) imwrite(imbb,'test.jpg');
Does anyone know how to solve this issue? Is it possible to save all images with the bounding box using the Batch Image Processor app and if so, how? Is it also possible to save the images without using imshow? I don't have to see the results directly, as long as I can save them.
I'm sorry if this question is too vague, but I hope someone can help me a bit further.
EDIT: I found out that the Batch Image Processor can be used to save the images, as long as the image is put into a results. string in the function (see documentation), but I don't know how to do this. I changed my code as followed:
function results = facedetection(im)
FDetect = vision.CascadeObjectDetector('FrontalFaceLBP','MergeThreshold', 5);
BBface = step(FDetect,im);
figure,
imbb = imshow(im); hold on
for i = 1:size(BBface,1)
rectangle('Position',BBface(i,:),'LineWidth',2,'LineStyle','-
','EdgeColor','r');
end
hold off;
BBimage = imfuse (im, BBface); %this doesn't work
results.BBValues=BBface;
results.BBimage=BBimage;
end
This code returns a complete green hued image (?!). So probably something goes wrong in the imfuse part. How do I put the im and the drawn rectangle together in the BBimage?
I solved the problem using the insertShape function. The complete function becomes as follows:
function results = facedetection(im)
FDetect = vision.CascadeObjectDetector('FrontalFaceLBP','MergeThreshold', 3);
BBvalues = step(FDetect,im);
hold on
for i = 1:size(BBvalues,1)
BBimage = insertShape (im,'rectangle',BBvalues(i,:),'Color','yellow');
end
hold off;
results.Values3=BBvalues;
results.Image3=BBimage;
end
When this function is applied to a batch of images in the Batch Image Processor app, the 'export results of all processed images to files'-button allows you to save the images including the bounding box rectangle. It saves each image with its original filename and an additional '_Image3'.
I'm using this code now to test the most effective threshold, which is why I named them Values3 and Image3 refering to the threshold 3. It works fine!
This means that imbb that you are trying to write out to a file is not the proper type to write out to a file.
Can you try something like this after your for loop and see what happens?
frame = getframe(figure);
image = frame2im(frame);
imwrite(image, 'test.jpg');
Eventually, you want to move your imwrite inside your for loop so you can batch process it.
You would declare a file name before the for loop like :
basename = 'MyFileName-';
Then inside the for loop, you would do something like
filename = [basename, num2str(i)];
imwrite(image, filename);

Save image from imshow

I want to save the image to a file after doing imshow(im,[]); to display it later in GUI. I am trying the following code, but it doesn't work.
New= imshow(uint8(MHI{t}),[]);
imwrite(New,'TMHI.jpg','jpg')
Any help will be appreciated. Thank you.
The imshow function is only used to show the image in MATLAB. If you want to save it, you don't need the imshow at all. And: the value (New) returned by imshow() is the handle to the figure. You need that handle if you want to modify how the figure is shown on the screen.
To write the image to the disk, you only need the imwrite function, which has the syntax:
imwrite(A,filename)
where A is the image array.
If the file name ends with .jpg, then MATLAB will create a JPEG image by default, so you don't need to specify that. (But of course, you still can.)
But before saving: you have a problem with the normalization of the image. MATLAB assumes that a double image is scaled to [0,1] and that a uint8 image is scaled to [0,255]. With imshow(im,[]) you override these defaults and make MATLAB calculate new values. You will experience the same problem when saving. The solution is to normalize the image properly. This can be done using the im2uint8 function, which scales the input to a maximum value of 255, and converts it to uint8. Note that you'll have to remove the minimal value manually, if that is needed:
newImage = im2uint8(MHI{t} - min(MHI{t}(:)));
imwrite(newImage,'TMHI.jpg')
In case you really need to save the contents of the displayed figure in matlab (sometimes also useful when you use imagesc for display as it has some smart logic for properly scaling your value ranges) you might be interested in the savefig and saveas which lets you save the contents of a figure. Its also possible to save graphs or figures with subfigures like that.
In that case, you would use something like:
F = imshow(uint8(MHI{t}),[]);
saveas('MHI.png');
In case you really just need to save the image stored in MHI{t}, hbaderts 's answer is the way to go...
Just use my NormalizeImage function and save the image normaly:
img = NormalizeImage(imgDouble);
imwrite(img ,'MyImage.png');
My NormalizeImage function:
function img8bpp = NormalizeImage(imgDouble)
minImgDouble = min(imgDouble(:));
factor = (255-0)/(max(imgDouble(:)) - minImgDouble);
%img8bppB = im2uint8(imgDouble-minImgDouble);
img8bpp = uint8((imgDouble-minImgDouble).*factor);
%im2uint8 does not work, duno y
%imgDif = img8bppB - img8bpp;
end

How to pass handles into certain GUI callbacks Matlab

I'm writing a matlab program and I'm trying to pass around my handles struct to ALL my callbacks. The only problem is that I'm using GUIDE and I can't pass in handles as an argument to a function I created:
%The proper slider callback: Deleted the default within GUIDE
function sliderContValCallback(hFigure,eventdata)
%test it out- get the handles object and dispay the current value
%getappdata(handles.video_loader_button,'handles');
handles = guidata(hFigure);
handles.currentFrame = floor(get(handles.slider,'Value'));
set(handles.frameBox,'String',num2str(handles.currentFrame));
fprintf('slider value: %f\n',get(handles.slider,'Value'));
updateAxes(handles);
The problem is that the way I'm 'getting' handles right now is that it isn't really the same handles that the rest of the UI object callback functions are using. I also thought of passing handles around with getappdata, but you need handles to even do that so I'm stuck. This has been causing some problems, any help as to how to get around this would be awesome, thanks!
EDIT:
I deleted the call back generated by GUIDE, so that I could use sliderContValCallback as a function handle and call it here:
handles.sliderListener = addlistener(handles.slider,'ContinuousValueChange',...
#(hFigure,eventdata) sliderContValCallback(hObject,eventdata));
for continuous updates as the user drags the slider(This is used to scroll through a video, and its working well).
The real reason I'm questioning this is because when I call:
allCoords = getappdata(handles.axes1,'mydata');
coordsXYZ = allCoords.clickcoordinates; %Do this to access the field 'allCoords' within 'mydata'
curIndex = allCoords.currentIndex;
if numel(coordsXYZ)>0
for i = 1:length(coordsXYZ)
coordXY = [coordsXYZ(i).x,coordsXYZ(i).y];
%viscircles(handles.axes1,coordXY,1,'EdgeColor','r');
hold on;
plot(coordsXYZ(i).x,coordsXYZ(i).y,'o');
end
end
everything works but a figure is generated for some reason, the plot is drawn to an image on handles.axes1. It's weird because this random figure pops up ONLY when I update the slider by moving it.

Adding a MATLAB GUI to a MATLAB code

I am asked by my professor to add a GUI for my Matlab code. My program receives an image as an input and returns a string.
The GUI should enable me to browse the image and then display it. Then I need to use that image in the Matlab code.
To browse and display the image, I created a pushbutton control and wrote the following in its callback
[baseFileName, folder] = uigetfile('*.jpg');
fullFileName = [folder baseFileName];
rgbImage = imread(fullFileName,'jpg');
imshow(rgbImage);
I added a second pushbutton and the Matlab code (which has a file name main.m) inside its callback. This function needs the image displayed above as an input, and its output (which is a string) needs to be displayed in the GUI.
I am facing a few problems:
I want the image to be displayed in a specific position.
How can I call the function in the push button?
How can I access and use the image in the first push button to the second push button?
Some hints on how you can get started with your problems:
You could create an axes object in your figure, whose position can be defined. then just plot the image on that axes. Do all that in the callback
Calling a function from a callback should not be a problem
Save the image in structure, then you can use for example setappdata and getappdata to pass it between callbacks, i.e. when your figure handle is h.fig and your structure called d:
setappdata(h.fig,'d',d)
in the first callback, and to retrieve it, in the second:
d = getappdata(h.fig,'d');

image save in matlab

I have an image and after drawing some features(ellipses and text) on it I want to save it as JPEG.
h= figure(1);
imagesc(im_name);
colormap('gray');
hold on
for i=1:no_of_points;
//draw features and write some text
end
hold off
imsave (h);
I am getting a figure with features drawn on it but when I save it, it is an image (which is my orignal image 'im_name') without new features on it.
I tried also
.
.
.
imsave (h);
hold off
Thanx in advance for your help.
Maybe you should try the function saveas
saveas
Save figure or Simulink block diagram using specified format
Alternatives
Use File > Save As on the figure window menu to access the Save As
dialog, in which you can select a graphics format. For details, see
Exporting in a Specific Graphics Format in the MATLAB Graphics
documentation. Sizes of files written to image formats by this GUI and
by saveas can differ due to disparate resolution settings. Syntax
saveas(h,'filename.ext') saveas(h,'filename','format')
Description
saveas(h,'filename.ext') saves the figure or Simulink block diagram
with the handle h to the file filename.ext. The format of the file is
determined by the extension, ext. Allowable values for ext are listed
in this table.
You can pass the handle of any Handle Graphics object to saveas, which
then saves the parent figure to the object you specified should h not
be a figure handle. This means that saveas cannot save a subplot
without also saving all subplots in its parent figure.
When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:
hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');
This will do exactly as manually saving the figure.
Source.