MATLAB: Display image inside circle - matlab

As part of a circle recognition program, I have a background image with a geometrical circle with known coordinates and radius. I want the inside part of the circle filled by an image and the outside left alone. My best idea is some sort of circular mask, but I am not sure this is the best approach. Any suggestions?
X = imread('X.jpg'); % Background image jpg
Y = imread('Y.jpg'); % Filling image jpg
cent = [100,100]; % Center of circle
rad = 20; % Circle radius
% Fill circle ?
...
I have not provided the extended code, due to confidentiality.

I think the hard part was done by whomever authored this: http://matlab.wikia.com/wiki/FAQ#How_do_I_create_a_circle.3F
Assumptions:
I'm assuming you're not going to specify points that are out of range of the image (i.e. I'm not adding validation here).
I use the background image to relate the "center" of your circle to the coordinates.
I'm assuming radius is in pixels.
I didn't create a background image with a circle of known radius because I don't think that's necessary to create the filling effect you're looking for (unless I'm missing something).
Code:
X = imread('rdel_x.png'); % Background image jpg (I used a random image but this can be your blank + geometric circle)
Y = imread('rdel_y.png'); % Filling image jpg
cent = [100,150]; % Center of circle
rad = 70; % Circle radius
% make a mesh grid to provide coords for the circle (mask)
% taken from http://matlab.wikia.com/wiki/FAQ#How_do_I_create_a_circle.3F
[columnsInImage rowsInImage] = meshgrid(1:size(X,2), 1:size(X,1));
% circle points in pixels:
circlePixels = (rowsInImage - cent(1)).^2 ...
+ (columnsInImage - cent(2)).^2 <= rad.^2;
circlePixels3d=repmat(circlePixels,[1 1 3]); % turn into 3 channel (assuming X and Y are RGB)
X((circlePixels3d)) = Y((circlePixels3d)); % assign the filling image pixels to the background image for pixels where it's the desired circle
imagesc(X);
axis image off
Result: from left to right, background image, filling image, result from above code.
Edit: you might not even need the background image if everything is encapsulated in your coordinates. e.g. try appending this to the above code...
Z=zeros(size(X),'uint8'); % same size as your background
Z(circlePixels3d) = Y(circlePixels3d);
figure; % new fig
imagesc(Z);
axis image off

Related

Finding area in image with maximum variation of pixels

I am struggling with some algorithm to extract the region from an image which has the maximum change in pixels. I got the following image after preprocessing.
I did following steps of pre-processing
x = imread('test2.jpg');
gray_x = rgb2gray(x);
I = medfilt2(gray_x,[3 3]);
gray_x = I;
%%
canny_x = edge(gray_x,'canny',0.3);
figure,imshow(canny_x);
%%
s = strel('disk',3);
si = imdilate(canny_x,s);
%figure5
figure; imshow(si);
se = imerode(canny_x,s);title('dilation');
%figure6
figure; imshow(se);title('Erodsion');
I = imsubtract(si,se);
%figure7
figure; imshow(I);
Basically what I am struggling for, is to make weapon detection system using Image processing. I want to localize possible area's to be weapon so that I could feed them to my classifier to identify if it is a weapon or not. Any suggestions? Thank you
A possible solution could be:
Find corner points in the image (Harris corner points, etc)
Set value of all the corner points to white while remaining image will be black
Take a rectangular window and traverse it over the whole image
sum all the white pixels in that rectangular window
select that region whose sum is maximum of all regions

How to plot boundary and centroids on video frames called inside step() function

I am calling some images inside a for loop and then doing some processing on those images. After that, I am using the step function to display those frames and their masks inside a video player. How can I add a boundary to an object inside the mask image? Also, how can I make the boundary thicker and plot the centroids of each blob in the mask in the mask image? Below is the rough sketch of the code.
videoPlayer = vision.VideoPlayer();
maskPlayer = vision.VideoPlayer();
for ii = 1:nfiles
filenameii = [............]
frame= imread(filenameii);
mask = dOB(frame,BackgroundImg);
% some processing on the images
mask= bwareaopen(mask,27);
boundaries = bwboundaries(mask,'noholes');
B=boundaries{1};
Centroid = regionprops(mask,'centroid');
Centroids = cat(1, Centroid.Centroid);
plot(B(:,2),B(:,1),'g','LineWidth',3);
plot(Centroids(:,1), Centroids(:,2), 'r+', 'MarkerSize', 10); step(videoPlayer,frame);
step(maskPlayer, mask);
P.S: I know how to display it on a figure using hold on but I would like this done directly on the image before displaying it in the video player. Any guidance would be appreciated.
Simply paint the pixels on the mask first before displaying it in the video player. What you have does work, but it will plot the boundary inside the figure for the mask player. Therefore, take your boundaries that you detected from bwboundaries, create linear indices from these coordinates and set the values in your image to white. What may be even simpler is to take your mask that you detected and use bwperim to automatically produce a mask that contains the boundaries of the blobs. I also see that you are filling in the holes of the mask, so you can use imfill directly on the output of your post-processing so that it gives you an image instead of coordinates. You would then use this mask to directly index into your image and set the coordinates of the boundaries of the blob to your desired colour. If you desire to make the perimeter thicker, a simple image dilation with imdilate using the appropriately sized square structuring element will help. Simply define the size of the neighbourhood of this structuring element to be the thickness of the perimeter that you desire. Finally, if you want to insert the centroids into the mask and since you have the MATLAB Computer Vision System Toolbox, use the insertMarker function so that you can use a set of points for each centroid and put them directly in the image. However, you must be sure to change the mask from a logical to a data type more suitable for images. uint8 should work. Therefore, cast the image to this type then multiply all nonzero values by 255 to ensure the white colours are maintained in the mask. With insertMarker, you want to insert red pluses with a size of 10 so we need to make sure we call insertMarker to reflect that. Also, because you want to have a colour image you will have to make your mask artificially colour and to do this painting individually for each plane for the colour that you want. Since you want green, this corresponds to the RGB value of (0,255,0).
Therefore, I have modified your code so that it does this. In addition, I've calculated the centroids of the filled mask instead of the original. We wouldn't want to falsely report the centroids of objects with gaps... unless that's what you're aiming for, but let's assume you're not:
videoPlayer = vision.VideoPlayer();
maskPlayer = vision.VideoPlayer();
% New - Specify colour you want
clr = [0 255 0]; % Default is green
% New - Define thickness of the boundaries in pixels.
thickness = 3;
% New - Create structuring element
se = strel('square', thickness);
for ii = 1:nfiles
filenameii = [............]
frame = imread(filenameii);
mask = dOB(frame, BackgroundImg);
% some processing on the images
mask = bwareaopen(mask,27);
%boundaries = bwboundaries(mask,'noholes');
%B=boundaries{1};
% New code - fill in the holes
mask = imfill(mask, 'holes');
Centroid = regionprops(mask,'centroid');
% New code - Create a boundary mask
mask_p = bwperim(mask, 8);
% New code - Make the boundaries thicker
mask_p = imdilate(mask_p, se);
% New code - create a colour image out of the mask
[red, green, blue] = deal(255*uint8(mask));
% Paint the perimeter of the blobs in the desired colour
red(mask_p) = clr(1); green(mask_p) = clr(2); blue(mask_p) = clr(3);
Centroids = cat(1, Centroid.Centroid);
%plot(B(:,2),B(:,1),'g','LineWidth',3);
%plot(Centroids(:,1), Centroids(:,2), 'r+', 'MarkerSize', 10);
% New - Make mask into RGB image for marker painting and to
% show to the user
mask_p = cat(3, red, green, blue);
% New - Insert the centroids directly in the mask image
mask_p = insertMarker(mask_p, Centroids, '+', 'color', 'r', 'size', 10);
step(videoPlayer, frame);
% New - Show new mask in the player
step(maskPlayer, mask_p);
end

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;

Quantifying pixels from a list of coordinates

I have a list of coordinates, which are generated from another program, and I have an image.
I'd like to load those coordinates (making circular regions of interest (ROIs) with a diameter of 3 pixels) onto my image, and extract the intensity of those pixels.
I can load/impose the coordinates on to the image by using;
imshow(file);
hold on
scatter(xCoords, yCoords, 'g')
But can not extract the intensity.
Can you guys point me in the right direction?
I am not sure what you mean by a circle with 3 pixels diameter since you are in a square grid (as mentioned by Ander Biguri). But you could use fspecial to create a disk filter and then normalize. Something like this:
r = 1.5; % for diameter = 3
h = fspecial('disk', r);
h = h/h(ceil(r),ceil(r));
You can use it as a mask to get the intensities at the given region of the image.
im = imread(file);
ROI = im(xCoord-1:xCoord+1; yCoord-1:yCoord+1);
I = ROI.*h;

Finding the area of the black spots in a circle MATLAB

Is it possible to find the area of the black pixelation of an area within a circle? in other words I want to find the number of pixels (the area) of the RGB 0,0,0 (black pixels) within the circle. I do not want the areas of the white pixels (1,1,1) within the circle. I also have a radius of the circle if that helps. Here is the image:
Here is the code:
BW2= H(:,:) <0.45 ;%& V(:,:)<0.1;
aa=strel('disk',5);
closeBW = imclose(BW2,aa);
figure, imshow(closeBW)
imshow(closeBW)
viscircles([MYY1 MYX1], round(MYR2/2))
MYY1,MYX2, and the other values are calculated by my program. How can I find the area of the black pixelation in my circle?
Here is an idea:
1) Calculate the total # of black pixels in your original image (let's call it A).
2) Duplicate that image (let's call it B) and replace all pixels inside the circle with white. To do that, create a binary mask. (see below)
3) Calculate the total # of black pixels in that image (i.e. B).
4) Subtract both values. That should give you the number of black pixels within the circle.
Sample code: I used a dummy image I had on my computer and created a logical mask with the createMask method from imellipse. That seems complicated but in your case since you have the center position and radius of the circle you can create directly your mask like I did or by looking at this question/answer.
Once the mask is created, use find to get the linear indices of the white pixels of the mask (i.e. all of it) to replace the pixels in the circle of your original image with white pixels, which you use to calculate the difference in black pixels.
clc;clear;close all
A = im2bw(imread('TestCircle.png'));
imshow(A)
Center = [160 120];
Radius = 60;
%// In your case:
% Center = [MYY1 MYX1];
% Radius = round(MYR2/2);
%// Get sum in original image
TotalBlack_A = sum(sum(~A))
e = imellipse(gca, [Center(1) Center(2) Radius Radius]);
%// Create the mask
ROI = createMask(e);
%// Find white pixels
white_id = find(ROI);
%// Duplicate original image
B = A;
%// Replace only those pixels in the ROI with white
B(white_id) = 1;
%// Get new sum
NewBlack_B = sum(sum(~B))
%// Result!
BlackInRoi = TotalBlack_A - NewBlack_B
In this case I get this output:
TotalBlack_A =
158852
NewBlack_B =
156799
BlackInRoi =
2053
For this input image: