Image blurring results in a sharp edge - matlab

I'm doing some processing with MATLAB on an RGB image.
I had to obtain a circular blurring like in the image below:
obtained through this code:
A = imread('lena .bmp');
I = rgb2gray(A);
[rNum,cNum,~] = size(I);
%center and radius of the circular mask
x1 = 256.5;
y1 = 256.5;
radius = 100;
%circular mask creation
[x,y] = ndgrid((1:rNum)-y1,(1:cNum)-x1);
mask = (x.^2 + y.^2)<radius^2;
h = ones(30,30)/900; %gaussian filter
J = roifilt2(h,I,mask); %apply the filter at the mask
%filtering plane - by - plane in order to apply the circular blurred mask
%to the RGB image
filtered_im = zeros(size(A));
filtered_im(:,:,1) = roifilt2(h, A(:,:,1), mask);
filtered_im(:,:,2) = roifilt2(h, A(:,:,2), mask);
filtered_im(:,:,3) = roifilt2(h, A(:,:,3), mask);
filtered_im = uint8(filtered_im);
figure
imshow(filtered_im)
title('Circular blurring RGB image');
The effect obtained, anyway, is too artificial because the transition between the blurred circular mask and the rest of the image is too sharp. Is there a possibility to make this transition more faded in order to obtain a more natural effect?

You can use a weighted average of both the original image and the modified one, using as weights a mask based on the distance to the center of the circle.
The original one would have more weight in the external part of the circle, and the modified image in the center. This could create a transition in the blurring.

Related

Get regions within black border of image

I begin with the following image:
I perform local thresholding by comparing a pixel to its neighborhood mean. I also crop out the white border surrounding the image after this local thresholding with the following code:
I = imread('img_path');
N = 21;
localMean = conv2(double(I), double(1/(N^2) * ones(N)), 'same');
BW = I > localMean;
borderSize = ceil(double(N) / 2);
R = [borderSize, borderSize, size(BW, 2) - 2*borderSize, size(BW, 1) - 2*borderSize];
BW = imcrop(BW, R);
This leaves me with the following image:
As you can see, there is a clear black border surrounding each of the segmented cells. How do I go about removing all things in this image OTHER than those regions within the black border?
If this is not possible, then are there any other techniques I should take a look at that might make give my local thresholding less noise?
Any help is appreciated.
you can use Otsu's thresholding (graythresh) and morphological operations:
im = im2double(imread('cells.png'));
% otsu thresholding
t = graythresh(im);
bw = im > t;
% morphological open to remove small noise
bw = imopen(bw,strel('disk',5,0));
% fill holes to form solid objects
bw = imfill(bw,'holes');
% show
imshow(bw)

how to perform image enhancement over a small region of an image?

I would like to enhance a portion of the image. I would like to enhance the regions within rectangular region esp on the green rectangle region
You can use imcrop.
[I2 rect] = imcrop(I)
This will ask you to draw a rectangle and rect will thus contain the coordinates of that rectangle. I2 contains the cropped image and you can then apply any function you would like on that matrix.
Using a function like ginput you can select a point on an image, and with having a width and height values of a rectangle, you can crop a rectangle from your image. Then you can use any function such as imadjust to enhance your cropped part.
a= 100; % height
b= 100; % width
I = imread('myimage.png'); % read the image file
figure;imagesc(I); % plot the image
[x,y] = ginput(1); % select a point
I2 = I(:,:,1); %
Ic = imcrop(I2,[x-a/2 y-b/2 a b]); % crop a rectangle around the selected point
J = imadjust(Ic); % adjust the contrast
If you want to be able to select a rectangle, you can use the following command:
imshow('myimage.png');
rect = getrect;

Can we rotate an image in MATLAB filled with background color of original image?

By default, MATLAB function imrotate rotate image with black color filled in rotated portion. See this, http://in.mathworks.com/help/examples/images_product/RotationFitgeotransExample_02.png
We can have rotated image with white background also.
Question is, Can we rotate an image (with or without using imrotate) filled with background of original image?
Specific to my problem: Colored image with very small angle of rotation (<=5 deg.)
Here's a naive approach, where we simply apply the same rotation to a mask and take only the parts of the rotated image, that correspond to the transformed mask. Then we just superimpose these pixels on the original image.
I ignore possible blending on the boundary.
A = imread('cameraman.tif');
angle = 10;
T = #(I) imrotate(I,angle,'bilinear','crop');
%// Apply transformation
TA = T(A);
mask = T(ones(size(A)))==1;
A(mask) = TA(mask);
%%// Show image
imshow(A);
You can use padarray() function with 'replicate' and 'both' option to interpolate your image. Then you can use imrotate() function.
In the code below, I've used ceil(size(im)/2) as pad size; but you may want bigger pad size to eliminate the black part. Also I've used s and S( writing imR(S(1)-s(1):S(1)+s(1), S(2)-s(2):S(2)+s(2), :)) to crop the image where you can extract bigger part of image just expanding boundary of index I used below for imR.
Try this:
im = imread('cameraman.tif'); %// You can also read a color image
s = ceil(size(im)/2);
imP = padarray(im, s(1:2), 'replicate', 'both');
imR = imrotate(imP, 45);
S = ceil(size(imR)/2);
imF = imR(S(1)-s(1):S(1)+s(1)-1, S(2)-s(2):S(2)+s(2)-1, :); %// Final form
figure,
subplot(1, 2, 1)
imshow(im);
title('Original Image')
subplot(1, 2, 2)
imshow(imF);
title('Rotated Image')
This gives the output below:
Not so good but better than black thing..

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);

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.