How do I make this code consistent to count just the green pixels in the image

1 次查看(过去 30 天)
I = imread("RefQ2.jpg","jpeg");
I2 = rgb2hsv(I)
Pic = imshow(I2)
s = mat2gray(I2(:,:,2))
A = imshow(s)
bw = im2bw(s, 0.1)
B = imshow(bw)
Green_Pxl_Count = sum(bw(:,:)==1);
Other_Pxl_Count = sum(bw(:,:)==0);
Sum_Green_Pxl = sum(Green_Pxl_Count,"all","default");
Sum_Other_Pxl = sum(Other_Pxl_Count,"all","default");
Totalpxl = Sum_Green_Pxl + Sum_Other_Pxl;
Percent_Cover = (Sum_Green_Pxl/Totalpxl)*100

回答(1 个)

Adithya
Adithya 2023-9-4
Hey @Carly Fitz Morris , To make the code consistent and count just the green pixels in the image, you can modify it as follows:
I = imread("RefQ2.jpg","jpeg");
I2 = rgb2hsv(I);
s = I2(:,:,2); % Extract the saturation channel (green component)
bw = im2bw(s, graythresh(s)); % Convert to binary image using automatic thresholding
Green_Pxl_Count = sum(bw(:) == 1); % Count the green pixels
Total_Pxl_Count = numel(bw); % Count the total number of pixels
Percent_Cover = (Green_Pxl_Count / Total_Pxl_Count) * 100; % Calculate the percentage of green coverage
In this modified code, the unnecessary steps of displaying intermediate images using imshow have been removed. The green component is extracted from the HSV image I2 by selecting the saturation channel (I2(:,:,2)). Then, the image is converted to a binary image using automatic thresholding (im2bw) with the threshold determined by graythresh(s), where s represents the saturation channel.
The green pixel count is obtained by summing the binary image where the pixel value is equal to 1 (sum(bw(:) == 1)). The total pixel count is obtained by counting the number of elements in the binary image (numel(bw)). Finally, the percentage of green coverage is calculated by dividing the green pixel count by the total pixel count and multiplying by 100.
By making these modifications, the code will count only the green pixels in the image and calculate the percentage of green coverage.

产品

Community Treasure Hunt

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

Start Hunting!

Translated by