creating an image in matlab of 9 small white circles in a large black square - image

Im looking to create an image in Matlab of a large black rectangle with 9 small circles arranged as a a 3x3 array aligned in the centre of the rectangle, i.e. the centre circle will have its midpoint in the centre of the square.
I need the circles evenly spaced apart with some distance between each circle and between the outer circles and the border of the rectangle (think of a square piece of paper with 9 holes placed in it by stabbing it with a pen). I need this so that i can see how image convolution using a 2D gaussian will distort this image.
However I’m relatively new to Matlab and have been trying to create this image. I have successfully made a black/white square and a white circle in a black square which takes up most of the square itself but I cant seem to make a small white circle in any desired location in a black square let alone multiple small circles in a specific alignment.
This is what I have used to create the black square with a large circle:
X = ones([100,1])*([-50:49]);
Y = ([-50:49]')*(ones([1,100]));
Z = (X.^2)+(Y.^2);
image = zeros([100 100]);
image(find(Z<=50^2)) = 1;
imshow(image)

If I understood correctly, try this:
% size of each small box. Final image will be 3Nx3N
N = 100;
% create a circle mask
t = linspace(0,2*pi,50); % approximated by 100 lines
r = (N-10)/2; % circles will be separated by a 10 pixels border
circle = poly2mask(r*cos(t)+N/2+0.5, r*sin(t)+N/2+0.5, N, N);
% replicate to build image
img = repmat(circle, 3,3);
subplot(121), imshow(img)
% after applying Gaussian filter
h = fspecial('gaussian', [15 15], 2.5);
img2 = imfilter(im2double(img), h);
subplot(122), imshow(img2)

Related

Retrieve corner coordinates of image given resolution and center point

I'm going through an image dataset which has image pixel coordinate and the resolution of the image. Is there any way to map that information to corner coordinates of the image.
For instance if the image pixel coordinates are -403059.626, -12869811.372 and image is 4168 x 3632 pixels, Is it possible to extract the real world coordinates of the four corners of each image in the rectangle? We can assume the size of the pixel as 1 unit
Assuming p = (-403059.626, -12869811.372) is the pixel in the middle of the image, and an image of size s = (4168, 3632) pixels, and a pixel size of 1 (meaning pixels are in the same units as the location given by p), then the coordinates of the top-left corner can be computed as follows:
q = p - s/2 = ( -403059.626 - 4168/2 , -12869811.372 - 3632/2 )
The s/2 value above can be computed differently depending on what you consider the pixel in the middle of the image. Here I assume the top-left pixel has index (0,0), and the pixel in the middle has index (4168/2,3632/2).
The above assumes no rotation (i.e. the image axes are aligned with the coordinate system), and no distortion (it is possible that the camera adds distortion to the image, causing the pixel pitch to change in different parts of the image).
The bottom-right corner then has coordinates:
r = q + s-1 = p + s/2 - 1

Crop the largest square inside a circle object - Matlab

I am trying to find a way to crop from a circle object (Image A) the largest square that can fit inside it.
Can someone please explain/show me how to find the biggest square fit parameters of the white space inside the circle (Image I) and based on them crop the square in the original image (Image A).
Script:
A = imread('E:/CirTest/Test.jpg');
%imshow(A)
level = graythresh(A);
BW = im2bw(A,level);
%imshow(BW)
I = imfill(BW, 'holes');
imshow(I)
d = imdistline;
[centers, radii, metric] = imfindcircles(A,[1 500]);
imageCrop=imcrop(A, [BoxBottomX BoxBottomY NewX NewY]);
I have a solution for you but it requires a bit of extra work. What I would do first is use imfill but directly on the grayscale image. This way, noisy pixels in uniform areas get inpainted with the same intensities so that thresholding is easier. You can still use graythresh or Otsu's thresholding and do this on the inpainted image.
Here's some code to get you started:
figure; % Open up a new figure
% Read in image and convert to grayscale
A = rgb2gray(imread('http://i.stack.imgur.com/vNECg.jpg'));
subplot(1,3,1); imshow(A);
title('Original Image');
% Find the optimum threshold via Otsu
level = graythresh(A);
% Inpaint noisy areas
I = imfill(A, 'holes');
subplot(1,3,2); imshow(I);
title('Inpainted image');
% Threshold the image
BW = im2bw(I, level);
subplot(1,3,3); imshow(BW);
title('Thresholded Image');
The above code does the three operations that I mentioned, and we see this figure:
Notice that the thresholded image has border pixels that need to be removed so we can concentrate on the circular object. You can use the imclearborder function to remove the border pixels. When we do that:
% Clear off the border pixels and leave only the circular object
BW2 = imclearborder(BW);
figure; imshow(BW2);
... we now get this image:
Unfortunately, there are some noisy pixels, but we can very easily use morphology, specifically the opening operation with a small circular disk structuring element to remove these noisy pixels. Using strel with the appropriate structuring element in addition to imopen should help do the trick:
% Clear out noisy pixels
SE = strel('disk', 3, 0);
out = imopen(BW2, SE);
figure; imshow(out);
We now get:
This mask contains the locations of the circular object we now need to use to crop our original image. The last part is to determine the row and column locations using this mask to locate the top left and bottom right corner of the original image and we thus crop it:
% Find row and column locations of circular object
[row,col] = find(out);
% Find top left and bottom right corners
top_row = min(row);
top_col = min(col);
bottom_row = max(row);
bottom_col = max(col);
% Crop the image
crop = A(top_row:bottom_row, top_col:bottom_col);
% Show the cropped image
figure; imshow(crop);
We now get:
It's not perfect, but it will of course get you started. If you want to copy and paste this in its entirety and run this on your computer, here we are:
figure; % Open up a new figure
% Read in image and convert to grayscale
A = rgb2gray(imread('http://i.stack.imgur.com/vNECg.jpg'));
subplot(2,3,1); imshow(A);
title('Original Image');
% Find the optimum threshold via Otsu
level = graythresh(A);
% Inpaint noisy areas
I = imfill(A, 'holes');
subplot(2,3,2); imshow(I);
title('Inpainted image');
% Threshold the image
BW = im2bw(I, level);
subplot(2,3,3); imshow(BW);
title('Thresholded Image');
% Clear off the border pixels and leave only the circular object
BW2 = imclearborder(BW);
subplot(2,3,4); imshow(BW2);
title('Cleared Border Pixels');
% Clear out noisy pixels
SE = strel('disk', 3, 0);
out = imopen(BW2, SE);
% Show the final mask
subplot(2,3,5); imshow(out);
title('Final Mask');
% Find row and column locations of circular object
[row,col] = find(out);
% Find top left and bottom right corners
top_row = min(row);
top_col = min(col);
bottom_row = max(row);
bottom_col = max(col);
% Crop the image
crop = A(top_row:bottom_row, top_col:bottom_col);
% Show the cropped image
subplot(2,3,6);
imshow(crop);
title('Cropped Image');
... and our final figure is:
You can use bwdist with L_inf distance (aka 'chessboard') to get the axis-aligned distance to the edges of the region, thus concluding the dimensions of the largest bounded box:
bw = imread('http://i.stack.imgur.com/7yCaD.png');
lb = bwlabel(bw);
reg = lb==2; %// pick largest area
d = bwdist(~reg,'chessboard'); %// compute the axis aligned distance from boundary inward
r = max(d(:)); %// find the largest distance to boundary
[cy cx] = find(d==r,1); %// find the location most distant
boundedBox = [cx-r, cy-r, 2*r, 2*r];
And the result is
figure;
imshow(bw,'border','tight');
hold on;
rectangle('Position', boundedBox, 'EdgeColor','r');
Once you have the bounding box, you can use imcrop to crop the original image
imageCrop = imcrop(A, boundedBox);
Alternatively, you can
imageCrop = A(cy + (-r:r-1), cx + (-r:r-1) );

Changing the centre of transformation/mapping in polar coordinate MATLAB

After applying the following code I get output mapped image started from centre top point. How can I put the starting point to left bottom corner? So, the output image should be stretched from left bottom point(not from top centre as it is now)...
im = imread ('peppers.png');
im = rgb2gray(im);
[nZ,nX] = size(im);
theta = ((0:(nX-1))-nX/2)*(0.1*(pi/180)) - pi/2;
rr = (0:(nZ-1))*0.1e-3;
%% Plot image in rectangular coordinates
figure
imagesc(theta*(180/pi), rr*1e3, im)
xlabel('theta [deg]')
ylabel('r [mm]')
%% Create grids and convert polar coordinates to rectangular
[THETA,RR] = meshgrid(theta,rr);
[XX,YY] = pol2cart(THETA,RR);
%% Plot as surface, viewed from above
figure
surf(XX*1e3,YY*1e3,im,'edgecolor','none')
view(0,90)
xlabel('x [mm]')
ylabel('y [mm]')

How to scale a rotated rectangle to always fit another rectangle

the background of my question is the following.
I have a picture and a crop rectangle which describes how the picture should be cropped to produce the resulting picture. The crop rectangle is always smaller or at maximum the size of the picture.
Now it should be possible to rotate the crop rectangle.
This means that when rotating the crop regtanle inside the picture, the crop must be scaled in order that its extends does not exceed the photo.
Can anybode help me with a formula of how to compute the scale of the crop rectanlge based on the axis aligned photo regtancle?
My first attempt was to compute a axis aligned bounding box of the crop rectanlge and than make this fit it the photo rectangle. But somehow i get stuck with this approach,
Edited:
One more think to note:
- The crop rectangle can have other dimension and another center point inside the surrounding rectangle. This means the crop rectangle can be much smaller but for example is located at the lower left bound of the picture rectangle. So when rotating the smaller crop it will also exceed its limits
Thanks in advance
Sebastian
When you rotate an axis-aligned rectangle of width w and height h by an angle φ, the width and height of the rotated rectangle's axis-aligned bounding box are:
W = w·|cos φ| + h·|sin φ|
H = w·|sin φ| + h·|cos φ|
(The notation |x| denotes an absolute value.) This is the bounding box of the rotated crop rectangle which you can scale to fit the original rectangle of width wo and height ho with the factor
a = min(wo / W, ho / H)
if a is less than 1, the rotated crop rectangle fits inside the original rectangle and you don't have to scale. Otherwise, reduce the crop rectangle to the scaled dimensions
W′ = a·W
H′ = a·H
You could start checking if the dimension of the cropped rectangle fit in the old rectangle:
bound_x = a * cos(theta) + b * sin(theta)
bound_y = b * cos(theta) + a * sin(theta)
Where a and b are the new dimensions, theta us the angle and bound_x and bound_y should be smaller of the original rectangle.

Image Repetition from Binary to Cartesian

I'd like to take in an RGB image, find the points in the image that are white, and get the cartesian coordinates of those points in the image. I've gotten most of the way there, but when I try to plot the cartesian coordinates, I get a vertically tiled image (i.e. 5 overlapped copies of what I should see). Anyone know what could be causing this?
,
Code: (JPG comes in as 2448 x x3264 x 3 uint8)
I = imread('IMG_0245.JPG');
imshow(I); % display unaltered image
% Convert image to grayscale
I = rgb2gray(I);
% Convert image to binary (black/white)
I = im2bw(I, 0.9);
% Generate cartesian coordinates of image
imageSize = size(I);
[x, y] = meshgrid( 1:imageSize(1), 1:imageSize(2) );
PerspectiveImage = [x(:), y(:), I(:)];
% Get indices of white points only
whiteIndices = find(PerspectiveImage(:,3));
figure; plot( PerspectiveImage(whiteIndices, 1), PerspectiveImage(whiteIndices, 2),'.');
% Flip vertically to correct indexing vs. plotting issue
axis ij
Very simple. You're declaring your meshgrid wrong. It should be:
[x, y] = meshgrid( 1:imageSize(2), 1:imageSize(1) );
The first parameter denotes the horizontal extents of the 2D grid, and so you want to make this vary for as many columns as you have. Similarly, the second parameter denotes the vertical extents of the 2D grid, and so you want to make this for as many rows as you have.
I had to pre-process some of your image to get some good results because your original image had a large white border surrounding the image. I had to remove this border by removing all pure white pixels. I also read in the image directly from StackOverflow:
I = imread('http://s7.postimg.org/ovb53w4ff/Track_example.jpg');
mask = all(I == 255, 3);
I = bsxfun(#times, I, uint8(~mask));
This was the image I get after doing my pre-processing:
Once I do this and change your meshgrid call, I get this:

Resources