How to use the placeholders in tensoflow to take an arbitrary matrix? - matrix

I am new to using Tensorflow.
I have two matrices that I want to take as input:
and my output matrix is as such:
When I do:
import tensorflow as tf
matrix1 = tf.placeholder();
matrix2 = tf.placeholder();
output_matrix = tf.placeholder();
is that enough? I do not know how I can define the shape of the matrix and the dtype if the matrices are arbitrary?

It's fine to leave the shape unspecified for a placeholder; you'll be able to feed anything that works with the downstream ops. Dtype will default to float32. But you do need to specify a sequence of transformations which go from your inputs (placeholders) to your outputs (not placeholders); see https://www.tensorflow.org/get_started/mnist/mechanics#build_the_graph.
If it's easier, you can also get started with eager execution, then switch to graph building later.

Related

Multiplying matrices across tenor axis with numpy and with GPU

I have a matrix X with shape (F,T,M). I wish to multiply each (T,M) matrix along the F axis so that the answer will be of shape (M,M,F). This code does the job for me but this operation repeats many times and it is very slow:
for f in range(F):
output[:,:,f] = np.matmul(X[f,:,:].T,X[f,:,:])
All I could find is np.tensordot() function. If I understand correctly, this is not a good option for me since I need a matrix multiplication and not a dot product.
How do I implement this efficiently using numpy? Is it possible and beneficial to utilize keras\tf for this purpose?
We can use np.matmul/# opeartor in Python 3.x after extending dimensions -
np.matmul(X.swapaxes(1,2),X).swapaxes(0,2)
(X.swapaxes(1,2)#X).swapaxes(0,2)
Alternatively, with np.einsum with a direct translation off the shape variables used for the string notation -
np.einsum('ftm,ftn->mnf',X,X)

Failed to convert structure to matrix with regionprops in MATLAB

I am working with particle tracking in images in MATLAB and using regionprops function. On the provided resource there is an example with circles:
stats = regionprops('table',bw,'Centroid',...
'MajorAxisLength','MinorAxisLength')
centers = stats.Centroid;
diameters = mean([stats.MajorAxisLength stats.MinorAxisLength],2);
radii = diameters/2;
In my Matlab R2014b, the line centers = stats.Centroid; produces undesired result: my stats.Centroid structure has 20 elements (each element is two numbers - the coordinates of the center of the region). However, after the following command, my variable center is only 1x2 matrix, instead of desired 20x2.
Screenshot attached.
I tried to go around this with different methods. The only solution I found is to do:
t=zeros(20,2);
for i=1:20
t(i,:)=stats(i).Centroid;
end
However, as we all know loops are slow in MATLAB. Is there another method that takes advantage of MATLAB matrix operations?
Doing stats.Centroid would in fact give you a comma-separated list of centroids, so MATLAB would only give you the first centre of that matrix if you did centers = stats.Centroid. What you must do is encapsulate the centres in an array (i.e. [stats.Centroid]), then reshape when you're done.
Something like this should work for you:
centers = reshape([stats.Centroid], 2, []).';
What this will do is read in the centroids as a 1 x 2*M array where M is the total number of blobs and because MATLAB does reshaping in column-major format, you should make sure that specify the total number of rows to be 2 and let MATLAB figure out how many columns there are after by itself. You would then transpose the result when you're done to complete what you want.
Minor Note
If you look at the regionprops documentation page in their Tips section - http://www.mathworks.com/help/images/ref/regionprops.html#buorh6l-1, you will see that they surround stats.Area, which is the area of each blob with [] brackets to ensure that the comma-separated list of values is encapsulated in an array. This is not an accident and there is a purpose of having those there and I've basically told you what that was.

MATLAB: Set points within plot polygon equal to zero

I am currently doing some seismic modelling and processing in MATLAB, and would like to come up with an easy way of muting parts of various datasets. If I plot the frequency-wavenumber spectrum of some of my data, for instance, I obtain the following result:
Now, say that I want to mute some of the data present here. I could of course attempt to run through the entire matrix represented here and specify a threshold value where everything above said value should be set equal to zero, but this will be very difficult and time-consuming when I later will work with more complicated fk-spectra. I recently learned that MATLAB has an inbuilt function called impoly which allows me to interactively draw a polygon in plots. So say I, for instance, draw the following polygon in my plot with the impoly-function:
Is there anything I can do now to set all points within this polygon equal to zero? After defining the polygon as illustrated above I haven't found out how to proceed in order to mute the information contained in the polygon, so if anybody can give me some help here, then i would greatly appreciate it!
Yes, you can use the createMask function that's part of the impoly interface once you delineate the polygon in your figure. Once you use create this mask, you can use the mask to index into your data and set the right regions to zero.
Here's a quick example using the pout.tif image in MATLAB:
im = imread('pout.tif');
figure; imshow(im);
h = impoly;
I get this figure and I draw a polygon inside this image:
Now, use the createMask function with the handle to the impoly call to create a binary mask that encapsulates this polygon:
mask = createMask(h);
I get this mask:
imshow(mask);
You can then use this mask to index into your data and set the right regions to 0. First make a copy of the original data then set the data accordingly.
im_zero = im;
im_zero(mask) = 0;
I now get this:
imshow(im_zero);
Note that this only applies to single channel (2D) data. If you want to apply this to multi-channel (3D) data, then perhaps a multiplication channel-wise with the opposite of the mask may be prudent.
Something like this:
im_zero = bsxfun(#times, im, cast(~mask, class(im)));
The above code takes the opposite of the polygon mask, converts it into the same class as the original input im, then performs an element-wise multiplication of this mask with each channel of the input separately. The result will zero each spatial location that's defined in the mask over all channels.

Unable to use multiplication with grayscale image matrix

I am quite new to matlab/octave. I loaded an image using imread() function of octave. I tried to perform multiplication operation on the matrix but get the following error:
binary operator `*' not implemented for `uint8 matrix' by `matrix' operations
Is there another way to input the image??
I=imread('...');
I=rgb2gray(I);
I=double(I);
% you can perform the multiplication operation now
This usually means that you are trying to multiply arrays of different data types. The easiest thing to do here is to convert the uint8 image into double. You can either use the double() function, which will just cast the values, or us im2double(), which will also normalize the values to be between 0 and 1.
If you're trying to multiple two images (I'm guessing that's what you're trying to do since the error is for multiplying matrices and not a matrix by a scalar), you should use the immultiply function which handles different classes for you.
Simply, use immultiply (imgA, imgB) and never again worry about what class are imgA and imgB. Note that you'll need the image package installed in loaded.

How to find the centroid of different sections of an image?

I have an image that I want to divide in three parts and find the centroid of the parts separately and display them on original image, I used blkproc for dividing the image in [1 3] grids, but can't display the centroids. Here is the code I wrote,
i=imread('F:\line3.jpg');
i2=rgb2gray(i);
bw=im2bw(i2);
imshow(bw)
fun=#(x) regionprops(x,'centroid');
b=blkproc(bw,[1 3],fun);
But I can't get to display the centroids, as well as get their values. Any help will be much appreciated.
You can just use the plot command to plot over the top of the image.
Whatever you [X,Y] centroid coordinates are, say cx(1:3) and cy(1:3)
numCentroids is the number of centroids you are plotting.
hold on;
for ii = 1:length(numCentroids)
plot(cx(ii),cy(ii),'Marker','s','MarkerSize',10,'MarkerFaceColor','r','MarkerEdgeColor','k')
end
If you wanted to write more elegant code, you could run the plot command once across all your centroids and then make the line style type invisible. The answer I supplied should work though.
Here's an example image with made up centroids.
Strong recommendation - use blockproc instead of blkproc. It is better designed and easier to use.
Now, first of all, the second input to blockproc is the blocksize and not the grid size. So if you want to divide your image into [1 3] grid, which I understand as a single row of three blocks, then you should set your blocksize as:
blocksize = [size(i,1) ceil(size(i,2)/3)];
The second thing is to turn off the 'TrimBorder' parameter in blockproc. The code would look something like:
fun=#(x) regionprops(x,'centroid');
blocksize = [size(i,1) ceil(size(i,2)/3)];
b=blockproc(bw,blocksize,fun,'TrimBorder',false);
One minor thing - I would recommend not using the variable name 'i'. By default it represents the imaginary number i = sqrt(-1); in Matlab.

Resources