Region mask in the center - Matlab - matlab

In the script below I create a mask based on coordinates and plot them in the original position and also starting at position 0,0. How can I plot another region mask (mask1venter) center?
Code:
xCoord = [354 500 100 363];
yCoord = [309 500 600 360];
if max(xCoord)>max(yCoord)
matrixLength = max(xCoord);
else
matrixLength = max(yCoord);
end
xCoordMin = xCoord-min(xCoord);
yCoordMin = yCoord-min(yCoord);
xCoordCenter = xCoord-round((max(xCoord))/2);
yCoordCenter = yCoord-round((max(yCoord))/2);
mask1 = poly2mask(yCoord,xCoord,matrixLength,matrixLength);
mask1Min = poly2mask(yCoordMin,xCoordMin,matrixLength,matrixLength);
mask1Center = poly2mask(yCoordCenter,xCoordCenter,matrixLength,matrixLength);
imshowpair(mask1,mask1Min)

You can either use subplot, add the two masks or logical OR the two masks
Subplot
figure
subplot(2,2,1)
imshow(mask1)
subplot(2,2,2)
imshow(mask1Min)
subplot(2,2,3)
imshow(mask1Center)
Add the two image
figure
imshowpair(mask1,mask1Min + mask1Center)
Logical OR the two masks
figure
imshowpair(mask1,mask1Min | mask1Center)

Related

loop over array matrix matlab

I am detecting circles in an image. I return circle radii and X,Y of the axis. I know how to crop 1 circle no problem with formula:
X-radius, Y-radius, width=2*r,height=2*r using imcrop.
My problem is when I get returned more than 1 circle.
I get returned circle radii in an array radiiarray.
I get returned circle centers in centarray.
When i disp(centarray), It looks like this:
146.4930 144.4943
610.0317 142.1734
When I check size(centarray) and disp it i get:
2 2
So I understand first column is X and second is Y axis values. So first circle center would be 146,144.
I made a loop that works for only 1 circle. "-------" is where I'm unsure what to use to get:
note: radius = r
1st circle)
X = centarray(1)-r;
Y = centarray(3)-r;
Width =2*r;
Width =2*r;
2nd circle)
X = centarray(2);
Y = centarray(4);
Width =2*r;
Width =2*r;
How would I modify the "------" parts for my code? I also would like that if there are 3+ circles the loop would work as Im getting sometimes up to 9 circles from an image.
B = imread('p5.tif');
centarray = [];
centarray = [centarray,centers];
radiiarray = [];
radiiarray = [radiiarray,radii];
for j=1:length(radiiarray)
x = centarray((------))-radiiarray(j); %X value to crop
y = centarray((------))-radiiarray(j); %Y value to crop
width = 2*radiiarray(j); %WIDTH
height = 2*radiiarray(j); %HEIGHT
K = imcrop(B, [x y width height]);
end
My full code, which doesnt work, as I realized why when i saw the way values are stored...:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DETECT + GET X Y WIDTH HEIGHT OF CIRCLES
I = imread('p5.tif');
subplot(2,2,1);imshow(I);title('Original Image');
%sharpen edges
B = imsharpen(I);
subplot(2,2,2);imshow(B);title('sharpened edges');
%find circles
Img = im2bw(B(:,:,3));
minRad = 20;
maxRad = 90;
[centers, radii] = imfindcircles(Img, [minRad maxRad], ...
'ObjectPolarity','bright','sensitivity',0.84);
imagesc(Img);
viscircles(centers, radii,'Color','green');
%nuber of circles found
%arrays to store values for radii and centers
centarray = [];
centarray = [centarray,centers];
radiiarray = [];
radiiarray = [radiiarray,radii];
sc = size(centarray);
disp(sc)
disp(centarray)
disp(radiiarray)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%CROP USING VALUE FROM ARRAYS NUMBER OF TIMES THERE ARE CENTERS(number of
%circles)
for j=1:length(radiiarray)
x = centarray((2*j)-1)-radiiarray(j); %X value to crop
y = centarray((2*j))-radiiarray(j); %Y value to crop
width = 2*radiiarray(j); %WIDTH
height = 2*radiiarray(j); %HEIGHT
disp(x)
disp(y)
disp(centarray)
%crop using values
K = imcrop(B, [x y width height]);
%togray
gray = rgb2gray(K);
subplot(2,2,3);imshow(K);title('cropped before bw');
Icorrected = imtophat(gray, strel('disk', 15));
%to black and white
black = im2bw(Icorrected);
subplot(2,2,4);imshow(black);title('sharpened edges');
%read
results = ocr(black);
number = results.Text;
%display value
disp(number)
end
Any help on how to create this kind of loop is appreciated as I just have no more ideas or cant find answer to this..
EDIT
SOLUTION
Hi, answer is to treat matrix as 2 dimensional.
for j=1:length(radiiarray)
x=centarray(j,1)
y=centarray(j,2)
width = radiiarray(j)
height = radiiarray(j)
end
as j increases values update correctly now.
answer is to treat matrix as 2 dimensional.
for j=1:length(radiiarray)
x=centarray(j,1)
y=centarray(j,2)
width = radiiarray(j)
height = radiiarray(j)
end
as j increases values update correctly now.
Thanks for #beaker for his comment! Thats why I figured it out

How to crop out a detected circle as a square?

