how to stretch the first left, right, top, and bottom row/column of image? - matlab

I have a satellite image and I want to show an example of multi-scale.
so what I did is, add zeros (black pixels) around the image and put the image in the centre. now how can I fill the zeros from the first left, right, top, and bottom pixel row/column?
Matlab code:
img=imread ('example.jpg');
padcam = padarray(img,[1000 1000],'both');
EDIT:
Maybe it is easy explain from this image. Is this image what I want is to repeat the sea part in such a ways at the black area that it looks like we have large empty sea and small ships at the centre. That's why I have made red lines that I want to repeat/make copy/extend first left, right, top, and bottom pixel row/column so that make image at centre and black will be converted to pixels values of first left, right, top, and bottom pixel row/column.

I don't know if this is what you have meant...
Instead of fill zeros, start from the highest resolution, and place lower resolution images at the center of each other.
Here is my code sample (you may use a for loop instead):
I0 = imread('peppers.png');
I0 = padarray(I0,[16 16],'both'); %I0 - full resolution.
I1 = imresize(I0, 0.5); %I1 - half resolution.
I2 = imresize(I0, 0.25); %I2 - quarter resolution.
J = I0;
%Place I1 at the center of J.
J(1+(end-size(I1,1))/2:(end+size(I1,1))/2, 1+(end-size(I1,2))/2:(end+size(I1,2))/2, :) = I1;
%Place I2 at the center of J.
J(1+(end-size(I2,1))/2:(end+size(I2,1))/2, 1+(end-size(I2,2))/2:(end+size(I2,2))/2, :) = I2;
figure;imshow(J);
Result:
Check the following:
The example is basted on Matlab documentation of imtransform
I = imresize(imread('peppers.png'), 0.5);
A = [1, 0, 0; 0, 1, 0; 0, 0, 1];
T = maketform('affine', A);
R = makeresampler({'cubic', 'nearest'}, 'replicate');
J = imtransform(I, T, R, 'XData', [-size(I,2), size(I,2)*2], 'YData', [-size(I,1), size(I,1)*2]);
figure;imshow(J);
Result:

I think you are looking for 'replicate' padding option:
padcam = padarray(img,[1000 1000],'both', 'replicate');
resulting with:
If you are looking for smoother result, consider using regionfill.

Related

Detect endpoints of a line

I want to detect the points shown in the image below:
I have done this so far:
[X,map] = rgb2ind(img,0.0);
img = ind2gray(X,map); % Convert indexed to grayscale
level = graythresh(img); % Compute an appropriate threshold
img_bw = im2bw(img,level);% Convert grayscale to binary
mask = zeros(size(img_bw));
mask(2:end-2,2:end-2) = 1;
img_bw(mask<1) = 1;
%invert image
img_inv =1-img_bw;
% find blobs
img_blobs = bwmorph(img_inv,'majority',10);
% figure, imshow(img_blobs);
[rows, columns] = size(img_blobs);
for col = 1 : columns
thisColumn = img_blobs(:, col);
topRow = find(thisColumn, 1, 'first');
bottomRow = find(thisColumn, 1, 'last');
img_blobs(topRow : bottomRow, col) = true;
end
inverted = imcomplement(img_blobs);
ed = edge(inverted,'canny');
figure, imshow(ed),title('inverted');
Now how to proceed to get the coordinates of the desired position?
The top point is obviously the white pixel with the highest ordinate, which is easily obtained.
The bottom point is not so well defined. What you can do is
follow the peak edges until you reach a local minimum, on the left and on the right. That gives you a line segment, which you can intersect with the vertical through the top point.
if you know a the peak width, try every pixel on the vertical through the top point, downward, and stop until it has no left nor right neighbors at a distance equal to the peak with.
as above, but stop when the distance between the left and right neighbors exceeds a threshold.
In this particular case, you could consider using houghlines in matlab. Setting the required Theta and MinLength parameter values, you should be able to get the two vertical lines parallel to your peak. You can use the end points of the vertical lines, to get the point at the bottom.
Here is a sample code.
[H,theta,rho] = hough(bw,'Theta',5:1:30);%This is the angle range
P = houghpeaks(H,500,'NHoodSize',[11 11]);
lines = houghlines(bw,theta,rho,P,'FillGap',10,'MinLength',300);
Here is a complete description of how houghlines actually works.

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 manipulate edges

I'm working on an image processing project. I have a grayscale image and detected edges with Canny edge detection. Now I would like to manipulate the result by filtering the unnecessary edges. I would like to keep the edges which are close to horizontal and delete edges which are close to vertical.
How can I delete the close to vertical edges?
One option is to use half of a Sobel operator. The full algorithm finds horizontal and vertical edges, then combines them. You are only interested in horizontal edges, so just compute that part (which is Gy in the Wikipedia article).
You may also want to threshold the result to get a black and white image instead of shades of gray.
You could apply this technique to the original grayscale image or the result of the Canny edge detection.
It depends on how cost-intensive it is allowed to be. One easy way to do would be:
(1) Convolute your image with Sobel-Filters (gives Dx, Dy).
For each canny-edge-pixel:
(2) Normalize (Dx, Dy), s.t. in every pixel you have the direction of your edge.
(3) Compute the inner products with the direction you want to remove (in your case (0,1)).
(4) If the absolut value of the inner product is smaller than some threshold remove the pixel.
Example:
img = ...;
canny_img = ...;
removeDir = [0;1];
% convolute with sobel masks
sobelX = [1, 0, -1; 2, 0, -2; 1, 0, -1];
sobelY = sobelX';
DxImg = conv2(img,sobelX,'same');
DyImg = conv2(img,sobelY,'same');
% for each canny-edge-pixel:
for lin = 1:size(img,1) % <-> y
for col = 1:size(img,2) % <-> x
if canny_img(lin,col)
% normalize direction
normDir = [DxImg(lin,col); DyImg(lin,col)];
normDir = normDir / norm(normDir,2);
% inner product
innerP = normDir' * removeDir;
% remove edge?
if abs(innerP) < cos(45/180*pi) % 45° threshold
canny_img(lin,col) = 0;
end
end
end
end
You can optimize it a lot due to your requirements.

