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
0 件のコメント
回答 (1 件)
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.
0 件のコメント
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!