How to generate a gaussian map with an effective y for an Equator Bias weighing? - image

I'm trying to add an Equator Bias weighing to an image, for that I'm using a Gaussian distribution and generate a weighing map to fuse it with the image. The following code is used to generate the weights map:
function map = gaussian_map(height, width)
if (width>8000)
density = 8*height;
elseif (width>4000 & width<=8000)
density = 8*height;
elseif (width>2000 & width<=4000)
density = 4*height;
else
density = 2*height;
end
beta = height/2;
for x = 1:height
for y = 1:width
map(x,y) = exp(-(x-beta)*(x-beta)/density);
end
end
end
Which gives something like this :
Update:
As we can see the distribution starts with y = 0. What I need is that this later starts let say y = 0.3 and all weights must be within [0, 1], something that should look like this:
I've done some googling but I couldn't find much information.
Thanks in advance.

Related

How can we detect these points in this case?

I have a data of pulse train samples as amplitude samples with equal intervals.
Let's call the sampled pulse amplitude array as A and time array as t.
So the plot is obtained by plot(t, A) in MATLAB.
Here below is plot of the pulse train:
And below is the zoomed version(green dots are samples, reds circles are max points):
What I need to do is, I need an algorithm which can detect and save the max point of each pulse(I circled them in red above) into an array.
So far I tried the following but didn't work:
kk = 0
for i=1:length(t)-2
if y(i)>0 & y(i+1)>y(i) & y(i+2)>y(i+1) & y(i+3)<y(i+2)
kk = kk+1;
maxPointTime(kk) = t(i+2);
maxPointVoltage(kk) = A(i+2);
end
end
So you want to find the local maxima, right? MATLAB has a build in function to do so, cf. doc.
x = 1:100;
A = (1-cos(2*pi*0.01*x)).*sin(2*pi*0.15*x);
TF = islocalmax(A);
plot(x,A,x(TF),A(TF),'r*')

Kalman FIlter Convergence

