Using imfreehand within your program - matlab

For instance, I start my program as follows reading some image:
I=input('image name: ','s');
img=double(imread(I));
I'm planning to work only on some portion of that image. So, I noticed that I may need h=imfreehand for this purpose.
Thus, I have inserted h=imfreehand under the two lines above. What I got is a white screen. So, how can I get the image and select the region I want? The other thing is, how can I tell my program to work only on that region I have selected?
Thanks.
UPDATE
I did the following in a portion of my code:
figure, imshow(img);
h = imfreehand;
position = wait(h);
% post processing
se=strel('disk',3);
erosion=imerode(h,se);
result_image=imsubtract(h,erosion);.
But, I got the following error:
Error using imerode
Expected input number 1, IM, to be one of these types:
numeric, logical
Instead its type was imfreehand.
Error in morphop>CheckInputImage (line 335)
validateattributes(A, {'numeric' 'logical'}, {'real' 'nonsparse'}, ...
Error in morphop>ParseInputs (line 166)
A = CheckInputImage(A, func_name);
Error in morphop (line 14)
[A,se,pre_pad,...
Error in imerode (line 123)
B = morphop(A,se,'erode',mfilename,varargin{:});
Error in program (line 155)
erosion=imerode(h,se);
Is it to do with erosion? What can be done in this case?
`

Following the advice in the matlab documentation try this:
I=input('image name: ','s');
img=imread(I);
figure, imshow(img);
h = imfreehand;
position = wait(h);
Edit:
The documentation suggests as an alternative
figure, imshow(img);
h = imfreehand(gca);

Try passing the handle of the plot to imfreehand()
I=input('image name: ','s');
img=double(imread(I));
figure;
ih=image(img);
h=imfreehand(ih)
Sorry, I don't have the image processing toolbox to test this.

Seems like converting your image (possibly uint8) to double causes a problem.
I would either do:
use the original coding of the image (for example img_uint8 = imread('coins.png') is coded using integers). The problem is that you won't probably be able to use imfreehand as it needs to read double or single precision float.
convert the image using img_double = double(imread('coins.png')) so that imfreehand will work. The conversion however causes a display problem that you can bypass with imshow(img_double,[]) that is an analogue of imshow(img_double, [min(min(img_double)), max(max(img_double))]). It forces imshow to correctly use the full range of data (255 Vs. 255.0)
The best option is therefore the second one.
To use imfreehand, #Try Hard gave a nice code h = imfreehand or h = imfreehand(gca)

Related

How to make a GIF from a set of MATLAB images

I have an array of values which I turn into a color image like so:
my_img = imagesc(my_data(:,:,tidx)); axis off; colormap('default'); c=colorbar; c.FontSize=26; c.FontWeight='bold';
I want to know if it's possible to loop through all the index values in my_data and turn them into a GIF.
I tried this:
for tidx = 5:64
my_img = imagesc(my_data(:,:,tidx)); axis off; colormap('default'); c=colorbar; c.FontSize=26; c.FontWeight='bold';
imwrite (my_img, int2str(tidx)+"_cspattern.png");
end
Which gave me this error:
Error using imwrite (line 427)
Expected DATA to be one of these types:
numeric, logical
Instead its type was matlab.graphics.primitive.Image.
I looked it up and tried this solution out:
for tidx = 5:64
my_img = imagesc(my_data(:,:,tidx)); axis off; colormap('default'); c=colorbar; c.FontSize=26; c.FontWeight='bold';
IMG_to_write = uint8(normalize(my_img, 'range', [0 255]));
imwrite(IMG_to_write, int2str(tidx)+"_cspattern.png");
end
But that just gave me this error:
Error using normalize>checkSupportedArray (line 159)
Invalid data type. First argument must be a real numeric or logical array, a table or a timetable.
Error in normalize (line 86)
checkSupportedArray(A,method,methodType,false);
Error in GenerateFigures (line 18)
IMG_to_write = uint8(normalize(SavePattern, 'range', [0 255]));
I feel as if I am overthinking this because there must be a simple way to load the data I want and save it as an image or series of images.
imagesc produces a graphics object, not a data array. It’s meant for displaying images into figures, not saving them into files. You need to hand imwrite your image data directly, along with your desired color map.
for tidx = 5:64
imwrite(my_data(:,:,tidx),parula(),int2str(tidx)+"_cspattern.png");
end
If you want to scale each image so that the full color range is used, the way imagesc does, you can do this manually.
for tidx = 5:64
my_data_slice = double(my_data(:,:,tidx));
my_data_slice = my_data_slice - min(my_data_slice,[],'all');
my_data_slice = my_data_slice / max(my_data_slice,[],'all')*255;
my_data_slice = uint8(my_data_slice);
imwrite(my_data_slice,parula(),int2str(tidx)+"_cspattern.png");
end

How to continuously update a plot?

I'm trying to plot in 'real time' in Matlab from Arduino. I have the following code to get the data:
clear all; close all;clc;delete(instrfind({'port'},{'COM12'}));
puerto=serial('COM12');
puerto.BaudRate=115200;
fopen(puerto);
for i=1:1000
a=fscanf(puerto, '%d');
v(i)=a;
++i;
end
fclose(puerto);
delete(puerto);
However, sometimes I get an error saying the following (in reference to variable a):
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in (line 8)
v(i)=a;
So I have 3 questions:
How can I avoid the error I mentioned?
How can I plot (v) continuously?
Is there a way to send an array of integers from Arduino to Matlab?
Try something like this. Using the BytesAvailableFcn of the serial port.
See Documentation
function serialTest()
lineHandle = plot(now,0);
hold on;
delete(instrfind({'port'},{'COM12'}));
puerto=serial('COM12');
puerto.InputBufferSize = 200; %Set to an appropriate number of bytes see docs
puerto.BaudRate=115200;
puerto.BytesAvailableFcnCount = 100; %Set to an appropriate number see docs.
set(puerto,'BytesAvailableFcn',{#bytesFcnCallback,lineHandle});
drawnow
fopen(puerto);
function bytesFcnCallback(puerto,evtData,lineHandle)
temp = fgetl(puerto); %Read a single line from the com port.
C = textscan(temp,'%f');
lineHandle(1).YData= [lineHandle(1).YData C{1}];
lineHandle(1).XData(end+1) = now;
Edit: Update to show how to continuously update a plot.

Series of dicom images into specific format in matlab

I have series of matlab images which belong to a single patient. I found some code online, but it is sowing some error. I want something like this, Image
Here is the code I have.
% Preallocate the 256-by-256-by-1-by-20 image array.
X = repmat(int16(0), [256 256 1 20]);
% Read the series of images.
for p=1:20
filename = sprintf('brain_%03d.dcm', p);
X(:,:,1,p) = dicomread(filename);
end
% Display the image stack.
montage(X,[])
I found this code from here:
https://www.mathworks.com/company/newsletters/articles/accessing-data-in-dicom-files.html
Error using montage>validateColormapSyntax (line 339)
An indexed image can be uint8, uint16, double, single, or logical.
Error in montage>parse_inputs (line 259)
cmap = validateColormapSyntax(I,varargin{2});
Error in montage (line 114)
[I,cmap,mSize,indices,displayRange,parent] = parse_inputs(varargin{:});
Error in Untitled2 (line 9)
montage(X,[]);
The syntax for calling the montage function has changed since that code sample was written (back in 2002!). As noted in the comments section of the File Exchange submission for the sample DICOM data files, the new correct syntax is this:
montage(X, 'DisplayRange', []);
You were getting that error since the new syntax interprets montage(X, []); as if X were an indexed color image (which isn't allowed to be a signed int16 type, according to the error) with an empty color map [].

MATLAB - error using imtransform()

I got an error when trying to run the imtransform() line in my code. I got:
Error using imtransform>parse_inputs (line 438)
XData and YData could not be automatically determined.
Try specifying XData and YData explicitly in the call to
IMTRANSFORM.
Error in imtransform (line 265)
args = parse_inputs(varargin{:});
Error in main (line 9)
newImage = imtransform(rgbImage,tf); %# Transform the image
I used the function tf = maketform() to generate the transformation itself.
So, in order to figure out what wrong with my code i simplified as much as I can the function:
function U = fisheye_inverse(X)
U = X;
end
and my code looked like this:
rgbImage = imread('IMG-20150622-WA0046.jpg'); %# Read the image
tf = maketform('custom',2,2,[],... %# Make the transformation structure
#fisheye_inverse,options);
newImage = imtransform(rgbImage,tf); %# Transform the image
imshow(newImage);
and still the code yell at me this error again.
I looked at a similar problem Here that posted here in the past, but no one answer the question in the end.
Thanks in advance, Gal :)

Cannot get imagesc to work in Matlab

Would someone kindly please tell me why imagesc is not doing what I want it to:
I am trying to get a grid of chars out like:
http://wetans.net/word-search-worksheets-for-kids
Here is the code:
A = [5,16,18,4,9;
9,10,14,3,18;
2,7,9,11,21;
3,7,2,19,22;
4,9,10,13,8]
AAsChars = char(A + 96);
imagesc(AAsChars);
The short answer is - you are using the wrong function for your job. imagesc will take a map of values and convert it to intensities - one pixel per value. You want it to magically take a character value and turn it into the representation (many pixels) of the character that this represents (without regard to font, etc).
You probably want to create an empty background, then put text characters at the locations you want. Something like (not tested):
figure
imagesc(ones(5,5))
axis off
for t = 1:5
for k = 1:5
text(t, k, sprintf('%c', A(t,k) + 96))
end
end
This should put the string (character) at the location (i,j). Experiment a bit - not sure I have the syntax of text() and the formatting of the string (with "%c") right and can't check right now.
I think you are overcomplicating, this should simply do the trick:
char(A + 96)