Determine the proportion of specific colors in an image - matlab

Do you have any idea how can I determine the proportion of Yellow (or Yellowish), Brown, and Red colour in a specific image? I tried to use HSV, but I could not find any threshold for H, S, and V for the aforementioned colours.
I attached a sample image.

So, let's do this one step at a time.
First how to know which color is represented by what value? For that, I referred to this stackoverflow question, from where you can get this HSV color map,
If you DuckDuckGo/Google/search for "HSV or HSL color map", you could find many examples.
Now, we can pick a color from the along the horizontal axis. We can use a single value e.g. 120 for dark blue or we can use a range of values e.g. 45 to 80 for all hues of green.
What I wasn't sure about was, how to define the,
proportion of Yellow (or Yellowish), Brown, and Red colour in a specific image
as you ask in your question.
I thought of then two ways to represent the color proportion.
Proportion of pixels containing some portion of that hue.
Proportion of the specific hue relative to all the hues in the image.
Then using the following script, you could get some numbers:
NOTE: (This the Python script, I originally posted. The corresponding Matlab script is further down the post.)
import cv2
import numpy as np
img = cv2.imread("D:\\lenna.jpg")
height_img, width_img, channels_img = img.shape
# Converts images from RGB to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask1 = cv2.inRange(hsv, (150, 0, 0), (150, 255,255)) #150 seems like pinkish
mask2 = cv2.inRange(hsv, (1,0,0), (20, 255, 255)) #1 to 20 seems orangish
total_num_of_pixels = height_img * width_img
all_colors = np.sum(hsv[:,:,:] > 0)
num_of_pixels_with_pinkish_component = np.sum(mask1 > 0)
num_of_pixels_with_orangish_component = np.sum(mask2 > 0)
print("%age of pixels with pinkish component:", "{:.2f}".format(num_of_pixels_with_pinkish_component/total_num_of_pixels * 100))
print("%age of pixels with orangish component:", "{:.2f}".format(num_of_pixels_with_orangish_component/total_num_of_pixels * 100))
print("%age of pinkish component in the entire HSV image:", "{:.2f}".format(num_of_pixels_with_pinkish_component/all_colors * 100))
print("%age of orangish in the entire HSV image:", "{:.2f}".format(num_of_pixels_with_orangish_component/all_colors * 100))
# To visualize the results
res1 = cv2.bitwise_and(img, img, mask=mask1)
res2 = cv2.bitwise_and(img, img, mask=mask2)
cv2.imshow('img', img)
cv2.imshow('mask1', mask1)
cv2.imshow('mask2', mask2)
cv2.imshow('res1', res1)
cv2.imshow('res2', res2)
# To save the output
cv2.imwrite('D:\\mask1.png', mask1)
cv2.imwrite('D:\\mask2.png', mask2)
cv2.imwrite('D:\\res1.png', res1)
cv2.imwrite('D:\\res2.png', res2)
Output:
%age of pixels with pinkish component: 0.41
%age of pixels with orangish component: 35.58
%age of pinkish component in the entire HSV image: 0.15
%age of orangish in the entire HSV image: 13.27
Here is how the output looks then:
MASK1 (150 on the hue axis seems pinkish)
MASK2 (1 ~ 20 on the hue axis seems orange)
RES1
RES2
Here is the equivalent MATLAB script.
close all;
clear all;
clc;
img = imread("/home/junglefox/Downloads/lenna.png");
figure, imshow(img), title('original image (RGB)');
img_size = size(img);
hsv_img = rgb2hsv(img);
hsv_img = im2uint8(hsv_img);
figure, imshow(hsv_img), title('original image in HSV');
% Orange component between 1 and 20 on the HSV map
minval = [1 0 0]; %// Define three element vector here for each colour plane i.e. [0 128 128];
maxval = [20 255 255]; %// Define three element vector here for each colour plane i.e. [0 128 128];
out = true(img_size(1), img_size(2));
for p = 1 : 3
out = out & (hsv_img(:,:,p) >= minval(p) & hsv_img(:,:,p) <= maxval(p));
end
figure, imshow(out), title('image of orange component in image only');
total_num_of_pixels = img_size(1) * img_size(2);
all_colors = sum(hsv_img(:,:,:) > 0);
num_of_pixels_with_orangish_component = sum(sum(out > 0));
percentage_orange = num_of_pixels_with_orangish_component/total_num_of_pixels * 100;
printf("percentage of orange component in all pixels:%d\n", percentage_orange);

Related

How to extract the white rings in the given image

