Make a circle inside a matrix in Matlab - matlab

I want to make a circle inside a matrix. For example; Make a matrix of some dimension, let's say ones(200,200) and then select its circle's x and y co-ordinates and change the color of these selected pixels and then show the image using imshow(img). As showing in the picture. Is it possible?
OR
Can I change this ploting code to picture for using the circle functionality?
radius = 5;
centerX = 20;
centerY = 30;
viscircles([centerX, centerY], radius);
axis square;

You can use meshgrid to create a grid of x and y coordinates and then use the equation of the circle to check whether each x/y pair is within the circle or not. This will yield a logical result which can be displayed as an image
[x,y] = meshgrid(1:200, 1:200);
isinside = (x - centerX).^2 + (y - centerY).^2 <= radius^2;
imshow(isinside);
If you simply want the outline of the circle, you can apply a convolution to the resulting binary mask to decrease it's size and then subtract out the circle to yield only the outline
shrunk = ~conv2(double(~isinside), ones(3), 'same');
outline = isinside - shrunk;
imshow(outline)
If you have the Image Processing Toolbox, you can use bwperim to yield the binary outline
outline = bwperim(isinside);
imshow(outline);
Update
If you want to change the colors shown above, you can either invert outline and isinside before displaying
isinside = ~isinside;
outline = ~outline;
imshow(isinside)
imshow(outline)
Or you can invert the colormap
imshow(isinside)
colormap(gca, flipud(gray))

Related

Finding the pixel displacement in fish eye images

