How can I change the colors in an RGB image to certain colors in MATLAB
16 views (last 30 days)
Show older comments
Hello,
What I'm trying to do is count the number of pixels below a certain threshold, that part works. What I'm struggling with is I want to change the color of pixels below the threshold (a) to black and the pixels above the threshold (b) to white. Does anybody have any suggestions?
RGB = imread(['Test2before.png']);
B = RGB(:,:,3);
image(B);
% a is the number of pixel of straw
% b is the number of pixel of soil
a = 0;
b = 0;
% B is a RxC matrix
% max. value for c is C
% max. value for r is R
for c = 1:2250 %729
for r = 1:2050 %349
if B(r,c) < 100
a = a+1;
else
b = b+1;
end
end
end
% percentage is the residue cover
percentage = a/(a+b)
0 Comments
Accepted Answer
Cris LaPierre
on 3 Apr 2019
A color image has 3 color values: r, g and b. I'd first convert the image to grayscale, and then impose a threshold doing something like this:
img = imread('pears.png');
imshow(img)
bw = rgb2gray(img);
bw(bw<100) = 0;
bw(bw>=100) = 255;
figure
imshow(bw)
2 Comments
Cris LaPierre
on 4 Apr 2019
Edited: Cris LaPierre
on 4 Apr 2019
I guess I'm curious why you want to just use the green values. I guess it's somewhat arbitrary what color you pick. Image Analyst shows you how to compute the percentage w/o using for loops.
Here's how I would incorporate it.
RGB = imread('pears.png');
B = RGB(:,:,3);
image(B);
thresh = 100;
imshow(B)
% a is the number of pixel of straw
% b is the number of pixel of soil
a = sum(B<thresh);
b = sum(B>=thresh);
% percentage is the residue cover
percentage = a/(a+b)
B(B<thresh) = 0;
B(B>=thresh) = 255;
figure
imshow(B)
If you are really new to MATLAB, consider going through MATLAB Onramp. Pick and choose the chapters you want to learn.
More Answers (1)
Image Analyst
on 3 Apr 2019
Try this instead of all your code.
RGB = imread('Test2before.png');
B = RGB(:,:,3);
percentage = nnz(B < 100) / numel(B)
0 Comments
See Also
Categories
Find more on Image Processing Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!