Attached is a simple python Kalman filter example of a free-fall object (g=-9.8m/s^2)
Alas, I have a problem. The state vector x contains both the position and the velocity but the z vector (measurement) contains only the position.
If I set a wrong initial position value, the algorithm coverages to the true value even with noisy measurements (see picture below)
However, if I sent the wrong initial velocity value, the algorithm does not converge even though the motion model is defined correctly.
Attached is the python code:
kalman.py
In your code I see two problems.
You set the Q-Matrix to zero. It means you trust too much in your model and give the filter no chance to improve the estimation through the measurement. Your filter becomes to stiff. You can think of it like a low pass filter with a very big time constant.
In my code I set the Q-Matrix to
Q = np.array([[1,0],[0,0.1]])
The second issue is your measurement noise. You simulate the noisy measurements with R=100 but communicate to the filter R=4. The filter trusts the measurement more than it should be. This issue is not really relevant to your question but still it should be corrected.
Now even if I set the initial velocity to 20, the position estimation works fine.
Here is the estimation for R = 4:
And for R = 100:
UPDATE
The velocity estimation works wrong, because you have some mistakes in your matrix operations. Please note, the matrix multiplication goes through np.dot(), not through *.
Here is a correct result for v0 = 20:
Many thanks, Anton.
Attached below is the corrected code for your convenience:
Roi
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
from numpy.linalg import inv
N = 1000 # number of time steps
dt = 0.01 # Sampling time (s)
t = dt*np.arange(N)
F = np.array([[1, dt],[ 0, 1]])# system matrix - state
B = np.array([[-1/2*dt**2],[ -dt]])# system matrix - input
H = np.array([[1, 0]])#; % observation matrix
Q = np.array([[1,0],[0,1]])
u = 9.80665# % input = acceleration due to gravity (m/s^2)
I = np.array([[1,0],[0,1]]) #identity matrix
# Define the initial position and velocity
y0 = 100; # m
v0 = 0; # m/s
G2 = np.array([-1/2*dt**2, -dt])# system matrix - input
# Initialize the state vector (true state)
xt = np.zeros((2, N)) # True state vector
xt[:,0] = [y0,v0]
for k in range(1,N):
xt[:,k] = np.dot(F,xt[:,k-1]) +G2*u
#Generate the noisy measurement from the true state
R = 4 # % m^2/s^2
v = np.sqrt(R)*np.random.randn(N) #% measurement noise
z = np.dot(H,xt) + v; #% noisy measurement
R2=4
#% Initialize the covariance matrix
P = np.array([[10, 0], [0, 0.1]])# Covariance for initial state error
#% Loop through and perform the Kalman filter equations recursively
x_list =[]
x_kalman= np.array([[117],[290]])
x_list.append(x_kalman)
print(-B*u)
for k in range(1,N):
x_kalman=np.dot(F,x_kalman) +B*u
P = np.dot(np.dot(F,P),F.T) +Q
S=(np.dot(np.dot(H,P),H.T) + R2)
S2 = inv(S)
K = np.dot(P,H.T)*S2
x_kalman = x_kalman +K*((z[:,k]- np.dot(H,x_kalman)))
P = np.dot((I - K*H),P)
x_list.append(x_kalman)
x_array = np.array(x_list)
print(x_array.shape)
plt.figure()
plt.plot(t,z[0,:], label="measurment", color='LIME', linewidth=1)
plt.plot(t,x_array[:,0,:],label="kalman",linewidth=5)
plt.plot(t,xt[0,:],linestyle='--', label = "Truth",linewidth=6)
plt.legend(fontsize=30)
plt.grid(True)
plt.xlabel("t[s]")
plt.title("Position Estimation", fontsize=20)
plt.ylabel("$X_t$ = h[m]")
plt.gca().set( ylim=(0, 110))
plt.gca().set(xlim=(0,6))
plt.figure()
#plt.plot(t,z, label="measurment", color='LIME')
plt.plot(t,x_array[:,1,:],label="kalman",linewidth=4)
plt.plot(t,xt[1,:],linestyle='--', label = "Truth",linewidth=2)
plt.legend()
plt.grid(True)
plt.xlabel("t[s]")
plt.title("Velocity Estimation")
plt.ylabel("$X_t$ = h[m]")

Find out which blob has the pixel location [x,y]?

