MATLAB: building gradient between two columns in greyscale image - matlab

I have two images, one of which is a greyscale image (orig), the other is a binary image of the same size with vertical lines (mask). Where the binary value is 1 I would like on the grey scale to create a gradient from the two columns of values on either side of the binary line. For example:
binary: old greyscale: new greyscale:
0 0 1 1 1 0 0 x 10 x x x 6 x x 10 9 8 7 6 x
0 0 1 1 1 0 0 x 1 x x x 5 x x 1 2 3 4 5 x
0 0 1 1 1 0 0 x 5 x x x 13 x x 5 7 9 11 13 x
0 0 1 1 1 0 0 x 10 x x x 2 x x 10 8 6 4 2 x
I have the following code so far...not sure if its of any value...it runs through and finds the x location of the start of a vertical streak in vectempa, width in vectempb, and then the value from the greyscale on either side in vectemp1 and vectemp2. Current plan is to take the absolute value of difference of each column in vectemp1 and vectemp2, divide by that column in vectempb (width), and then use that to increment the gradient...somehow accounting for direction of the gradient. Does this make sense or is there a much better/easier way to do this?
vectempa=[];
vectempb=[];
vectemp1=[];
vectemp2=[];
q=1;
r=1;
for i=1:x
if mask(1,i)==0 && mask(1,(i+1))==1
vectempa(end+1)=i;
vectemp1(1:z,q)=orig((1:z),i);
q=q+1;
elseif mask(1,i)==1 && mask(1,(i+1))==0
vectempb(end+1)=i-vectempa(end);
vectemp2(1:z,r)=orig((1:z),i);
r=r+1;
end
end
Thanks!

Is it possible you are looking for roifill?
new = roifill( old, mask );

Related

Calculate pixel from coordinates

Hello I have this image:
This image has 16 pixels. White is 0, pink 1... like in image. My problem is that I need to calculate number of pixel from coordinates. If I have coordinates x = 3 and y = 3, I need to get black pixel with number 15.
How can I do that?
If you know how many pixels per row you have, you can simply use the next formula :
(y * numberPerRow) + x
Example using a 16 pixels images (4x4)
x
y
calcul
value
3
3
3 * 4 + 3
15
0
0
0 * 4 + 0
0
1
2
2 * 4 + 1
9

Create a matrix from a vector such that its height and width are powers of multiples in matlab

I have tried multiple solutions in matlab to convert a vector for example
A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
into
B= [ 1 2 3 4 ]
5 6 7 8
9 10 11 12
13 14 15 16
17 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Here the desired matrix is 8x4 or rather the height or width is any multiple of 4. This would mean the nearest greater multiple of 4 if we keep any one dimension(height or width) fixed for fitting all elements and padding the extra elements with zeroes. I have tried reshape like so
reshape([c(:) ; zeros(rem(nc - rem(numel(c),nc),nc),1)],nc,[])
Here c is the original vector or matrix, nc is the number of columns.
It simply changes the number of rows and cols but does not take into account the possible powers required by the condition for height and width. I don't have the Communications Toolbox which has the vec2mat function.
Another possible alternative thought is to initialize a matrix with all zeroes and then assign. But at this point I'm stuck. So please help me matlab experts.
i think this what you mean:
n = 4;
A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
B = zeros(n,ceil(numel(A)/n^2)*n);
B(1:numel(A)) = A;
B = B'
B = [ 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0]

Histogram of subblock matrix

