Extract foreground from background in matlab - matlab

I have 2 images. One is background image and other image has same background but with some foreground object. I want to extract foreground object from background. Simple subtraction operation in matlab will not suffice as it subtracts RGB value of background image from that of foreground image (as in below code).
im1 = imread('output/frame-1.jpg')
im2 = imread('output/frame-7.jpg')
%# subtract
deltaImage = im1 - im2;
imshow(deltaImage)
So if background color is white and foreground object is blue, then output (i.e. deltaImage) comes foreground object with orange color with black background. However the output I want is foreground object with blue color (i.e. original color) with black background. How can I get this ? I tried to do it using below code, but output image is incorrect.
im1 = imread('foreground.jpg')
im2 = imread('background.jpg')
[m n k]=size(im2);
deltaImage = zeros(m,n,3);
fprintf('%d %d %d.\n',m,n,k);
for l=1:k
for i=1:m-1
for j=1:n-1
if im1(i:j:l)~=im2(i:j:l)
deltaImage(i,j,l) = im1(i,j,l);
end
end
end
end
imshow(deltaImage)
Background IMAGE
Foreground Image
Output Image (Here I want color of man to be blue)

You can use deltaImage to create a mask (zeros and ones image) that multiplies the foreground. However, note that you will have artifacts associated with lossy image compression (.jpeg). These can be reduced, to some extent, if you use a threshold, like the average difference or a specific value you want. Try this:
im1 = double(imread('~/Downloads/foreground.jpg'));
im2 = double(imread('~/Downloads/background.jpg'));
compute the difference of the averages of the 3 channels
deltaImage = mean(im2,3) - mean(im1,3);
then use the product of the mean by a standard deviation (~3), or uncomment the line below to use a specific threshold, like 128
mask = deltaImage>3*mean(deltaImage(:));
% mask = deltaImage>128;
then assuming all original images are in 8-bit format produce a result also in 8-bit format:
result = uint8(cat(3, im1(:,:,1).*mask, im1(:,:,2).*mask, im1(:,:,3).*mask));
imshow(result)
And this is the result you should get:
Again the weird looking pixels around the main object are artifacts of lossy image compression (.jpeg), you should try working with lossless like .png formats.

Related

How to apply binary mask to remove background from skin lesion colour image

the figure outputted just displays the binary mask image, however I am trying to get just the foreground of the coloured image, with the background being black.
original = imread('originalImage.jpg');
binaryImage = imread('binaryImage.png');
mask = cat(3,binaryImage, binaryImage, binaryImage);
output = mask.*original;
figure,imshow(output);
the binary mask
The original image
The most likely issue is that binary is an image with values of 0 for background and 255 for foreground. Multiplying a color image with values in the range [0,255] by such a mask leads to overflow. Since the input images are uint8, overflow leads to values of 255. Thus, everywhere where the mask is white, you get white colors.
The solution is to convert the images to double:
output = double(mask)/255 .* double(original)/255;
or to truly binarize the mask image:
output = (mask>0) .* original;

separated foreground and background or change the value of background image in Matlab

How should I change the background image color to black or change the RGB values become black color background. I want to take the original leaf image only.
Leaf image
In order to change the background color to black you'll need the following:
calculate the background mask by using a threshold
The threshold can be either find automatically, by using the function graythresh, or manually, by looking at the image histogram.
perform thresholding by using the value from stage 1 in order to find the foreground mask. Also, pick the largest connected component and perform noise cleaning (imclose operation).
calculate the BG from the FG, and zero out the corresponding locations in the original input image.
Code example:
I = imread('YaEwk.jpg');
%converts to hsv colorspace, and takes the 3rd dimension. normlizes it.
im = rgb2hsv(I);
im = mat2gray(im(:,:,3));
%determines a threshold to distinguish between the leaf and its surroundings.
T = graythresh(im);
%defines FG as all the values below the threshold
%Also, keeps just the biggest connected component and perform noise
%reduction.
FG = im < T;
FG = bwareafilt(FG,1);
FG = imclose(FG,strel('disk',2));
%defines the background as the opposite of the foreground
BG = ~FG;
I(repmat(BG,1,1,3)) = 0;
%smooth the output
I(:,:,1) = medfilt2(I(:,:,1));
I(:,:,2) = medfilt2(I(:,:,2));
I(:,:,3) = medfilt2(I(:,:,3));
Result:

Finding dark purple pixels in an image

I am doing a research for my higher studies in automation. I have done the automation part of the microscope but I need help in MATLAB. An example of what I would like to segment is shown here:
I need to extract the dark purple pixels from this image and only display that in a figure. It is almost like colour based segmentation but I just want to only take the dark purple pixel from the whole image.
What would I do in this case?
Here's something to get you started. Let's go with the theme of colour segmentation where you only want to extract pixels that are of a deep purple. I would like to point you to the HSV colour space before we get started. The HSV colour space is ideal for representing colours in a way that is most intuitive to humans. We tend to describe colours by their dominant colour, followed by attributes such as how washed out or how pure the colour is, and how bright or dark the colour is. The dominant colour is represented by the Hue, the appearance of how washed out or how pure the colour is is represented by the Saturation and the intensity of the colour is represented by the Value, and hence Hue-Saturation-Value, or the HSV colour space.
We can transform a RGB image so that it becomes HSV by rgb2hsv. This will return a 3D matrix that has the hue, saturation and value as 2D slices in a 3D matrix, much like a RGB image where each slices represents the red, green and blue channels. Let's see what each component looks like once we transform the image into HSV:
im = imread('https://www.cdc.gov/dpdx/images/malaria/ovale/Po_gametocyte_thickB.jpg');
hsv = rgb2hsv(im2double(im));
figure;
for idx = 1 : 3
subplot(1,3,idx);
imshow(hsv(:,:,idx));
end
The first line of code reads in an image from a URL. I'm going to use the one that Hoki referred you to, as it's the most simplest one to deal with. For self-containment, this is what the original image looks like:
Once we do this, we convert the image into the HSV colour space. It is important that you convert the image to double precision and you normalize each component to [0,1], and that is performed by im2double. Next, we spawn a new figure, and place each component in a single row over three columns. The first column represents the hue, next column the saturation and finally the last column being the value. This is the figure that we see:
With the first figure, it looks like the dominant colour is purple, whether it's a light shade or a dark shade of the colour, so the hue won't help us here. If you look at a HSV colour wheel:
(source: hobbitsandhobos.com)
Normalize the wheel so that it falls between [0,1] instead of 0 to 360 degrees. The hue is actually represented as degrees due to the nature of the colour space, but MATLAB normalizes this to [0,1]. You can see that purple falls within a hue of [0.6,0.8], which corresponds to the first figure I showed you that displays the hue for our image. If you examine the pixels around the image, they fluctuate between this range. Therefore, the hue won't help us much here.
What will certainly help us are the saturation and value components. If you take a look, the deep purple pixels have a higher saturation than the rest of the background, which makes sense because the deep purple has a much more pure version of purple than the rest of the background. For the value, you can see that the brightness of the dark purple is darker than the background.
We can use these two points as an exploit to segment out the purple colour in the image. The easiest thing to do would be to threshold the saturation and value planes so that any values that are within a certain range you keep while those that are outside you throw away. Therefore, you can do something like this:
sThresh = hsv(:,:,2) > 0.6 & hsv(:,:,2) < 0.9;
vThresh = hsv(:,:,3) > 0.4 & hsv(:,:,3) < 0.65;
I used impixelinfo and I hovered my mouse over the saturation and value components to examine what the values were for the deep purple regions. It looks like those pixels that are deep purple have a saturation value between 0.6 and 0.9, while the value component has values between 0.4 and 0.65. The above code will create two binary masks where true means that the pixel satisfies our criteria while false means it doesn't. Because I want to combine both things together and not leave any stone unturned, let's logical OR the masks together for the final result:
figure;
result = sThresh | vThresh;
imshow(result);
We will also show the result too. This is what we get:
As you can see, this does a pretty good job, but we have remnants of the red arrow that we don't want in the final result. To do a bit of cleanup, we can use morphology - specifically an opening filter of a small window so that we don't affect the pixels that we want as much. We can use imopen to perform our opening operation for us. A morphological opening removes isolated pixels that appear around your image. You use what is called a structuring element that is used to look at local neighbourhoods of your image. For the basics, any pixel regions that are as small as the shape that is contained within the structuring element get removed. Because we want to preserve the shape of the other objects, we can try using a 5 x 5 disk structuring element to clean these pixels up:
figure;
se = strel('disk', 2, 0);
final = imopen(result, se);
imshow(final);
This is what we get:
Not bad! There are some holes that we need to patch up, so let's fill in those holes with imfill:
figure;
final_noholes = imfill(final, 'holes');
imshow(final_noholes);
This is what we get:
OK! So we have our mask. The last thing we need to do is present the image so that you only show the deep purple colours from the original image, and nothing else. That can easily be achieved with bsxfun:
figure;
out = bsxfun(#times, im, uint8(final_noholes));
imshow(out);
The above operation takes your mask, and multiplies every pixel in your image by this mask. One small thing I'd like to point out is that the mask we found in the previous step needs to be cast to uint8, because bsxfun requires that the multiplication (or whatever operation you perform) need to be the same type. We replicate this mask in 3D so that you mask out the unwanted RGB pixels and only keep the ones you are looking for.
This is what we finally get:
As you can see, it isn't perfect, but it's certainly enough to get you started. Those thresholds are what are important, but with some very simple thresholding, I extracted most of the purple pixels out.
To make it easier for you, here's the code that I wrote above that can easily be copied and pasted into MATLAB for you to run:
clear all; close all; clc;
im = imread('https://www.cdc.gov/dpdx/images/malaria/ovale/Po_gametocyte_thickB.jpg');
hsv = rgb2hsv(im2double(im));
figure;
for idx = 1 : 3
subplot(1,3,idx);
imshow(hsv(:,:,idx));
end
sThresh = hsv(:,:,2) > 0.6 & hsv(:,:,2) < 0.9;
vThresh = hsv(:,:,3) > 0.4 & hsv(:,:,3) < 0.65;
figure;
result = sThresh | vThresh;
imshow(result);
figure;
se = strel('disk', 2, 0);
final = imopen(result, se);
imshow(final);
figure;
final_noholes = imfill(final, 'holes');
imshow(final_noholes);
figure;
out = bsxfun(#times, im, uint8(final_noholes));
imshow(out);
Good luck!
Try this:
function main
clc,clear
A = imread('https://www.cdc.gov/dpdx/images/malaria/ovale/Po_gametocyte_thickB.jpg');
subplot(1,2,1)
imshow(A)
RGB = [230 210 200]; % color you want
e = 40; % color shift
B = pix_in(A,RGB,e);
B = B + 255.*uint8(~B); % choosing white background
subplot(1,2,2)
imshow(B)
end
function B = pix_in(A,RGB,e)
% select specific pixels in image
% A - color image (3D matrix uint8)
% RGB - [R G B] - color to select
% e - color shift/deviation
A = double(A); % for same class operations (RGB - double)
[m, n, ~] = size(A);
RGB = reshape(RGB,1,1,3);
RGB = repmat(RGB,m,n,1); % creating 3D matrix
b = abs(A-RGB) < e; % logical 3D
b = sum(b,3) == 3; % if [R,G,B] of a pixel in range
B = A.*repmat(b,1,1,3); % selecting pixels those in range
B = uint8(B);
end

How to smooth the perimeter output of bwperim?

I have a segmented image
When I apply bwperim function on this I get the output as below
I want to have a thin line of perimeter - just one pixel-thick. This is essential for further processing work. What is the best approach?
Please suggest.
======
BoundingBox
%%% ComputeBoundingBox
%%%
function [stats, statsAlreadyComputed] = ...
ComputeBoundingBox(imageSize,stats,statsAlreadyComputed)
% [minC minR width height]; minC and minR end in .5.
if ~statsAlreadyComputed.BoundingBox
statsAlreadyComputed.BoundingBox = 1;
[stats, statsAlreadyComputed] = ...
ComputePixelList(imageSize,stats,statsAlreadyComputed);
num_dims = numel(imageSize);
for k = 1:length(stats)
list = stats(k).PixelList;
if (isempty(list))
stats(k).BoundingBox = [0.5*ones(1,num_dims) zeros(1,num_dims)];
else
min_corner = min(list,[],1) - 0.5;
max_corner = max(list,[],1) + 0.5;
stats(k).BoundingBox = [min_corner (max_corner - min_corner)];
end
end
end
That is happening because your image had quantization error when you were saving the image. Did you save your image using a lossy compression algorithm, like JPEG? If you want to preserve the intensities so that they don't change when you save the image, use a lossless compression algorithm, like PNG.
To eliminate these "noisy" effects, threshold your image first to eliminate any quantization errors so that you can set these pixels to completely white, then try using bwperim again. In other words, do something like this:
im = im2bw(imread('http://i.stack.imgur.com/dagEc.png'));
im_noborder = imclearborder(im);
out = bwperim(im_noborder);
imshow(out);
The first line of code reads in your image directly from StackOverflow and we use im2bw to threshold your image. This image was originally grayscale, and so we want to convert this into black and white only. This will also remove any quantization artifacts as it thresholds anything higher than 128. The next line of code removes the white border with imclearborder that surrounds your shape because the image you uploaded has a white border surrounding it for some reason. Once we remove this border, we then apply bwperim and we show the image.
This is the image I get:

Displaying a png image without the background

http://sweetclipart.com/multisite/sweetclipart/files/sunglasses_black.png
I have read the png image in MATLAB using [X,map,alpha]=imread('...','png').
Now I want to place this png image on another image. But I want the background color of the read png not to be shown. In the link I want the sunglasses alone to be shown without the 'white' background (Background is another image).
The alpha channel is opacity, the opposite of transparency.
MATLAB figures support alpha blending via the AlphaData property:
background = uint8(255*rand(size(alpha)));
imshow(background)
hold on
h = imshow(X);
set(h, 'AlphaData', alpha)
Result:
Given another image Y and your image X with it's alpha data, you can use alpha to generate a blended image. In you case, alpha has only the values 0 and 255, but in general there can be levels of opacity. In this simple case, again with noise background, but in color:
out = uint8(255*rand(size(X))); % Y
hardMask = repmat(alpha==255,1,1,3);
out(hardMask) = X(hardMask);
imwrite(out,'sunglass_alphaC.png')
It's a big image, so I resized the output here:
If your alpha channel actually had more than two levels of transparency, you could blend with the background:
s = double(alpha)/255;
Yout = uint8((bsxfun(#times,1-s,double(Y)) + bsxfun(#times,s,double(X))));
For grayscale, bsxfun can be replaced with just .- (e.g. s.*double(X)).
You can do it like this:
% Image with alpha channel
[glasses, ~, alpha] = imread('http://sweetclipart.com/multisite/sweetclipart/files/sunglasses_black.png');
% OPTIONAL: Let's rescale it (it's very big!)
glasses = imresize(glasses, 0.1);
alpha = imresize(alpha, 0.1);
% An image of a person (let's put the glasses on the person).
person = imread('http://cinemacao.com/wp-content/uploads/2013/12/Scarlett-CAPA-2.jpg');
% Lets make the alpha MxNx3 (so we can combine it with the RGB channels).
alpha = repmat(alpha, [1 1 3]);
% And convert everything from uint8 to double (to avoid precision issues).
glasses = im2double(glasses);
alpha = im2double(alpha);
person = im2double(person);
% Final image
% Let x,y be the top-left coordinates where we'll put the glasses.
x = 440;
y = 450;
% Let's combine the images.
img3 = person;
img3(y:y+size(glasses,1)-1, x:x+size(glasses,2)-1, :) = ...
glasses .* alpha + ...
person(y:y+size(glasses,1)-1, x:x+size(glasses,2)-1, :) .* (1 - alpha);
% An display the result.
imshow(img3);
Result:
I dont know much about Matlab, but seems to be that [X,map,alpha] use "alpha" as the alpha channel; alpha channel means level of transparency. (probably you already know this). Also check if the image itself has the alpha channel set. PNG doesn't recognise "white" as alpha channel by default. In this case, go to your favorite "*shop" software to edit the photo (maybe select with magic tool which will be the background, go to select inverse, copy-paste to a new image previously specifying that the background image will be transparency).