I have detected a circle as shown below:
As later I want to detect what speed limit is in the detected sign, how do I crop it out so that I am left with an image like below?
When program finishes it, it shows me where the center is and the radii in terminal.
centers =
248.4873 170.4811
radii =
24.5024
I know how to use imcrop but how do I use the values that are returned instead of writing in them myself, as there might be more than 1 circle detected?
Code:
I = imread('p1.tif');
subplot(3,3,1); imshow(I); title('Original Image');
%sharpen edges
B = imsharpen(I);
subplot(3,3,2); imshow(B); title('sharpened edges');
%find circles
Img = im2bw(B(:,:,3));
minRad = 20;
maxRad = 90;
[centers, radii] = imfindcircles(Img, [minRad maxRad], ...
'ObjectPolarity','bright','sensitivity',0.87)
imagesc(Img);
viscircles(centers, radii,'Color','green');
Assuming you have one centre and one radius. This should do it
rect = [centers(1)-radii,centers(2)-radii,2*radii,2*radii]
I2 = imcrop(I,rect)
For multiple circles you can do this process for each of the circle returned in a loop.

Find a nearly circular band of bright pixels in this image

This is the problem I have: I have an image as shown below. I want to detect the circular region which I have marked with a red line for display here (that particular bright ring).
Initially, this is what I do for now: (MATLAB)
binaryImage = imdilate(binaryImage,strel('disk',5));
binaryImage = imfill(binaryImage, 'holes'); % Fill holes.
binaryImage = bwareaopen(binaryImage, 20000); % Remove small blobs.
binaryImage = imerode(binaryImage,strel('disk',300));
out = binaryImage;
img_display = immultiply(binaryImage,rgb2gray(J1));
figure, imshow(img_display);
The output seems to be cut on one of the parts of the object (for a different image as input, not the one displayed above). I want an output in such a way that it is symmetric (its not always a perfect circle, when it is rotated).
I want to strictly avoid im2bw since as soon as I binarize, I lose a lot of information about the shape.
This is what I was thinking of:
I can detect the outer most circular (almost circular) contour of the image (shown in yellow). From this, I can find out the centroid and maybe find a circle which has a radius of 50% (to locate the region shown in red). But this won't be exactly symmetric since the object is slightly tilted. How can I tackle this issue?
I have attached another image where object is slightly tilted here
I'd try messing around with the 'log' filter. The region you want is essentially low values of the 2nd order derivative (i.e. where the slope is decreasing), and you can detect these regions by using a log filter and finding negative values. Here's a very basic outline of what you can do, and then tweak it to your needs.
img = im2double(rgb2gray(imread('wheel.png')));
img = imresize(img, 0.25, 'bicubic');
filt_img = imfilter(img, fspecial('log',31,5));
bin_img = filt_img < 0;
subplot(2,2,1);
imshow(filt_img,[]);
% Get regionprops
rp = regionprops(bin_img,'EulerNumber','Eccentricity','Area','PixelIdxList','PixelList');
rp = rp([rp.EulerNumber] == 0 & [rp.Eccentricity] < 0.5 & [rp.Area] > 2000);
bin_img(:) = false;
bin_img(vertcat(rp.PixelIdxList)) = true;
subplot(2,2,2);
imshow(bin_img,[]);
bin_img(:) = false;
bin_img(rp(1).PixelIdxList) = true;
bin_img = imfill(bin_img,'holes');
img_new = img;
img_new(~bin_img) = 0;
subplot(2,2,3);
imshow(img_new,[]);
bin_img(:) = false;
bin_img(rp(2).PixelIdxList) = true;
bin_img = imfill(bin_img,'holes');
img_new = img;
img_new(~bin_img) = 0;
subplot(2,2,4);
imshow(img_new,[]);
Output:

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 provide region of interest (ROI) for edge detection and corner detection in Matlab?

I have a movie file, in which I am interested in recording the movement of a point; center of a circular feature to be specific. I am trying to perform this using edge detection and corner detection techniques in Matlab.
To perform this, how do I specify a region of interest in the video? Is subplot a good idea?
I was trying to perform this using the binary masks as below,
hVideoSrc = vision.VideoFileReader('video.avi','ImageColorSpace', 'Intensity');
hEdge = vision.EdgeDetector('Method', 'Prewitt','ThresholdSource', 'Property','Threshold', 15/256, 'EdgeThinning', true);
hAB = vision.AlphaBlender('Operation', 'Highlight selected pixels');
WindowSize = [190 150];
hVideoOrig = vision.VideoPlayer('Name', 'Original');
hVideoOrig.Position = [10 hVideoOrig.Position(2) WindowSize];
hVideoEdges = vision.VideoPlayer('Name', 'Edges');
hVideoEdges.Position = [210 hVideoOrig.Position(2) WindowSize];
hVideoOverlay = vision.VideoPlayer('Name', 'Overlay');
hVideoOverlay.Position = [410 hVideoOrig.Position(2) WindowSize];
c = [123 123 170 170];
r = [160 210 210 160];
m = 480; % height of pout image
n = 720; % width of pout image
BW = ~poly2mask(c,r,m,n);
while ~isDone(hVideoSrc)
dummy_frame = step(hVideoSrc) > 0.5; % Read input video
frame = dummy_frame-BW;
edges = step(hEdge, frame);
composite = step(hAB, frame, edges); % AlphaBlender
step(hVideoOrig, frame); % Display original
step(hVideoEdges, edges); % Display edges
step(hVideoOverlay, composite); % Display edges overlayed
end
release(hVideoSrc);
but it turns out that the mask applied on frame is good only for the original video. The edge detection algorithm detects the edges those are masked by binary mask. How can I mask other features permanently and perform edge detection?
Is this what you mean?
BW = poly2mask(c,r,m,n);
frame = dummy_frame .* BW;