You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
how do I filter noise and background objects from images?
12 views (last 30 days)
Show older comments
i have images that have these cylindrical objects that i want removed before doing analysis? How do I remove them?
Thank you
Accepted Answer
Image Analyst
on 14 Jan 2023
Do what? Erase/blacken those black regions from the original image? You simply do
grayImage(~mask) = 0;
If you don't have the mask yet then you need to segment your image to get objects. Then try to find some property that distinguishes "cylindrical/sinusoidal objects" (whatever those are or look like) from other objects. We can't really help (yet) since you forgot to attach the original image. You only attached the segmented image (mask).
34 Comments
Matthew Worker
on 15 Jan 2023
That was ex image. I don't have the pre masked image so I have attached a different image where I want to substract the objects that I circled.
Matthew Worker
on 15 Jan 2023
I checked out your segmentation tutorial and it looks nice but I am not sure how I can apply it what i want.
I want to extract the objects that I circled such that they do not appear in my measurements. in other images the region of interest would be the non cylindrical/sinusoidal areas.
Image Analyst
on 15 Jan 2023
There seems to be no predictable way to identify the ones you circled, so I suggest you just manually click on the items using bwselect
Matthew Worker
on 17 Jan 2023
Out of cursioity, why does the mask for your script not encompass the entire white area like in the image (attached)? Is it becasue your mask is more detailed and the other mask is computer generated from that program? what is the difference between these two mask? one you made and the other that comes with the software? you answered my question this question is just curisoity.
Image Analyst
on 17 Jan 2023
It looks like someone has done additional morphological operations on the original image by thresholding. Like they used imerode, imdilate, or imclose , at least it looks like it based on the shapes of the edges of the white region. And they might have used bwareaopen to fill holes in a certain size range.
Image Analyst
on 17 Jan 2023
Not necessarily. Sometimes people don't like accurate edges and just want smoother edges for some reason. Or sometimes they want pixels to be included in the region even if they're part of a small dark interior "island".
Image Analyst
on 17 Jan 2023
If you want dark regions, the threshold values will be low, and lowThreshold would probably be 0.
If you want bright regions, the threshold values will be high, and the highThreshold would probably be 255.
I don't know what sinusoid has to do with anything.
Matthew Worker
on 18 Jan 2023
sinusoid was typo.
To clarify: i want the bright regions but rather than selecting all the bright regions how do I just exclude the black regions? Would it be:
- (mask = grayImage >= lowThreshold & grayImage <= highThreshold);
Image Analyst
on 18 Jan 2023
No. That is not proper MATLAB syntax.
Again, not sure what you want. I don't even know what it means, what you said. If you want bright regions, you can get a mask for that using the appropriate thresholds. If you want dark regions, you can also get a mask for that using different thresholds. Using the mask, you can then do things like particle analysis, shape analysis, area fraction, mean gray level etc. I'm not sure what you want.
Matthew Worker
on 18 Jan 2023
I want everything except the dark areas.
How do I subtract out only the dark regions in the image?
@image analyst
Image Analyst
on 19 Jan 2023
Boy, this is getting tough. I still don't know what you want or what "want" means to you. Let me assume you "want" a list of all pixel values greater than the threshold. So create your mask and use it as an index
% Get mask of bright pixels:
mask = grayImage > 50; % or whatever value you want.
% Get a list of all pixel values in that region:
pixelValues = grayImage(mask)
Is that what you want? If not, then describe in many more words exactly what "want" means. What sort of mathematical operation does "want" mean? I thresholded and then extracted. If that's not what you want then describe what you want much, much, much better.
Matthew Worker
on 19 Jan 2023
Edited: Matthew Worker
on 19 Jan 2023
Sorry @Image Analyst
I am trying to be more clear. I have made a definition of what I want:
want - list of all pixel values less than the threshold
And I have written an idea of the mathematical operation based on your example:
% Get mask of dark pixels or all the complete black pixels:
mask = grayImage < 15; % or whatever value you want.
% Get a list of all pixel values in that region:
pixelValues = grayImage(mask)
Then:
apply the mask such that it substracts all of the pixel values at or below the threshold in the entire image leaving behind all the pixels greater than the threshold (which should be the pixels that are green minus the pixels that are completely black).
Lastly, I have attached a screenshot that i found where in the image "a" the people represent the green pixels and everything else is the background (everything without people). Instead of extracting the people and deleting the background "c" (synonymously instead of extracting the green pixels and deleting the background), how about extracting the background leaving everything else? This may ensure that you get all the information from the nonbackground without accidentally deleting information that is not necessarily the people but is also not background. pLease let me know how i can explain better.
Matthew Worker
on 19 Jan 2023
Edited: Matthew Worker
on 19 Jan 2023
to add to this explanation:
imagine you have an image and in that image there are two possible categories 1. obvious information (the region of interest) 2. obvious background (completely black or very obscure regions). BUT what if there was a possible third category? 3. ambiguous region of interest that is not necessarily background.
So if I just subtract the background I will possibly be left with everything informative but if i just select the region of interest i may leave out some unobvious areas that are informative.
Image Analyst
on 19 Jan 2023
So let's say you have a threshold of 50 and all pixels with that threshold or lower are definitely background. Now let's say you have a threshold of 60 and all pixels with that gray level or higher are definitely foreground with no question. So that leaves pixels with gray levels between 51 and 59 (inclusive) that you could consider either foreground or background - you're not sure. So if you're dealing with certain types of images (fluorescence or x-ray) then you might say that there is an overall background offset that everything is sitting on. So then you could subtract the background image from the original image. But at a certain pixel, you don't know what the background value would be if the signal were not at that location. So what do you subtract? Do you subtract the mean of the pixels you know are definitely background, let's say it's 30. Or do you subtract 50, the max of what you consider to be background?
Image Analyst
on 19 Jan 2023
And what is that? What is definitely background is a whole bunch of pixels with a huge variety of gray levels. What do you want to subtract?
Matthew Worker
on 19 Jan 2023
Well you wrote:
“Do you subtract the mean of the pixels you know are definitely background, let's say it's 30.”
So my response is yes. I want to substract all the pixels that are definitely background by applying a threshold of 30 and removing those pixels and all below it.
Image Analyst
on 19 Jan 2023
Let's say your image is this
img = [5, 200, 200;
5, 200, 200;
100, 29, 150]
img = 3×3
5 200 200
5 200 200
100 29 150
Tell me what you want as your subtracted image (this must be a 3 by 3 square matrix), and what you want the final answer to be, like a single number that is the mean of something or whatever..
Matthew Worker
on 20 Jan 2023
I don’t think I know how to determine that.. I just know that if the threshold is low enough then I want to substract those pixel values from my image and leave everything else. Is that easier to understand? I can’t determine by looking at a matrix what I want to substract from it and what the final answer will be.
Image Analyst
on 20 Jan 2023
Then I don't know either. How about this
img = [5, 200, 200;
5, 200, 200;
100, 29, 150]
img = 3×3
5 200 200
5 200 200
100 29 150
bgCorr = img - 29
bgCorr = 3×3
-24 171 171
-24 171 171
71 0 121
Is that what you want?
Image Analyst
on 20 Jan 2023
Okay, glad we finally figured out what you want. So just do that. Subtract the max noise value from every pixel in the image.
Matthew Worker
on 20 Jan 2023
To accomplish that, would I:
% read in the image
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Denoise the image
noiseValue = medfilt2(grayImage(:))
% Subtract noise
newImage = grayImage - noiseValue
% Substract background by creating mask
lowThreshold = 14;
highThreshold = 255;
% [lowThreshold, highThreshold, lastThresholdedBand] = threshold(3, 255, grayImage);
masksinusoid = grayImage >= lowThreshold & grayImage <= highThreshold;
% Compute the mean/analysis (...)
Image Analyst
on 20 Jan 2023
Uh, no. Not sure why you'd think that. The median filtered image is not the noise image. And you certainly don't want to call a median filter on the image converted to a column vector, which is what grayImage(:) is.
Again, I don't know what you want. I thought you wanted the mean gray level of all the green pixels and I gave you code for that long ago.
Matthew Worker
on 20 Jan 2023
Would I just add this line of code to the training script you gave me?
bgCorr = img - 29
Image Analyst
on 21 Jan 2023
No, unless you know the background is 29 gray levels everywhere. Why do you want to get rid of the background? Why is it necessary? What do you need to know, actually? And I'm not looking for an answer like I need to know how to subtract noise. Or I need to know the leve of noise. Who hired you to analyze these photos? If you went to them and said "what do you want me to measure for me?" I doubt they would say I need to know the noise level or I need to have a background subtracted image. Let's say that National Science Foundation put out a request for proposals. What would it say? It's not going to say I'd like to give money to a university group so they can give me background subtracted images. They don't care about that. They care about something else. What is it?
Matthew Worker
on 21 Jan 2023
I’m a student and I know python and imageJ styles now I want to learn Matlab so I’m trying to make different algorithms to understand different analysis that I’m interested in. For this image I just want to want understand that I’ve extracted all of the useless information and only have the regions with info in them that’s why I want to substract background and noise. Unless you think that it is not a good way to do it?
Matthew Worker
on 21 Jan 2023
heres the image that I am researching for your reference, thank you for sharing your knowledge and answering my question always I aspire to be like you.
Chanille
on 21 Jan 2023
I think this question doesn’t uphold the community values and it’s too long for a good learning tool.
Matthew Worker
on 21 Jan 2023
Sorry for this. I have reworded the question to be more clear and I will accept @Image Analyst answer about how to filter the max noise from the pixels in the image.
Matthew Worker
on 23 Jan 2023
was this a rectorical question about the max noise from the pixels? Or is there a way to filter the max noise from all pixels in an image? Thank you.
More Answers (2)
Matt J
on 14 Jan 2023
Edited: Matt J
on 14 Jan 2023
Perhaps with bwpropfilt(____,'Eccentricity', range)
4 Comments
Matthew Worker
on 15 Jan 2023
I think this will work but I am unsure how to format the code such that it extracts those objects that I circled.
Walter Roberson
on 15 Jan 2023
It looks to me as if you want a combination of higher eccentricty (remove the circles) and lower area (remove the large irregular blobs and the ones that are formed by several objects touching.)
Matthew Worker
on 15 Jan 2023
in other images I have these are just areas of non interest. and the areas in black have pixels of interest that's why i want them removed.
I just circled 3 for example but all of the long cylindrical objects will be removed. heres another example where here all the black parts of the image will be removed leaving the green pixelated areas for analysis.
Image Analyst
on 15 Jan 2023
If you want a script to extract only the round blobs, try this:
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = 'D45F33C9-CCA7-4815-B426-07D56A8657D7.jpeg';
folder = pwd;
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
%=======================================================================================
% Read in image.
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display image.
subplot(2, 2, 1);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Original RGB Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
g = gcf;
g.WindowState = "maximized";
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
%--------------------------------------------------------------------------------------------------
% Create a logical image mask.
mask = rgbImage(:, :, 2) > 128;
% Get areas
props = regionprops(mask, 'Area')
allAreas = sort([props.Area])
% Display image.
subplot(2, 2, 2);
imshow(mask, []);
impixelinfo;
axis on;
caption = sprintf('Initial Mask with %d blobs', numel(allAreas));
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Get rid of blobs less than 100 pixels in area
mask = bwareaopen(mask, 100)
% Get rid of partial blobs (those touching the border).
mask = imclearborder(mask);
% Get areas
props = regionprops(mask, 'Area', 'Circularity')
allAreas = sort([props.Area])
allCircs = [props.Circularity]
% Display image.
subplot(2, 2, 3);
imshow(mask, []);
impixelinfo;
axis on;
caption = sprintf('Next Mask with %d blobs', numel(allAreas));
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Filter out non-circular blobs.
[labeledImage, numBlobs] = bwlabel(mask);
roundBlobsOnly = ismember(labeledImage, find(allCircs > 0.6));
% Display image.
subplot(2, 2, 4);
imshow(roundBlobsOnly, []);
impixelinfo;
axis on;
caption = sprintf('Final Mask with %d round-only blobs', sum(allCircs > 0.6));
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
16 Comments
Matthew Worker
on 15 Jan 2023
@Image Analyst Yes this is what i am interested in learning more about! This is what answer I am trying to explore
Is there a way to apply it to the extraction of all of the black areas in this image attached (which I just found is the pre masked image i posted). the black areas are just areas of non interests that did not get the green pixels, so they are not areas that should be analyzed.
Image Analyst
on 16 Jan 2023
Not sure what "extraction" means to you.
If you want to see how to extract out each blob to a small image that is the bounding box of the blobs, see my Image Processing Tutorial in my File Exchange:
Matthew Worker
on 16 Jan 2023
here extraction means substraction.
from this image, i want to substract all of the black areas in the image so that only the non black area is measured. so the mask will be white everywhere except for the black areas. does that make more sense? excuse my poor wording please
Image Analyst
on 16 Jan 2023
You can just multiply the mask by the image to erase the parts you don't want and then they won't get analyzed. Tell me what measurements you want to make. Most of the white parts of the mask are just background, not fluorescent blobs.
Matthew Worker
on 17 Jan 2023
I could multiply by the mask but I want to look at other images as well to see how it works. Which u can’t do without it’s mask right?
Measurements I want to make: After contrast correction, Gaussian filtering and removal of background I want to take the mean of the pixel content remaining (excluding the elongated black areas surrounding the green).
Image Analyst
on 17 Jan 2023
You're confusing. At lease I'm confused. You have already segmented your image and have a mask -- that's what I understood. The white parts of the mask are the mostly black background. If you multiply by that mask, the green blobs will be erased. You can then somehow analyze what's left, which will be the dark background. If you have additional images I imagine you'd segment them also and have a mask for them also that applies only for the image it was generated for.
If you wanted the green blobs, you'd multiply by the inverse of your mask which would keep the green blobs and erase the background.
All that said, I still don't know what you really want - the background or the green blobs -- and what attributes/properties you want to measure in that/those region(s). Please clarify. Your language and descriptions are confusing and contradictory. And remember the foreground in the mask is white in MATLAB, which may be the opposite of what it is in other programs like ImageJ. At one point it seemed like you wanted to erase non-round blobs and keep only round blobs, and I showed you that. Another time (original question) it seemed like you wanted ALL black blobs in your segmented image to be erased, which would leave you only the dark background in the original picture. Just tell me what you want and be very very clear and specific.
Matthew Worker
on 17 Jan 2023
I am so sorry for my confusion. I know I must explain better.
I have an image(hi.jpg) in its original form no segmentation and no mask. I want to create a mask of the image that subtracts the black areas (I have circled some of the elongated shapes that the mask should get rid of hi.jpeg).
This will leave me with just the green information. I hope that this explanation is more clear, please let me no if not.
Sorry to bother with this,
Image Analyst
on 17 Jan 2023
Edited: Image Analyst
on 17 Jan 2023
OK, this will do it but what do you want to measure from the green pixels? Just the mean?
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = 'hi.jpg';
folder = pwd;
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
%=======================================================================================
% Read in image.
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display image.
subplot(2, 3, 1);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Original RGB Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
g = gcf;
g.WindowState = "maximized";
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
%--------------------------------------------------------------------------------------------------
% Get the green channel
grayImage = rgbImage(:, :, 2);
% Display image.
subplot(2, 3, 2);
imshow(grayImage, []);
impixelinfo;
axis on;
title('Green Channel', 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
drawnow;
%--------------------------------------------------------------------------------------------------
% Show the histogram
subplot(2, 3, 3);
imhist(grayImage);
grid on;
drawnow;
%--------------------------------------------------------------------------------------------------
% Create a logical image mask of the green parts.
lowThreshold = 14;
highThreshold = 255;
% [lowThreshold, highThreshold, lastThresholdedBand] = threshold(3, 255, grayImage);
mask = grayImage >= lowThreshold & grayImage <= highThreshold;
% Display image.
subplot(2, 3, 4);
imshow(mask, []);
impixelinfo;
axis on;
title('Initial Mask of Green Areas', 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
drawnow;
%--------------------------------------------------------------------------------------------------
% Get the mean of the green pixels
meanGreen = mean(grayImage(mask))
Matthew Worker
on 17 Jan 2023
You answered it in another question, "If you just want the mean gray level in 12 strips going across the image"
I want the mean gray level of each strip across the image.
Matthew Worker
on 17 Jan 2023
Yes i think this will work, i have accepted answer it has removed the black areas so I can only focus on the information from the green. This is what i wanted to learn more about. I hope to grow to know as much as you do @Image Analyst
Chanille
on 25 Jan 2023
May I ask a related question?
Is there a way to COUNT the content per strip area then DIVIDE by the area in that strip?
Image Analyst
on 25 Jan 2023
@Chanille I have no idea what that means. What is the discrete, countable items that you want to count? If you can make a mask of blobs somehow, then yes you can count them with bwlabel or regionprops and then divide by the number of pixels.
[~, blobCount] = bwlabel(mask);
output = blobCount / numel(mask) % compute count density
Image Analyst
on 25 Jan 2023
Note, the area fraction = (# foreground pixels) / (total # of pixels in ROI) is not the same as the count density = (# distinct blobs) / (total # of pixels in ROI). You can get either and/or both - just depends on what will help you in your further analysis.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)