Replace a certain color in an image with another color Matlab - matlab

I have an image that I opened in Matlab using imshow and I want to replace the color of every pixel with value (140,50,61) with a new color (150,57,80). If anyone could please advise how I can do this.

Assuming A to be the input image data, this could be one approach -
%// Initialize vectors for old and new pixels tuplets
oldval = [140,50,61]
newval = [150,57,80]
%// Reshape the input array to a 2D array, so that each column would
%// reprsent one pixel color information.
B = reshape(permute(A,[3 1 2]),3,[])
%// Find out which columns match up with the oldval [3x1] values
matches = all(bsxfun(#eq,B,oldval(:)),1)
%// OR matches = matches = ismember(B',oldval(:)','rows')
%// Replace all those columns with the replicated versions of oldval
B(:,matches) = repmat(newval(:),1,sum(matches))
%// Reshape the 2D array back to the same size as input array
out = reshape(permute(B,[3 2 1]),size(A))
Sample run -
>> A
A(:,:,1) =
140 140 140
40 140 140
A(:,:,2) =
50 20 50
50 50 50
A(:,:,3) =
61 65 61
61 61 61
>> out
out(:,:,1) =
150 140 150
40 150 150
out(:,:,2) =
57 20 57
50 57 57
out(:,:,3) =
80 65 80
61 80 80

bsxfun is the way I would have solved it. However, if you aren't familiar with it, you can extract each channel from your image, use three logical masks for each channel and combine them all using logical AND. Doing AND will find those pixels in your image that looks for that particular RGB triple.
As such, we set the outputs of each channel accordingly and reconstruct the image to produce the output.
Therefore, given your input image A, one could do:
red = A(:,:,1); green = A(:,:,2); blue = A(:,:,3);
mred = red == 140; mgreen = green == 50; mblue = blue == 61;
final_mask = mred & mgreen & mblue;
red(final_mask) = 150; green(final_mask) = 57; blue(final_mask) = 80;
out = cat(3, red, green, blue);

Related

Color of errobar different from the graph matlab

i have this problem i want to make a color of errobars different from the color of my graph
there is the code i have tried
pp=errorbar(x,testMatriceFluxSortie/ValeurFluxSortie(1,1),err)
pp.Color=[255 0 1]./255;
But it gives me this all in red
my graph
you can always use hold on and plot only the x,y data after the errorbar was plotted, for example:
x = 1:10:100;
y = [20 30 45 40 60 65 80 75 95 90];
err = 8*ones(size(y));
errorbar(x,y,err,'or'); hold on
plot(x,y,'b');

3D histogram and conditional coloring

I have a series of ordered points (X, Y, Z) and I want to plot a 3D histogram, any suggestions?
I'm trying to do it by this tutorial http://www.mathworks.com/help/stats/hist3.html , but points are random here and presented as a function. My example is easier, since i already know the points.
Furthermore, depending on the number value of Z coordinate, i'd like to colour it differently. E.g. Max value - green, min value - red. Similar as in this case Conditional coloring of histogram graph in MATLAB, only in 3D.
So, if I have a series of points:
X = [32 64 32 12 56 76 65]
Y = [160 80 70 48 90 80 70]
Z = [80 70 90 20 45 60 12]
Can you help me with the code for 3D histogram with conditional coloring?
So far the code looks like this:
X = [32 64 32 12 56 76 65];
Y= [160 80 70 48 90 80 70];
Z= [80 70 90 20 45 60 12];
A = full( sparse(X',Y',Z'));
figure;
h = bar3(A); % get handle to graphics
for k=1:numel(h),
z=get(h(k),'ZData'); % old data - need for its NaN pattern
nn = isnan(z);
nz = kron( A(:,k),ones(6,4) ); % map color to height 6 faces per data point
nz(nn) = NaN; % used saved NaN pattern for transparent faces
set(h(k),'CData', nz); % set the new colors
end
colorbar;
Now I just have to clear the lines and design the chart to make it look useful. But how would it be possible to make a bar3 without the entire mesh on 0 level?
Based on this answer, all you need to do is rearrange your data to match the Z format of that answer. After than you might need to remove edgelines and possibly clear the zero height bars.
% Step 1: rearrange your data
X = [32 64 32 12 56 76 65];
Y= [160 80 70 48 90 80 70];
Z= [80 70 90 20 45 60 12];
A = full( sparse(X',Y',Z'));
% Step 2: Use the code from the link to plot the 3D histogram
figure;
h = bar3(A); % get handle to graphics
set(h,'edgecolor','none'); % Hopefully this will remove the lines (from https://www.mathworks.com/matlabcentral/newsreader/view_thread/281581)
for k=1:numel(h),
z=get(h(k),'ZData'); % old data - need for its NaN pattern
nn = isnan(z);
nz = kron( A(:,k),ones(6,4) ); % map color to height 6 faces per data point
nz(nn) = NaN; % used saved NaN pattern for transparent faces
nz(nz==0) = NaN; % This bit makes all the zero height bars have no colour
set(h(k),'CData', nz); % set the new colors. Note in later versions you can do h(k).CData = nz
end
colorbar;

Matlab - Create a vector using another vector as the limits

Say I have the following columns vector Z
1 53 55 57 60 64 68 70 71 72 74 76 77 78 79 80 255
I want to use it to create a matrix such that each row would contain all the number between (and including) 2 adjacent elements in Z
So the output matrix should be something like this:
1 2 3 .... 53
53 54 55
55 56 57
57 58 60
....
80 81 ... 255
I've been searching for something similar but couldn't find it.
Thanks
See if this works for you -
lens = diff(Z)+1;
mask1 = bsxfun(#le,[1:max(lens)]',lens); %//'
array1 = zeros(size(mask1));
array1(mask1) = sort([1:255 Z(2:end-1)]);
out = array1.'; %//'# out is the desired output
Try this to break the monotony of bsxfun :) :
d = diff(Z);
N = max(d)+1;
R = zeros(length(Z)-1,N);
for i = 1:length(Z)-1
R(i,1:1+d(i)) = Z(i):Z(i+1);
end
EDIT:
I know that the general consensus is that one always should try to avoid loops in Matlab, but is this valid for this example? I know that this is a broad question, so lets focus on this particular problem and compare bsxfun to JIT loop. Comparing the two proposed solutions:
the code used for testing:
Z = [1 53 55 57 60 64 68 70 71 72 74 76 77 78 79 80 255];
%[1 3 4, 6];
nn = round(logspace(1,4,10));
tm1_nn = zeros(length(nn),1);
tm2_nn = zeros(length(nn),1);
for o = 1:length(nn)
tm1 = zeros(nn(o),1);
tm2 = zeros(nn(o),1);
% approach1
for k = 1:nn(o)+1
tic
d = diff(Z);
N = max(d)+1;
R = zeros(length(Z)-1,N);
for i = 1:length(Z)-1
R(i,1:1+d(i)) = Z(i):Z(i+1);
end
tm1(k) = toc;
end
%approach 2
for k = 1:nn(o)+1
tic
lens = diff(Z)+1;
mask1 = bsxfun(#le,[1:max(lens)]',lens); %//'
array1 = zeros(size(mask1));
array1(mask1) = sort([1:255 Z(2:end-1)]);
out = array1.';
tm2(k) = toc;
end
tm1_nn(o) = mean(tm1);%sum(tm1);%mean(tm1);%
tm2_nn(o) = mean(tm2);%sum(tm2);%mean(tm2);%
end
semilogx(nn,tm1_nn, '-ro', nn,tm2_nn, '-bo')
legend('JIT loop', 'bsxfun')
xlabel('log_1_0(Number of runs)')
%ylabel('Sum execution time')
ylabel('Mean execution time')
grid on
I encountered other tasks previously where the loop was faster. (or I mess up the comparison?)

Conditional coloring of histogram graph in MATLAB

I have a histogram that I want conditional coloring in it with this rule :
Values that are upper than 50 have red bars and values lower than 50 have blue bars.
Suppose that we have this input matrix:
X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65];
I want default bins of MATLAB and applying this coloring on X-axes (bins). I'm using GUIDE to design my GUI and this histogram is an axes in my GUI.
This is our normal graph. Bars with upper values than 50 should be red and bars with lower values than 50 should be green (X-axes). Bars with upper values than 50 should be red and ?
I think this does what you want (as per comments). The bar around 50 is split into the two colors. This is done by using a patch to change the color of part of that bar.
%// Data:
X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65]; %// data values
D = 50; %// where to divide into two colors
%// Histogram plot:
[y n] = hist(X); %// y: values; n: bin centers
ind = n>50; %// bin centers: greater or smaller than D?
bar(n(ind), y(ind), 1, 'r'); %// for greater: use red
hold on %// keep graph, Or use hold(your_axis_handle, 'on')
bar(n(~ind), y(~ind), 1, 'b'); %// for smaller: use blue
[~, nd] = min(abs(n-D)); %// locate bar around D: it needs the two colors
patch([(n(nd-1)+n(nd))/2 D D (n(nd-1)+n(nd))/2], [0 0 y(nd) y(nd)], 'b');
%// take care of that bar with a suitable patch
X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65];
then you create an histogram, but you are only going to use this to get the numbers of bins, the numbers of elements and positions:
[N,XX]=hist(X);
close all
and finally here is the code where you use the Number of elements (N) and the position (XX) of the previous hist and color them
figure;
hold on;
width=8;
for i=1:length(N)
h = bar(XX(i), N(i),8);
if XX(i)>50
col = 'r';
else
col = 'b';
end
set(h, 'FaceColor', col)
end
here you can consider using more than one if and then you can set multiple colors
cheers
First sort X:
X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65];
sorted_X = sort(X)
sorted_X :
sorted_X =
Columns 1 through 14
12 32 32 44 56 56 64 65 65 76 78 86 87 89
Columns 15 through 18
90 95 96 100
Then split the data based on 50:
idx1 = find(sorted_X<=50,1,'last');
A = sorted_X(1:idx1);
B = sorted_X(idx1+1:end);
Display it as two different histograms.
hist(A);
hold on;
hist(B);
h = findobj(gca,’Type’,’patch’);
display(h)
set(h(1),’FaceColor’,’g’,’EdgeColor’,’k’);
set(h(2),’FaceColor’,’r’,’EdgeColor’,’k’);

Most repeated values

I know how to check an 8-neighbourhood in matlab (i.e; nlfilter). But, I want to assign the value which is more repeated to the center value. So, say for instance that I have the following values in the 8-neighbourhood:
2-values = 56
3-values = 64
1-value = 70
1-value = 87
1-value = 65
In this case we would assign 64 to the center pixel.
How can we do that?
Thanks.
I think you want either the mode or the histc function.
M=mode(X) for vector X computes M as the sample mode, or most
frequently
occurring value in X.
Example with your data:
x = [56 56 64 64 64 70 87 65];
mode(x)
ans =
64
But this will only get you the most frequently occurring value.
If you want the count of each unique item in the array, you could do,
unqx = unique(x);
unqx =
56 64 65 70 87
valueCount = histc(x, unqx)
ans =
2 3 1 1 1
You could then sort this and take the first N values
valueCount = sort(valueCount, 'descend');
% Use unqx(valueCount(1:N))