I have a labelled blob image using bwlabel, I want to find a blob which has the pixel location [x,y] and display it by removing the rest of blobs.
Here is the code I wrote, but it doesn't give correct answer, please fix this
[y, x] = ginput(1);
x = round(x);
y = round(y); % here x and y is a location of blob i want to keep
BW = bwlabel(newImgg,4) ; % labelled image contains several blobs
% figure, imshow(BW, [])
props = regionprops(logical(BW),'all');
while(1)
for k = 2:length(props)
if ismember([x,y],props(k,1).PixelList) == [1, 1];
keeperIndex = k;
break
end
end
break
end
keeperBlobsImage = ismember(BW, keeperIndex);
keeperBlobsImage = imfill(keeperBlobsImage,'holes');
figure, imshow(keeperBlobsImage,[])
Thanks,
Gopi
I do not currently have a MATLAB license, so I wouldn't be able to test this on my machine, I've also been away from MATLAB syntax for a while. Here's an idea:
From MATLAB's documentation, PixelList is an array where each row is formatted [x,y,...], depending on your dimensions.
Working with your image I'm assuming PixelList has the format [x,y]
Looping through PixelList, keep track of the indices you want to discard. If you measured n pixels:
discardList = []
for i = 1:n
if (PixelList(i) != [target_x,target_y]
discardList=[discardList,i]
end
end
newPixelList = PixelList
newPixelList(discardList) = []
Again, I haven't used MATLAB for a decent amount of time now, so I apologize for any problems in the syntax (brackets, loops, and conditionals)
EDIT/UPDATE:
According to the MATLAB's documentation, it shows bwlabel being used only on a BW image. So make sure you're doing that, I guess.
Also, on the output of regionprops you should have WeightedCentroid.
From your ginput, find the region where the centroid is the closest.
My suggestion would be to use the vision.BlobAnalysis System Object
[y,x] = ginput(1)
bA = vision.BlobAnalysis;
centroids = step(bA,BWImage);
using the documentation make sure you turn off all "output ports" of the system object, and keep the centroid output port on.
d = 1e10;
d2 = 0;
dArr = [x,y;0,0]
cIndex=0;
for i = 1:length(centroids)
dArr(2,:) = centroids(i,:);
d2 = pdist(dArr);
if (d2<d)
d = d2;
cIndex = i;
end
end
The variable cIndex will contain the index of the blob you need. You can run blob analysis and isolate it from the rest

how to get more accurate point position in an image

usually, we can get point position in an image in this way:
figure, imshow rice.png;
[x,y,~] = ginput(1)
what returned is something like this:
x = 121
y = 100
these numbers are measured by pixels, but I'd like more accurate results like:
x = 121.35
y = 100.87
any help would be appreicated!!!
I think imagesc can be useful
% load example image
Istruct = load('gatlin');
I = Istruct.X./max(Istruct.X(:));
% display it
figure;
imagesc(I);
colormap(gray);
% get some point
[x,y]=ginput(1);
[x, y] % x and y will be double
For aligning / registering two images using control points you do need sub-pixel accuracy for the different control points.
Matlab has a very nice user interface for this purpose you might want to look at: cpselect.
A nice tutorial is also available here.
Given two images oim1 and oim2 you may use cpselect to transform oim2 to "fit" oim1:
>> [input_points, base_points] = cpselect(oim2, oim1, 'Wait', true);
>> T = cp2tform( input_points, base_points, 'similarity' ); % find similarity transformation
>> aim2 = tformarray( oim2, T, makeresampler('cubic','fill'), [2 1], [2 1], size(oim1(:,:,1)'), [], 0 );

Plot images as axis labels in MATLAB

I am plotting a 7x7 pixel 'image' in MATLAB, using the imagesc command:
imagesc(conf_matrix, [0 1]);
This represents a confusion matrix, between seven different objects. I have a thumbnail picture of each of the seven objects that I would like to use as the axes tick labels. Is there an easy way to do this?
I don't know an easy way. The axes properties XtickLabel which determines the labels, can only be strings.
If you want a not-so-easy way, you could do something in the spirit of the following non-complete (in the sense of a non-complete solution) code, creating one label:
h = imagesc(rand(7,7));
axh = gca;
figh = gcf;
xticks = get(gca,'xtick');
yticks = get(gca,'ytick');
set(gca,'XTickLabel','');
set(gca,'YTickLabel','');
pos = get(axh,'position'); % position of current axes in parent figure
pic = imread('coins.png');
x = pos(1);
y = pos(2);
dlta = (pos(3)-pos(1)) / length(xticks); % square size in units of parant figure
% create image label
lblAx = axes('parent',figh,'position',[x+dlta/4,y-dlta/2,dlta/2,dlta/2]);
imagesc(pic,'parent',lblAx)
axis(lblAx,'off')
One problem is that the label will have the same colormap of the original image.
#Itmar Katz gives a solution very close to what I want to do, which I've marked as 'accepted'. In the meantime, I made this dirty solution using subplots, which I've given here for completeness. It only works up to a certain size input matrix though, and only displays well when the figure is square.
conf_mat = randn(5);
A = imread('peppers.png');
tick_images = {A, A, A, A, A};
n = length(conf_mat) + 1;
% plotting axis labels at left and top
for i = 1:(n-1)
subplot(n, n, i + 1);
imshow(tick_images{i});
subplot(n, n, i * n + 1);
imshow(tick_images{i});
end
% generating logical array for where the confusion matrix should be
idx = 1:(n*n);
idx(1:n) = 0;
idx(mod(idx, n)==1) = 0;
% plotting the confusion matrix
subplot(n, n, find(idx~=0));
imshow(conf_mat);
axis image
colormap(gray)

Resources