Given some matrix, I want to divide it into blocks of size 2-by-2 and show a histogram for each of the blocks. The following is the code I wrote to solve the problem, but the sum of the histograms I'm generating is not the same as the histogram of the whole matrix. Actually the the sum of the blocks' histograms is double what I expected. What am I doing wrong?
im =[1 1 1 2 0 6 4 3; 1 1 0 4 2 9 1 2; 1 0 1 7 4 3 0 9; 2 3 4 7 8 1 1 4; 9 6 4 1 5 3 1 4; 1 3 5 7 9 0 2 5; 1 1 1 1 0 0 0 0; 1 1 2 2 3 3 4 4];
display(imhist(im));
[r c]=size(im);
bs = 2; % Block Size (8x8)
nob=[r c ]./ bs; % Total number of Blocks
% Dividing the image into 8x8 Blocks
kk=0;
for k=1:nob/2
for i=1:(r/bs)
for j=1:(c/bs)
Block(:,:,kk+j)=im((bs*(i-1)+1:bs*(i-1)+bs),(bs*(j-1)+1:bs*(j-1)+bs));
count(:,:,kk+j)=sum(sum(sum(hist(Block(:,:,kk+j)))));
p=sum(count(:,:,kk+j));
end
kk=kk+(r/bs);
end
end
The reason they aren't the same is because you use imhist for im and hist for the blocks. Hist separates data into 10 different bins based on your data range, imhist separates data based on the image type. Since your arrays are doubles, the imhist bins are from 0 to 1.0 Thats why your imhist has only values at 0, and 1. The hist produces bins based on your data range, so it will actually change slightly depending on what value you pass in. So you cant simply add bins together. Even though they are the same size vector 10x1 , the values in them can be very different. in one set bin(1) can be the range 1-5 but in another set of data bin(1) could be 1-500.
To fix all these issues I used imhist, and converted your data to uint8. At the very end I subtract the two histograms from one another and get zero, this shows that they are indeed the same
im =uint8([1 1 1 2 0 6 4 3 ;
1 1 0 4 2 9 1 2 ;
1 0 1 7 4 3 0 9 ;
2 3 4 7 8 1 1 4 ;
9 6 4 1 5 3 1 4 ;
1 3 5 7 9 0 2 5 ;
1 1 1 1 0 0 0 0 ;
1 1 2 2 3 3 4 4 ]);
orig_imhist = imhist(im);
%% next thing
[r c]=size(im);
bs=2; % Block Size (8x8)
nob=[r c ]./ bs; % Total number of Blocks
%creates arrays ahead of time
block = uint8(zeros(bs,bs,nob(1)*nob(2)));
%we use 256, because a uint8 has 256 values, or 256 'bins' for the
%histogram
block_imhist = zeros(256,nob(1)*nob(2));
sum_block_hist = zeros(256,1);
% Dividing the image into 2x2 Blocks
for i = 0:nob(1)-1
for j = 0:nob(2)-1
curr_block = i*nob(1)+(j+1);
%creates the 2x2 block
block(:,:,curr_block) = im(bs*i+1:bs*i+ bs,bs*j+1:bs*j+ bs);
%creates a histogram for the block
block_imhist(:,curr_block) = imhist(block(:,:,curr_block));
%adds the current histogram to the running sum
sum_block_hist = sum_block_hist + block_imhist(:,curr_block);
end
end
%shows that the two are the same
sum(sum(orig_imhist-sum_block_hist))
if my solution solves your problem please mark it as the answer

Find Value at a given Orientation in Matrix

