已完成背景分割,如何提取水稻叶片的R、G、B、H、S、V颜色空间值?
Hey there! Let's work through this together. Right now, your code is only visualizing the full RGB channels of the entire image—but you aren’t using your segmentation mask to isolate the rice leaf region, nor are you converting to the HSV color space to pull those values. Here’s how to fix this:
Step 1: Prepare Your Segmentation Mask
First, make sure you have a binary mask where rice leaf pixels are marked as 1 (or 255 if it’s a uint8 image) and background pixels are 0. This should be the output from your background-target segmentation step.
Step 2: Extract RGB Values for the Leaf Region
Use the mask to index into your RGB channels and grab only the pixels that belong to the rice leaf:
% Your original RGB channel extraction rmat = Im(:,:,1); gmat = Im(:,:,2); bmat = Im(:,:,3); % Extract leaf-only RGB values (adjust mask condition if your mask uses 255 instead of 1) leaf_r = rmat(mask == 1); leaf_g = gmat(mask == 1); leaf_b = bmat(mask == 1); % Optional: Visualize masked RGB channels to confirm masked_r = rmat .* mask; masked_g = gmat .* mask; masked_b = bmat .* mask; subplot(2,3,1), imshow(masked_r); title('Masked Red Plane'); subplot(2,3,2), imshow(masked_g); title('Masked Green Plane'); subplot(2,3,3), imshow(masked_b); title('Masked Blue Plane');
Step 3: Convert to HSV & Extract H/S/V Values
Convert your RGB image to the HSV color space, then use the same mask to isolate the leaf region’s HSV values:
% Convert RGB image to HSV hsv_im = rgb2hsv(Im); hmat = hsv_im(:,:,1); % Hue (scaled 0-1) smat = hsv_im(:,:,2); % Saturation (scaled 0-1) vmat = hsv_im(:,:,3); % Value (scaled 0-1) % Extract leaf-only HSV values leaf_h = hmat(mask == 1); leaf_s = smat(mask == 1); leaf_v = vmat(mask == 1); % Optional: Visualize masked HSV channels masked_h = hmat .* mask; masked_s = smat .* mask; masked_v = vmat .* mask; subplot(2,3,4), imshow(masked_h); title('Masked Hue Plane'); subplot(2,3,5), imshow(masked_s); title('Masked Saturation Plane'); subplot(2,3,6), imshow(masked_v); title('Masked Value Plane');
Step 4: Work with the Extracted Values
Now leaf_r, leaf_g, leaf_b, leaf_h, leaf_s, leaf_v are 1D arrays containing only the color values of your rice leaf pixels. You can analyze them further, like calculating statistics:
% Example: Calculate mean color values for the leaf mean_leaf_r = mean(leaf_r); mean_leaf_g = mean(leaf_g); mean_leaf_b = mean(leaf_b); mean_leaf_h = mean(leaf_h); mean_leaf_s = mean(leaf_s); mean_leaf_v = mean(leaf_v);
Quick Notes:
- If your mask uses
255for leaf pixels (common in uint8 binary images), change the indexing condition tomask == 255. - Double-check that
Imis a true RGB image (not grayscale) by runningsize(Im)—it should return[height, width, 3].
内容的提问来源于stack exchange,提问作者Putri Ranati

