How to crop face section from an image with given corner points. MATLAB - matlab

I want to crop a face section from an image but face image is not straight/vertically aligned. I am having four pixel points to crop it..
Problem is that,
If i will transform image first the pixel points cannot be used thereafter to crop the facial section out of it.
Or in other case I am not having an exact bounding box to crop the image directly using imcrop as facial sections are somewhat tilted left or right.
The four pixel points are at forehead , chin and ears of the face to be cropped.

You should look at poly2mask. This function produces a mask image from your given x and y coordinates:
BW = poly2mask(x,y,m,n);
where x and y are your coordinates, and the produced BW image is m by n. You can then use this BW image to mask your original image I by doing
I(~BW) = 0;
If you actually want to crop, then you could get the bounding box (either through the regionprops function or the code below):
x1 = round(min(x));
y1 = round(min(y));
x2 = round(max(x));
y2 = round(max(y));
and then crop the image after you have used the BW as a mask.
I2 = I(x1:x2,y1:y2);
Hope that helps.

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

Geometrical transformation of a polygon to a higher resolution image

I'm trying to resize and reposition a ROI (region of interest) correctly from a low resolution image (256x256) to a higher resolution image (512x512). It should also be mentioned that the two images cover different field of view - the low and high resolution image have 330mm x 330mm and 180mm x 180mm FoV, respectively.
What I've got at my disposal are:
Physical reference point (in mm) in the 256x256 and 512x512 image, which are refpoint_lowres=(-164.424,-194.462) and refpoint_highres=(-94.3052,-110.923). The reference points are located in the top left pixel (1,1) in their respective images.
Pixel coordinates of the ROI in the 256x256 image (named pxX and pxY). These coordinates are positioned relative to the reference point of the lower resolution image, refpoint_lowres=(-164.424,-194.462).
Pixel spacing for the 256x256 and 512x512 image, which are 0.7757 pixel/mm and 2.8444 pixel/mm respectively.
How can I rescale and reposition the ROI (the binary mask) to correct pixel location in the 512x512 image? Many thanks in advance!!
Attempt
% This gives correctly placed and scaled binary array in the 256x256 image
mask_lowres = double(poly2mask(pxX, pxY, 256., 256.));
% Compute translational shift in pixel
mmShift = refpoint_lowres - refpoint_highres;
pxShift = abs(mmShift./pixspacing_highres)
% This produces a binary array that is only positioned correctly in the
% 512x512 image, but it is not upscaled correctly...(?)
mask_highres = double(poly2mask(pxX + pxShift(1), pxY + pxShift(2), 512.,
512.));
So you have coordinates pxX, and pxY in pixels with respect to the low-resolution image. You can transform these coordinates to real-world coordinates:
pxX_rw = pxX / 0.7757 - 164.424;
pxY_rw = pxY / 0.7757 - 194.462;
Next you can transform these coordinates to high-res coordinates:
pxX_hr = (pxX_rw - 94.3052) * 2.8444;
pxY_hr = (pxY_rw - 110.923) * 2.8444;
Since the original coordinates fit in the low-res image, but the high-res image is smaller (in physical coordinates) than the low-res one, it is possible that these new coordinates do not fit in the high-res image. If this is the case, cropping the polygon is a non-trivial exercise, it cannot be done by simply moving the vertices to be inside the field of view. MATLAB R2017b introduces the polyshape object type, which you can intersect:
bbox = polyshape([0 0 180 180] - 94.3052, [180 0 0 180] - 110.923);
poly = polyshape(pxX_rw, pxY_rw);
poly = intersect([poly bbox]);
pxX_rw = poly.Vertices(:,1);
pxY_rw = poly.Vertices(:,2);
If you have an earlier version of MATLAB, maybe the easiest solution is to make the field of view larger to draw the polygon, then crop the resulting image to the right size. But this does require some proper calculation to get it right.

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;

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..

MATLAB: Display image inside circle

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