In Matlab I've matrix where, in a previous stage of my code, an specific element was chosen. From this point of the matrix I would like to find a maximum, not just the maximum value between all its surounding neighbours for a given radius, but the maximum value at a given angle of orientation. Let me explain this with an example:
This is matrix A:
A =
0 1 1 1 0 0 9 1 0
0 2 2 4 3 2 8 1 0
0 2 2 3 3 2 2 1 0
0 1 1 3 2 2 2 1 0
0 8 2 3 3 2 7 2 1
0 1 1 2 3 2 3 2 1
The element chosen in the first stage is the 4 in A(2,4), and the next element should be the maximum value with, for example, a 315 degrees angle of orientation, that is the 7 in A(5,7).
What I've done is, depending on the angle, subdivide matrix A in different quadrants and make a new matrix (an A's submatrix) with only the values of that quadrant.
So, for this example, the submatrix will be A's 4th quadrant:
q_A =
4 3 2 8 1 0
3 3 2 2 1 0
3 2 2 2 1 0
3 3 2 7 2 1
2 3 2 3 2 1
And now, here is my question, how can I extract the 7?
The only thing I've been able to do (and it works) is to find all the values over a threshold value and then calculate how those points are orientated. Then, saving all the values that have a similar orientation to the given one (315 degrees in this example) and finally finding the maximum among them. It works but I guess there could be a much faster and "cleaner" solution.
This is my theory, but I don't have the image processing toolbox to test it. Maybe someone who does can comment?
%make (r,c) the center by padding with zeros
if r > size(A,1)/2
At = padarray(A, [size(A,1) - r], 0, 'pre');
else
At = padarray(A, [r-1], 0 'post');
if c > size(A,2)/2
At = padarray(At, [size(A,2) - c], 0, 'pre');
else
At = padarray(At, [c-1], 0 'post');
%rotate by your angle (maybe this should be -angle or else 360-angle or 2*pi-angle, I'm not sure
Ar = imrotate(At,angle, 'nearest', 'loose'); %though I think nearest and loose are defaults
%find the max
max(Ar(size(Ar,1)/2, size(Ar,2)/2:end); %Obviously you must adjust this to handle the case of odd dimension sizes.
Also depending on your array requirements, padding with -inf might be better than 0
The following is a relatively inexpensive solution to the problem, although I found wrapping my head around the matrix coordinate system a real pain, and there is probably room to tidy it up somewhat. It simply traces all matrix entries along a line around the starting point at the supplied angle (all coordinates and angles are of course based on matrix index units):
A = [ 0 1 1 1 0 0 9 1 0
0 2 2 4 3 2 8 1 0
0 2 2 3 3 2 2 1 0
0 1 1 3 2 2 2 1 0
0 8 2 3 3 2 7 2 1
0 1 1 2 3 2 3 2 1 ];
alph = 315;
r = 2;
c = 4;
% generate a line through point (r,c) with angle alph
[nr nc] = size(A);
x = [1:0.1:nc]; % overkill
m = tan(alph);
b = r-m*c;
y = m*x + b;
crd = unique(round([y(:) x(:)]),'rows');
iok = find((crd(:,1)>0) & (crd(:,1)<=nr) & (crd(:,2)>0) & (crd(:,2)<=nc));
crd = crd(iok,:);
indx=sub2ind([nr,nc],crd(:,1),crd(:,2));
% find max and position of max
[val iv]=max(A(indx)); % <-- val is the value of the max
crd(iv,:) % <-- matrix coordinates (row, column) of max value
Result:
val =
7
iv =
8
ans =
5 7

How can I find local maxima in an image in MATLAB?

I have an image in MATLAB:
y = rgb2gray(imread('some_image_file.jpg'));
and I want to do some processing on it:
pic = some_processing(y);
and find the local maxima of the output. That is, all the points in y that are greater than all of their neighbors.
I can't seem to find a MATLAB function to do that nicely. The best I can come up with is:
[dim_y,dim_x]=size(pic);
enlarged_pic=[zeros(1,dim_x+2);
zeros(dim_y,1),pic,zeros(dim_y,1);
zeros(1,dim_x+2)];
% now build a 3D array
% each plane will be the enlarged picture
% moved up,down,left or right,
% to all the diagonals, or not at all
[en_dim_y,en_dim_x]=size(enlarged_pic);
three_d(:,:,1)=enlarged_pic;
three_d(:,:,2)=[enlarged_pic(2:end,:);zeros(1,en_dim_x)];
three_d(:,:,3)=[zeros(1,en_dim_x);enlarged_pic(1:end-1,:)];
three_d(:,:,4)=[zeros(en_dim_y,1),enlarged_pic(:,1:end-1)];
three_d(:,:,5)=[enlarged_pic(:,2:end),zeros(en_dim_y,1)];
three_d(:,:,6)=[pic,zeros(dim_y,2);zeros(2,en_dim_x)];
three_d(:,:,7)=[zeros(2,en_dim_x);pic,zeros(dim_y,2)];
three_d(:,:,8)=[zeros(dim_y,2),pic;zeros(2,en_dim_x)];
three_d(:,:,9)=[zeros(2,en_dim_x);zeros(dim_y,2),pic];
And then see if the maximum along the 3rd dimension appears in the 1st layer (that is: three_d(:,:,1)):
(max_val, max_i) = max(three_d, 3);
result = find(max_i == 1);
Is there any more elegant way to do this? This seems like a bit of a kludge.
bw = pic > imdilate(pic, [1 1 1; 1 0 1; 1 1 1]);
If you have the Image Processing Toolbox, you could use the IMREGIONALMAX function:
BW = imregionalmax(y);
The variable BW will be a logical matrix the same size as y with ones indicating the local maxima and zeroes otherwise.
NOTE: As you point out, IMREGIONALMAX will find maxima that are greater than or equal to their neighbors. If you want to exclude neighboring maxima with the same value (i.e. find maxima that are single pixels), you could use the BWCONNCOMP function. The following should remove points in BW that have any neighbors, leaving only single pixels:
CC = bwconncomp(BW);
for i = 1:CC.NumObjects,
index = CC.PixelIdxList{i};
if (numel(index) > 1),
BW(index) = false;
end
end
Alternatively, you can use nlfilter and supply your own function to be applied to each neighborhood.
This "find strict max" function would simply check if the center of the neighborhood is strictly greater than all the other elements in that neighborhood, which is always 3x3 for this purpose. Therefore:
I = imread('tire.tif');
BW = nlfilter(I, [3 3], #(x) all(x(5) > x([1:4 6:9])) );
imshow(BW)
In addition to imdilate, which is in the Image Processing Toolbox, you can also use ordfilt2.
ordfilt2 sorts values in local neighborhoods and picks the n-th value. (The MathWorks example demonstrates how to implemented a max filter.) You can also implement a 3x3 peak finder with ordfilt2 with the following logic:
Define a 3x3 domain that does not include the center pixel (8 pixels).
>> mask = ones(3); mask(5) = 0 % 3x3 max
mask =
1 1 1
1 0 1
1 1 1
Select the largest (8th) value with ordfilt2.
>> B = ordfilt2(A,8,mask)
B =
3 3 3 3 3 4 4 4
3 5 5 5 4 4 4 4
3 5 3 5 4 4 4 4
3 5 5 5 4 6 6 6
3 3 3 3 4 6 4 6
1 1 1 1 4 6 6 6
Compare this output to the center value of each neighborhood (just A):
>> peaks = A > B
peaks =
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0
or, just use the excellent: extrema2.m