Stretching an ellipse in an image to form a circle

I want to stretch an elliptical object in an image until it forms a circle. My program currently inputs an image with an elliptical object (eg. coin at an angle), thresholds and binarizes it, isolates the region of interest using edge-detect/bwboundaries(), and performs regionprops() to calculate major/minor axis lengths.
Essentially, I want to use the 'MajorAxisLength' as the diameter and stretch the object on the minor axis to form a circle. Any suggestions on how I should approach this would be greatly appreciated. I have appended some code for your perusal (unfortunately I don't have enough reputation to upload an image, the binarized image looks like a white ellipse on a black background).
EDIT: I'd also like to apply this technique to the gray-scale version of the image, to examine what the stretch looks like.
code snippet:
rgbImage = imread(fullFileName);
redChannel = rgbImage(:, :, 1);
binaryImage = redChannel < 90;
labeledImage = bwlabel(binaryImage);
area_measurements = regionprops(labeledImage,'Area');
allAreas = [area_measurements.Area];
biggestBlobIndex = find(allAreas == max(allAreas));
keeperBlobsImage = ismember(labeledImage, biggestBlobIndex);
measurements = regionprops(keeperBlobsImage,'Area','MajorAxisLength','MinorAxisLength')
You know the diameter of the circle and you know the center is the location where the major and minor axes intersect. Thus, just compute the radius r from the diameter, and for every pixel in your image, check to see if that pixel's Euclidean distance from the cirlce's center is less than r. If so, color the pixel white. Otherwise, leave it alone.
[M,N] = size(redChannel);
new_image = zeros(M,N);
for ii=1:M
for jj=1:N
if( sqrt((jj-center_x)^2 + (ii-center_y)^2) <= radius )
new_image(ii,jj) = 1.0;
end
end
end
This can probably be optimzed by using the meshgrid function combined with logical indices to avoid the loops.
I finally managed to figure out the transform required thanks to a lot of help on the matlab forums. I thought I'd post it here, in case anyone else needed it.
stats = regionprops(keeperBlobsImage, 'MajorAxisLength','MinorAxisLength','Centroid','Orientation');
alpha = pi/180 * stats(1).Orientation;
Q = [cos(alpha), -sin(alpha); sin(alpha), cos(alpha)];
x0 = stats(1).Centroid.';
a = stats(1).MajorAxisLength;
b = stats(1).MinorAxisLength;
S = diag([1, a/b]);
C = Q*S*Q';
d = (eye(2) - C)*x0;
tform = maketform('affine', [C d; 0 0 1]');
Im2 = imtransform(redChannel, tform);
subplot(2, 3, 5);
imshow(Im2);

Matlab fill shapes by white

As you see, I have shapes and their white boundaries. I want to fill the shapes in white color.
The input is:
I would like to get this output:
Can anybody help me please with this code? it doesn't change the black ellipses to white.
Thanks alot :]]
I = imread('untitled4.bmp');
Ibw = im2bw(I);
CC = bwconncomp(Ibw); %Ibw is my binary image
stats = regionprops(CC,'pixellist');
% pass all over the stats
for i=1:length(stats),
size = length(stats(i).PixelList);
% check only the relevant stats (the black ellipses)
if size >150 && size < 600
% fill the black pixel by white
x = round(mean(stats(i).PixelList(:,2)));
y = round(mean(stats(i).PixelList(:,1)));
Ibw = imfill(Ibw, [x, y]);
end;
end;
imshow(Ibw);
Your code can be improved and simplified as follows. First, negating Ibw and using BWCONNCOMP to find 4-connected components will give you indices for each black region. Second, sorting the connected regions by the number of pixels in them and choosing all but the largest two will give you indices for all the smaller circular regions. Finally, the linear indices of these smaller regions can be collected and used to fill in the regions with white. Here's the code (quite a bit shorter and not requiring any loops):
I = imread('untitled4.bmp');
Ibw = im2bw(I);
CC = bwconncomp(~Ibw, 4);
[~, sortIndex] = sort(cellfun('prodofsize', CC.PixelIdxList));
Ifilled = Ibw;
Ifilled(vertcat(CC.PixelIdxList{sortIndex(1:end-2)})) = true;
imshow(Ifilled);
And here's the resulting image:
If your images are all black&white, and you have the image processing toolkit, then this looks like what you need:
http://www.mathworks.co.uk/help/toolbox/images/ref/imfill.html
Something like:
imfill(image, [startX, startY])
where startX, startY is a pixel in the area that you want to fill.