I have an image of a robot moving, I need to extract the white rings
in order to find the midpoint of the robot. But thresholding is not giving correct result:
What method should I try to extract only the white rings.
%code to get second image
img=imread('data\Image13.jpg');
hsv=rgb2hsv(img);
bin=hsv(:,:,3)>0.8;
Something like that?
import cv2
import numpy as np
# get bounding rectangles of contours
img = cv2.imread('img.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# filter contours by area and width
contours = [c for c in contours if (50 < cv2.contourArea(c) < 500) and cv2.boundingRect(c)[2] > 20]
# draw contours on empty mask
out = np.zeros(thresh.shape, dtype=np.uint8)
cv2.drawContours(out, contours, -1, 255, -1)
cv2.imwrite('out.png', out)
Output:

Why can't I colour my segmented region from the original image

I have the following code:
close all;
star = imread('/Users/name/Desktop/folder/pics/OnTheBeach.png');
blrtype = fspecial('average',[3 3]);
blurred = imfilter(star, blrtype);
[rows,cols,planes] = size(star);
R = star(:,:,1); G = star(:,:,2); B = star(:,:,3);
starS = zeros(rows,cols);
ind = find(R > 190 & R < 240 & G > 100 & G < 170 & B > 20 & B < 160);
starS(ind) = 1;
K = imfill(starS,'holes');
stats = regionprops(logical(K), 'Area', 'Solidity');
ind = ([stats.Area] > 250 & [stats.Solidity] > 0.1);
L = bwlabel(K);
result = ismember(L,find(ind));
Up to this point I load an image, blur to filter out some noise, do colour segmentation to find the specific objects which fall in that range, then create a binary image that has value 1 for the object's colour, and 0 for all other stuff. Finally I do region filtering to remove any clutter that was left in the image so I'm only left with the objects I'm looking for.
Now I want to recolour the original image based on the segmentation mask to change the colour of the starfish. I want to create Red,Green,Blue channels, assign value to them then lay the mask over the image. (To have red starfishes for example)
red = star;
red(starS) = starS(:,:,255);
green = star;
green(starS) = starS(:,:,0);
blue = star;
blue(starS) = star(:,:,0);
out = cat(3, red, green, blue);
imshow(out);
This gives me an error: Index exceeds matrix dimensions.
Error in Project4 (line 28)
red(starS) = starS(:,:,255);
What is wrong with my current approach?
Your code is kinda confusing... I don't understand whether the mask you want to use is starS or result since both look like 2d indexers. In your second code snippet you used starS, but the mask you posted in your question is result.
Anyway, no matter what your desired mask is, all you have to do is to use the imoverlay function. Here is a small example based on your code:
out = imoverlay(star,result,[1 0 0]);
imshow(out);
and here is the output:
If the opaque mask of imoverlay suggested by Tommaso is not what you're after, you can modify the RGB values of the input to cast a hue over the selected pixels without saturating them. It is only slightly more involved.
I = find(result);
gives you an index of the pixels in the 2D image. However, star is 3D. Those indices will point at the same pixels, but only at the first 2D slice. That is, if I points at pixel (x,y), it is equivalently pointing to pixel (x,y,1). That is the red component of the pixel. To index (x,y,2) and (x,y,2), the green and blue components, you need to increment I by numel(result) and 2*numel(result). That is, star(I) accesses the red component of the selected pixels, star(I+numel(result)) accesses the green component, and star(I+2*numel(result)) accesses the blue component.
Now that we can access these values, how do we modify their color?
This is what imoverlay does:
I = find(result);
out = star;
out(I) = 255; % red channel
I = I + numel(result);
out(I) = 0; % green channel
I = I + numel(result);
out(I) = 0; % blue channel
Instead, you can increase the brightness of the red proportionally, and decrease the green and blue. This will change the hue, increase saturation, and preserve the changes in intensity within the stars. I suggest the gamma function, because it will not cause strong saturation artefacts:
I = find(result);
out = double(star)/255;
out(I) = out(I).^0.5; % red channel
I = I + numel(result);
out(I) = out(I).^1.5; % green channel
I = I + numel(result);
out(I) = out(I).^1.5; % blue channel
imshow(out)
By increasing the 1.5 and decreasing the 0.5 you can make the effect stronger.

Export/Rasterize alpha shape to bitmap

I build an alpha shape from some points (example given in code) and want to export the shape to a raster graphics format. I need the shape only, not the plot markings (axis, scales ect).
I need only the resulting triangle on white ground as a bitmap.
Scale needs to be 1 unit = 1 pixel.
x = [0 10 20 30 30 30 15];
y = [0 0 0 0 15 30 15];
shape = alphaShape (x',y');
plot (shape, 'FaceColor', 'black');
I have not found anything on how to export shapes or how to rasterize them. Is there any way to do that?
Run the following code after yours.
imgwidth = max(1, ceil(max(x) - min(x)));
imgheight = max(1, ceil(max(y) - min(y)));
ax = gca;
ax.Visible = 'off';
ax.XTickMode = 'manual';
ax.YTickMode = 'manual';
ax.ZTickMode = 'manual';
ax.XLimMode = 'manual';
ax.YLimMode = 'manual';
ax.ZLimMode = 'manual';
ax.Position = ax.OuterPosition;
af = gcf;
figpos = getpixelposition(af);
resolution=get(0, 'ScreenPixelsPerInch');
set(af, 'paperunits','inches', ....
'papersize',[imgwidth imgheight]/resolution, ....
'paperposition',[0 0 [imgwidth imgheight]/resolution]);
print(af,'out.png','-dpng',['-r',num2str(resolution)],'-opengl')
Things done:
Fetch data range and convert to image dimensions.
Turn off axes and ticks.
Minimize/remove padding space surrounding the actual content.
Map 1 unit in data into 1 pixel in output image.
Things not done:
Guarantee aspect ratio. (should work, though)
This screenshot shows non-unity aspect ratio output:
References
Mathworks - Save Figure at Specific Size and Resolution
MATLAB Central - saving a figure at a set resolution
Mathworks - print
Mathworks - Save Figure with Minimal White Space

Colouring specific pixels in an image

Say I have an image. How can I colour some specific pixels in that image using MATLAB?
Thanks.
RGB Pixels
I'd suggest working with an RGB image, so that you can easily represent color and gray pixels. Here's an example of making two red blocks on an image:
img = imread('moon.tif');
imgRGB = repmat(img,[1 1 3]);
% get a mask of the pixels you want and set an RGB vector to those pixels...
colorMask = false(size(imgRGB,1),size(imgRGB,2));
colorMask(251:300,151:200,:) = true; % two discontiguous blocks
colorMask(50:100,50:100,:) = true;
redPix = permute([255 0 0],[1 3 2]);
imgRGB(repmat(colorMask,[1 1 3])) = repmat(redPix, numel(find(colorMask)),1);
AlphaData image property
Another cool way of doing this is with an image's AlphaData property. See this example on a MathWorks blog. This essentially turns color on or off in certain parts of the image by making the gray image covering the color image transparent. To work with a gray image, do like the following:
img = imread('moon.tif');
influenceImg = abs(randn(size(img)));
influenceImg = influenceImg / (2*max(influenceImg(:)));
imshow(img, 'InitialMag', 'fit'); hold on
green = cat(3, zeros(size(img)), ones(size(img)), zeros(size(img)));
h = imshow(green); hold off
set(h, 'AlphaData', influenceImg)
See the second example at the MathWorks link.

Contour detection in MATLAB

I am trying to understand this code:
d=edge(d,'canny',.6);
figure,
imshow(d,[])
ds = bwareaopen(d,40);
figure,
imshow(ds,[])
iout = d1;
BW=ds;
iout(:,:,1) = iout;
iout(:,:,2) = iout(:,:,1);
iout(:,:,3) = iout(:,:,1);
iout(:,:,2) = min(iout(:,:,2) + BW, 1.0);
iout(:,:,3) = min(iout(:,:,3) + BW, 1.0);
I understand that d is the image and canny detector is applied and 40 pixels are neglected. The image is gray scale and contour is added to the image.
Can you please explain the next lines? What principle/algorithm is used here? I am having trouble especially with the contour detection portion of the code.
Assuming that the variable d1 stores what is likely a double precision representation (values between 0 and 1) of the original grayscale intensity image that is operated on, then the last 5 lines will turn that grayscale image into a 3-D RGB image iout that looks the same as the original grayscale image except that the contours will be overlaid on the image in cyan.
Here's an example, using the image 'cameraman.tif' that is included with the MATLAB Image Processing Toolbox:
d1 = double(imread('cameraman.tif'))./255; % Load the image, scale from 0 to 1
subplot(2, 2, 1); imshow(d1); title('d1'); % Plot the original image
d = edge(d1, 'canny', .6); % Perform Canny edge detection
subplot(2, 2, 2); imshow(d); title('d'); % Plot the edges
ds = bwareaopen(d, 40); % Remove small edge objects
subplot(2, 2, 3); imshow(ds); title('ds'); % Plot the remaining edges
iout = d1;
BW = ds;
iout(:, :, 1) = iout; % Initialize red color plane
iout(:, :, 2) = iout(:, :, 1); % Initialize green color plane
iout(:, :, 3) = iout(:, :, 1); % Initialize blue color plane
iout(:, :, 2) = min(iout(:, :, 2) + BW, 1.0); % Add edges to green color plane
iout(:, :, 3) = min(iout(:, :, 3) + BW, 1.0); % Add edges to blue color plane
subplot(2, 2, 4); imshow(iout); title('iout'); % Plot the resulting image
And here is the figure the above code creates:
How it works...
The creation of the image iout has nothing to do with the edge detection algorithm. It's simply an easy way to display the edges found in the previous steps. A 2-D grayscale intensity image can't display color, so if you want to add colored contour lines to the image you have to first convert it to a format that will let you show color: either an indexed image (which is a little harder to deal with, in my experience) or a 3-D RGB image (the third dimension represents the red, green, and blue color components of each pixel).
Replicating the grayscale image 3 times in the third dimension gives us a 3-D RGB image that initially still contains gray colors (equal amounts of red, green, and blue per pixel). However, by modifying certain pixels of each color plane we can add color to the image. By adding the logical edge mask BW (ones where edges are and zeroes elsewhere) to the green and blue color planes, those pixels where the contours were found will appear cyan. The call to the function min ensures that the result of adding the images never causes a pixel color value to exceed the value 1.0, which is the maximum value an element should have for a double-precision 3-D RGB image.
It should also be noted that the code for creating the 3-D RGB image can be simplified to the following:
iout = d1;
iout(:, :, 2) = min(d1+ds, 1.0);
iout(:, :, 3) = min(d1+ds, 1.0);