Geometric transformation using MATLAB Function block - matlab

I tried to apply a geometric transformation to a video using MATLAB Function block in Simulink. I connected a 'From Multimedia File' block to MATLAB Function block ant its output to a 'To Video Display' block. Inside MATLAB Function Block this code:
function outputImage = fcn(inputImage,theta)
coder.extrinsic('affine2d')
coder.extrinsic('imwarp')
outputImage = coder.nullcopy(inputImage);
tform = affine2d([cosd(theta) -sind(theta) 0; sind(theta) cosd(theta) 0; 0 0 1]);
outputImage = imwarp(inputImage,tform);
where angle theta is a constant block of 10. The code above is an example from 'affine2d' function examples. It returns me following error:
Size mismatch for MATLAB expression 'imwarp'. Expected = 120x160x3 Actual = 146x179x3 Block MATLAB Function (#108) While executing: State During Action
but I don't understand where is the error (why Actual=146x179x3). The input video is a RGB video file ('vipmen.avi') from CV toolbox demos.
EDIT: I solved it: I used Apply Geometric Transformation block for translation and a Rotate block for rotation with:
H = [1 0; 0 1; Ox-X Oy-Y] %where Ox,Oy are image framework origin coordinates and X,Y are offset coordinates.
Indeed after translation, the "new" image framework origin is the (X,Y) point and the Rotate block rotates it about (X,Y).

The Computer Vision System Toolbox includes a block called Apply Geometric Transformation, which will do what you need and save you the trouble of using MATLAB function block.
Edit:
The Apply Geometric Transformation block has been deprecated as of R2015b release. Please use the Warp block instead.

As an image is warped/rotated the number of rows and/or columns in it will change.
You'll need to modify your code so that outputImage is variable sized.
To do this open the code (for the MATLAB Function Block) in the editor and open up the "Edit Data" dialog.
Select outputImage in the left hand column, then
check the "variable size" check box
enter something like [400 400 3] as the size
You have to make a best guess for the maximum row and column size that you expect.
Note also that the Matlab function block must have a discrete sample time for it to use variable sized signals.
To set this, right click on the block and select Block Parameters, then set a sample time.

I solved trying to understand what happens. The deformed image has a dimension different from Output=coder.nullcopy(X) so I calculated the dimension of the new deformed image, create a blank image with Output=coder.nullcopy(ones(new_row,new_colomn,3)) and that works

Related

Active contour snake

I am trying using MATLAB activecontour code to segment the region. the example was used grayscale image while i am using binary image. it turn out ok when i run the code by calling the binary image. however, when i combined the code, nothing happen. it skips the iteration part, and generate the sama binary image. for your reference, below is my code.
%% snake
figure
x = imread('1.jpg');
threshold = 160;
I = rgb2gray(x);
I = Igray>threshold;
imshow (I);
I = imresize(I,.5);
imshow(I)
title('Original Image')
mask = zeros(size(I));
mask(25:end-25,25:end-25) = 1;
imshow(mask)
title('Initial Contour Location')
bw = activecontour(I,mask,1300);
imshow(bw)
title('Segmented Image, 300 Iterations')
no process happen starting from snake's code. it eventually only generate binary image. I hope someone could try run this and help me to find my mistake. Thank you in advance
Matlab's activecontour function uses the Chan–Vese (active contours without edges) method by default, like Cris said. The implementation "uses the Sparse-Field level-set method, similar to the method described in [3]", citing Whitaker, "A level-set approach to 3d reconstruction from range data". (Besides Chan–Vese, activecontour has an optional method arg that can be set to 'edge' to use an alternative "edge-based model" based on the (older) geodesic active contours method of Caselles, Kimmel, and Sapiro.)
The Chan–Vese method segments a grayscale image by looking for a binary image equal to "c1" inside the contour and "c2" outside the contour that both has a smooth contour and is a good approximation to the original image. The method optimizes c1, c2, and the shape of the contour, beginning from some initial contour and evolving it by an iterative process.
If you'll excuse a self-citation, you can find an article, open source C code, and online demo about Chan–Vese on the IPOL journal at http://www.ipol.im/pub/art/2012/g-cv/, which you may find helpful.
So why is it not working in your case? Some thoughts:
In your use, since the input image is already binary, it is clearly tempting for the method to simply set c1=0, c2=1, and the contour to the edges of the input, so "nothing happens". Try setting the optional 'SmoothFactor' arg (possibly to a large value) to force the method to look for a smoother contour.
It's conceivably a datatype problem, since image I is passed as a logical array to activecontour, but normally the function takes a numeric array. Try casting I to a double array before passing.

How can I overwrite specific values in an matrix? MATLAB

For a university assignment I have to take an image of size 512x512 and then apply an effect to particular blocks of the image, as displayed in the image below.
I have managed to achieve this by accessing particular regions of the image using indexing, like this:
w1_region = [DCTImage(1:imageSizeQuarter, imageSizeQuarter+1:imageSizeHalf)];
This is repeated for w2 and w3. These regions are all of size 128x128 and need to be written back into the original image.
However now what I need to do is overwrite the blocks of the original image with the edited blocks, so that I have a full image with 3 blocks w1, w2, w3 that have been modified.
How can I go about overwriting the matrix that defines the original image with the modified blocks? Is there a way that I can effectively say "Overwrite the values held in the matrix starting at X"?
I feel like there is some kind of matrix operation that would allow me to do this but I'm not entirely sure which.
You can use for example:
BlockFunc = #(block_struct) YourFunction(block_struct);
block_size = [128 128];
block_edges = blockproc(file_name,block_size,BlockFunc);
You should just create a function with Name of YourFunction. The input of this function is block_struct and you can access to your block position and its data.
Moreover you can use global variable to handle between YourFunction and your main script.

how to easy select the pixel's position and pixel value in matlab?

In order to classify remote sensing image by using k-means method in matlab, I want to select some samples in an image with an mouse clicking on it, but I don't know how to code that, could you tell me some method to accomplish it?
you can use impoint, for example:
figure, imshow('pout.tif');
h = impoint(gca,[]);
position = wait(h);
this interactively place a point. Use wait to block the MATLAB command line. Double-click on the point to resume execution of the MATLAB command line.
position is specifying the coordinates of the point [X Y].

Control Point Registration using matlab -'fitgeotrans' function

I'm new to Matlab and I'm trying to do a Control Point Registration using their guide: http://www.mathworks.com/help/images/point-mapping.html
It works fine until the 'fitgeotrans' function where I get an error that saying:
'Undefined function or variable 'input_points'.
I read the Matlab help and the previous "cpselect" function gives me two nX2 arrays with the coordinates which are saved (by the 'cpselect' function) in two array variables 'input_points' and 'base_points'. So, I really don't understand why the next function can't "See" them and considers them 'Undefined'.
My code is attached bellow. Thank you for your help.
function [Y] =EBL
ReferenceImg=imread('GFI.jpg'); %This is the fixed image
CroppedImg=imcrop(ReferenceImg); %Crop the image
close %close the imcrop window
ResizedIReferenceImg= imresize(CroppedImg,[1000 1000]); %re-size the fixed image
t=imagesc(ResizedIReferenceImg); %Set transparency of fixed image
set(t,'AlphaData',0.5);
hold on
I = imread('GF.bmp'); %This is the moving picture
MovingImg = imrotate(I,-5,'nearest','crop'); % Rotate the moving picture cw
ResizedMovingImg= imresize(MovingImg,[1000 1000]); %re-size the moving image
h=imagesc(ResizedMovingImg); %Set transparency of moving image
set(h,'AlphaData',0.6);
close
cpselect(ResizedMovingImg,ResizedIReferenceImg); %Alignment
tform = fitgeotrans(input_points,base_points,'NonreflectiveSimilarity');
The problem is that MATLAB doesn't, by default, wait for you to be done before moving on from cpselect. So it simply moves on from cpselect to tform before you have a chance to actually select any points, at which point input_points doesn't yet exist. You have to set the Wait parameter, and doing so also affects the outputs. With Wait on, call cpselect something like this:
[input_points,base_points] = cpselect(MovingImg,ReferenceImg,'Wait', true);
When calling cpselect in this way, you will not have the "Export Points to Workspace" option. Instead, the selected points will be output into the variables input_points,base_points when the cpselect window is closed.

Hough Transform Matlab - how to display?

I got a code from the book Feature Extraction & Image Processing.
As I am a total beginner in Matlab, I don't know how to run these codes to see results.
Are they complete?
First one : Hough Transform for Lines
%Polar Hough Transform for Lines
function HTPLine(inputimage)
%image size
[rows,columns]=size(inputimage);
%accumulator
rmax=round(sqrt(rows^2+columns^2));
acc=zeros(rmax,180);
%image
for x=1:columns
for y=1:rows
if(inputimage(y,x)==0)
for m=1:180
r=round(x*cos((m*pi)/180)+y*sin(m*pi)/180);
if(r0) acc(r,m)=acc(r,m)+1; end
end
end
end
end
Second one : Hough Transform for Circles
%Hough Transform for Circles
function HTCircle(inputimage,r)
%image size
[rows,columns]=size(inputimage);
%accumulator
acc=zeros(rows,columns);
%image
for x=1:columns
for y=1:rows
if(inputimage(y,x)==0)
for ang=0:360
t=(ang*pi)/180;
x0=round(x-r*cos(t));
y0=round(y-r*sin(t));
if(x00 & y00)
acc(y0,x0)=acc(y0,x0)+1;
end
end
end
end
end
Third one : Hough Transform for Elipses
%Hough Transform for Ellipses
function HTEllipse(inputimage,a,b)
%image size
[rows,columns]=size(inputimage);
%accumulator
acc=zeros(rows,columns);
%image
for x=1:columns
for y=1:rows
if(inputimage(y,x)==0)
for ang=0:360
t=(ang*pi)/180;
x0=round(x-a*cos(t));
y0=round(y-b*sin(t));
if(x00 & y0< rows & y0>0)
acc(y0,x0)=acc(y0,x0)+1;
end
end
end
end
end
I have images (png) that I need to run these programs with.
But I cannot seem to run it.
I create new script, paste the code, save it and in main window I run the function name sending path to the image as a parameter. It does nothing, no message or so.
Your functions don't return any value, that means that you have to add a return argument to those functions (in case of the hough trafo, you'd like to return the accumulator array acc) and as described in the manual (http://www.mathworks.de/de/help/matlab/ref/function.html), change the functions headers to:
function acc = HTPLine(inputimage)
and then also call it like this from the commandline (or from another script):
IMG = imread('some_image.jpg');
% e.g. convert to grayscale:
IMG = rgb2gray(IMG);
acc = HTPLine(IMG);
you then still need to find the maximum (or several maxima, depending on how many lines you'd like to fit) in the accumulator and display the fitted line (ellipse/circle) on your own via plot in a figure...
EDIT: Looking at your code, I don't know what the variable r0 should be!? It will def. give you an errormsesage as it's not defined anywhere.
And why do you the if(inputimage(y,x)==0) in your code? The pixel at the current point doesn't have to be black in ordner to calculate the hough transformation for that single pixel (just think of a grey-image with a white line in it -> your code wouldn't do anything as the image wouldn't contain any black pixels). So that's what you need to rethink about.
If you want to, you could also use the built-in hough transformation of MATLAB: http://www.mathworks.de/de/help/images/ref/hough.html // http://www.mathworks.de/de/help/images/ref/houghpeaks.html