I am trying to plot the displacement of a pixel from the original image to the fish eye image based on the radius from the center of the image.
I was successful in producing fish images in MATLAB using maketform
testImg = imread('ship.jpg');
optTra = maketform('custom',2,2,[],#radial,options);
newX = imtransform(testImg,optTra);
imshow(newX);
the radial function here helps me to get the fish eye distorted image.
I need to find the displacement of each pixel in the original image to that of the distorted image.
If the transformation applied (a.k.a "#radial") was angular, the inverse transformation is given by:
u = r cos(phi) + 0.5;
v = r sin(phi) + 0.5;
where
r = atan2(sqrt(x*x+y*y),p.z)/pi;
phi = atan2(y,x);
x,y are assumed to be normalized coordinates (centered and between -1 to 1).

How do i create a rectangular mask at known angles?

I have created a synthetic image that consists of a circle at the centre of a box with the code below.
%# Create a logical image of a circle with image size specified as follows:
imageSizeY = 400;
imageSizeX = 300;
[ygv, xgv] = meshgrid(1:imageSizeY, 1:imageSizeX);
%# Next create a logical mask for the circle with specified radius and center
centerY = imageSizeY/2;
centerX = imageSizeX/2;
radius = 100;
Img = double( (ygv - centerY).^2 + (xgv - centerX).^2 <= radius.^2 );
%# change image labels from double to numeric
for ii = 1:numel(Img)
if Img(ii) == 0
Img(ii) = 2; %change label from 0 to 2
end
end
%# plot image
RI = imref2d(size(Img),[0 size(Img, 2)],[0 size(Img, 1)]);
figure, imshow(Img, RI, [], 'InitialMagnification','fit');
Now, i need to create a rectangular mask (with label == 3, and row/col dimensions: 1 by imageSizeX) across the image from top to bottom and at known angles with the edges of the circle (see attached figure). Also, how can i make the rectangle thicker than 1 by imageSizeX?. As another option, I would love to try having the rectangle stop at say column 350. Lastly, any ideas how I can improve on the resolution? I mean is it possible to keep the image size the same while increasing/decreasing the resolution.
I have no idea how to go about this. Please i need any help/advice/suggestions that i can get. Many thanks!.
You can use the cos function to find the x coordinate with the correct angle phi.
First notice that the angle between the radius that intersects the vertex of phi has angle with the x-axis given by:
and the x coordinate of that vertex is given by
so the mask simply needs to set that row to 3.
Example:
phi = 45; % Desired angle in degrees
width = 350; % Desired width in pixels
height = 50; % Desired height of bar in pixels
theta = pi-phi*pi/180; % The radius angle
x = centerX + round(radius*cos(theta)); % Find the nearest row
x0 = max(1, x-height); % Find where to start the bar
Img(x0:x,1:width)=3;
The resulting image looks like:
Note that the max function is used to deal with the case where the bar thickness would extend beyond the top of the image.
Regarding resolution, the image resolution is determined by the size of the matrix you create. In your example that is (400,300). If you want higher resolution simply increase those numbers. However, if you would like to link the resolution to a higher DPI (Dots per Inch) so there are more pixels in each physical inch you can use the "Export Setup" window in the figure File menu.
Shown here:

Matlab: mask/create a circular roi knowing its origin point with a certain radius

Just a quick question. I've an image and I've extracted a certain point (feature), I know the coordinates of that point in every frame.
Say x1 and y1.
I need a circular ROI form that point on the image with a radius that I chose.
I tried impoly and roipoly - not sure how to use either of these when I know the point in the image.
Thanks
Since you know the coordinates of the center of the ROI along with the radius, you can modify a bit the code provided by #Jonas here to create a circular mask in a quite efficient way.
Example:
clc;clear
Im = imread('coins.png');
[rNum,cNum,~] = size(Im);
%// Define coordinates and radius
x1 = 60;
y1 = 100;
radius = 40;
%// Generate grid with binary mask representing the circle. Credit to Jonas for original code.
[xx,yy] = ndgrid((1:rNum)-y1,(1:cNum)-x1);
mask = (xx.^2 + yy.^2)<radius^2;
%// Mask the original image
Im(mask) = uint8(0);
imshow(Im)
Output:
EDIT
If you want to see only the outer edge of the ROI to see the center, add a logical condition with some tolerance for the radius of a smaller circle. Something like this:
mask = (xx.^2 + yy.^2)<radius^2 & (xx.^2 + yy.^2)>(radius-tol)^2;
With a tol of 2 it looks like this:

How to draw a circle with perspective transformation

I want to draw a circle with perspective tansformation in Matlab. Here I have used sample of code to draw a circle. If I rotate this circle using perspective tansform this must be ellipse. I want to draw both axis rotation(X & Y) of a circle. Now I am struggled to draw a perspetive rotation of this circle.
I need to use radious of the circle, x axis roation angle and y axis roation angle as input parameters.
Rimg = zeros(600,600);
ri = 100;
xcentre = 300;
ycentre = 300;
for r = 0:ri
for rad = 0:(pi/720):(2*pi)
xi = round(xcentre+(r*cos(rad)));
yi = round(ycentre+(r*sin(rad)));
Rimg(xi,yi) = 1;
end
end
imshow(Rimg,[]);
The first image shows my circle and the second image shows the expected result. This is only rotated in x axis. But I need both axis rotation in a single image.

How to measure the rotation of a image in MATLAB?

I have two images. One is the original, and the another is rotated.
Now, I need to discover the angle that the image was rotated. Until now, I thought about discovering the centroids of each color (as every image I will use has squares with colors in it) and use it to discover how much the image was rotated, but I failed.
I'm using this to discover the centroids and the color in the higher square in the image:
i = rgb2gray(img);
bw = im2bw(i,0.01);
s = regionprops(bw,'Centroid');
centroids = cat(1, s.Centroid);
colors = impixel(img,centroids(1),centroids(2));
top = max(centroids);
topcolor = impixel(img,top(1),top(2));
You can detect the corners of one of the colored rectangles in both the image and the rotated version, and use these as control points to infer the transformation between the two images (like in image registration) using the CP2TFORM function. We can then compute the angle of rotation from the affine transformation matrix:
Here is an example code:
%# read first image (indexed color image)
[I1 map1] = imread('http://i.stack.imgur.com/LwuW3.png');
%# constructed rotated image
deg = -15;
I2 = imrotate(I1, deg, 'bilinear', 'crop');
%# find blue rectangle
BW1 = (I1==2);
BW2 = imrotate(BW1, deg, 'bilinear', 'crop');
%# detect corners in both
p1 = corner(BW1, 'QualityLevel',0.5);
p2 = corner(BW2, 'QualityLevel',0.5);
%# sort corners coordinates in a consistent way (counter-clockwise)
p1 = sortrows(p1,[2 1]);
p2 = sortrows(p2,[2 1]);
idx = convhull(p1(:,1), p1(:,2)); p1 = p1(idx(1:end-1),:);
idx = convhull(p2(:,1), p2(:,2)); p2 = p2(idx(1:end-1),:);
%# make sure we have the same number of corner points
sz = min(size(p1,1),size(p2,1));
p1 = p1(1:sz,:); p2 = p2(1:sz,:);
%# infer transformation from corner points
t = cp2tform(p2,p1,'nonreflective similarity'); %# 'affine'
%# rotate image to match the other
II2 = imtransform(I2, t, 'XData',[1 size(I1,2)], 'YData',[1 size(I1,1)]);
%# recover affine transformation params (translation, rotation, scale)
ss = t.tdata.Tinv(2,1);
sc = t.tdata.Tinv(1,1);
tx = t.tdata.Tinv(3,1);
ty = t.tdata.Tinv(3,2);
translation = [tx ty];
scale = sqrt(ss*ss + sc*sc);
rotation = atan2(ss,sc)*180/pi;
%# plot the results
subplot(311), imshow(I1,map1), title('I1')
hold on, plot(p1(:,1),p1(:,2),'go')
subplot(312), imshow(I2,map1), title('I2')
hold on, plot(p2(:,1),p2(:,2),'go')
subplot(313), imshow(II2,map1)
title(sprintf('recovered angle = %g',rotation))
If you can identify a color corresponding to only one component it is easier to:
Calculate the centroids for each image
Calculate the mean of the centroids (in x and y) for each image. This is the "center" of each image
Get the red component color centroid (in your example) for each image
Subtract the mean of the centroids for each image from the red component color centroid for each image
Calculate the ArcTan2 for each of the vectors calculated in 4), and subtract the angles. That is your result.
If you have more than one figure of each color, you need to calculate all possible combinations for the rotation and then select the one that is compatible with the other possible rotations.
I could post the code in Mathematica, if you think it is useful.
I would take a variant to the above mentioned approach:
% Crude binarization method to knock out background and retain foreground
% features. Note one looses the cube in the middle
im = im > 1
Then I would get the 2D autocorrelation:
acf = normxcorr2(im, im);
From this result, one can easily detect the peaks, and as rotation carries into the autocorrelation function (ACF) domain, one can ascertain the rotation by matching the peaks between the original ACF and the ACF from the rotated image, for example using the so-called Hungarian algorithm.