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

조회 수: 4 (최근 30일)
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)

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Image Processing Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by