How can I change the colors in an RGB image to certain colors in MATLAB

4 visualizzazioni (ultimi 30 giorni)
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)

Risposta accettata

Cris LaPierre
Cris LaPierre il 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 Commenti
Dillon Thoms
Dillon Thoms il 3 Apr 2019
Thanks for the reply!
I'm fairly new to MATLAB how would that incorporate into the code I provided?
Cris LaPierre
Cris LaPierre il 4 Apr 2019
Modificato: Cris LaPierre il 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.

Accedi per commentare.

Più risposte (1)

Image Analyst
Image Analyst il 3 Apr 2019
Try this instead of all your code.
RGB = imread('Test2before.png');
B = RGB(:,:,3);
percentage = nnz(B < 100) / numel(B)

Categorie

Scopri di più su Image Processing Toolbox in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by