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

1 回表示 (過去 30 日間)
Dillon Thoms
Dillon Thoms 2019 年 4 月 3 日
編集済み: Cris LaPierre 2019 年 4 月 4 日
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 Center および File ExchangeImage Processing Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by