Matlab: Coding with arrays and writing data to excel sheet - image

I have obtained blood vessels of an eye in an image variable ves. I found the number of connected components(8-connectivity) as blobs. For each blob I need to calculate the Area, Major axis length and Centroid and store these values in a matrix testfv (each row corresponding to each property).For a single blob, Area returns a 1x1 struct, Centroid returns a 1x2 struct, and MajorAxisLength returns a 1x1 struct. So ,I guess depending on the number of blobs the number of cells required to store the values of Areas, Centroids and MajorAxisLength's vary, so using just one testfv to store these values as I have done would be wrong.
Is it possible? This is the code I tried(i assumed that testfv has 25 columns which allows me to store upto 8 blobs info)
[labeledImage numberOfBlobs] = bwlabel(ves, 8);
col=numberOfBlobs*2;
testfv = zeros(3,col);
for i=1:col
blobMeasurements = regionprops(labeledImage, 'Area');
testfv(1,col) = [blobMeasurements.Area];
blobMeasurements = regionprops(labeledImage, 'MajorAxisLength');
testfv(2,col)= [blobMeasurements.MajorAxisLength];
blobMeasurements = regionprops(labeledImage, 'Centroid');
testfv(3,col) = [blobMeasurements.Centroid];
end
I am getting the following error....
??? Subscripted assignment dimension mismatch.
Error in ==> alpha1 at 191 <br/>
testfv(1,col) = [blobMeasurements.Area];
Also, I need to write the data of the testfv matrix to an excel sheet file. How do I that ?
Would really appreciate the help as I am new to Matlab.

Related

how do I make face recognition with blob oracle

I have a row that contains the names and photos of people in Oracle, how do I make face recognition that can recognize names only by taking pictures from the camera ??
what techniques can I use?
Firstly, do not store the raw images in the blob column. You should store the vector representation of raw images. The following python code block will find the vector representation of a face image.
#!pip install deepface
from deepface.basemodels import VGGFace, Facenet
model = VGGFace.loadModel() #you can use google facenet instead of vgg
target_size = model.layers[0].input_shape
#preprocess detects facial area and aligns it
img = functions.preprocess_face(img="img.jpg", target_size=target_size)
representation = model.predict(img)[0,:]
Here, you can either pass exact image path like img.jpg or the 3D array to img argument of preprocess_face. In this way, you will store the vector representations in the blob column of oracle database.
When you have a new face image, and want to find its identity in the database find its representation again.
#preprocess detects facial area and aligns it
target_img = functions.preprocess_face(img="target.jpg", target_size=target_size)
target_representation = model.predict(target_img )[0,:]
Now, you have the vector representation of the target image and vector representations of the database images. You need to find the similarity score of target image representation and each instance of database representations.
Euclidean distance is the easiest way to compare vectors.
def findEuclideanDistance(source_representation, test_representation):
euclidean_distance = source_representation - test_representation
euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
euclidean_distance = np.sqrt(euclidean_distance)
return euclidean_distance
We will compare each data base instance to target. Suppose that representations of data base instances are stored in representations object.
distances = []
for i in range(0, len(representations)):
source_representation = representations[i]
#find the distance between target_representation and source_representation
distance = findEuclideanDistance(source_representation, target_representation )
distances.append(distance)
Distances list stores the distance of each item in the data base to target. We need to find the lowest distance.
import numpy as np
idx = np.argmax(distances)
Idx is the id of the target image in the database.

What is the syntax of ImageResize()

I have data that change in size and want to display them in the same window. The command
void ImageResize( BasicImage im, Number num_dim, Number... )
seems like a potential fit, but the syntax is not clear at all.
Let's say I have 512x5 data set and now it needs to be 367x5.
The , Number...) indicates that this command takes a different number of parameters, all of them interpreted as number parameters. Commands which do this, usually use one of their other parameters to specify how many such parameters follow.
A typical example for this is also the SliceN command.
In this particular case, the command not only allows you to change the size of the dimensions in the image, but also the number of dimensions. It is a very useful command to f.e. change a 2D image into a 3D stack or the like.
The command ImageResize( BasicImage im, Number num_dim, Number... ) does several things:
It replaces im in-place, so the meta-data, display and window remains the same
It adjusts the dimension calibration when the dimension size is changed. Here, the assumption is, that the field-of-view before and
after the resize is the same. (The command can be used to easily scale
images as shown in the example below.)
All values of the image im are set to zero. ( If you need to keep the values, you need to act on an image clone!)
Example 1: Resizing image with bilinar interpolation
image before := GetFrontImage()
number sx, sy
before.GetSize(sx,sy)
number factor = 1.3
image after := before.ImageClone()
after.ImageResize( 2, factor*sx, factor*sy ) // Adjusts the empty container with meta-data
after = warp(before, icol/factor, irow/factor ) // interpolate data
after.ShowImage()
Example 2: Extend 2D image into 3D stack
number sx = 100
number sy = 100
image img := RealImage("2D",4,sx,sy)
img = iradius* Random()
img.ShowImage()
OKDialog("Now into a stack...")
number sz = 10
img.ImageResize(3,sx,sy,sz) // All values are zero now!
img = iradius * Random()

Coordinates and Field values

Consider I have load a dataset as follows:
ds = yt.load('pltxxx')
The dataset includes the following fields
density, mag_vort, tracer, x_velocity, y_velocity
One can simply plot the mag_vort which is the magnitude of vorticity in 2D domain in this case, by means of:
slc = yt.SlicePlot(ds, 'z', 'mag_vort')
If I want to export the x-cooridnates, y-coordinates and vorticity_magnitude in the txt file (or numpy array) or plot it via matplotlib scatter plot
plt.scatter(x_coor, y_coor, c=mag_vort)
Is there an easy way to extract those information from dataset?
You can use a data object (in this case we use the all_data data object) to access the field values for the 'x', 'y', and 'mag_vort' fields:
ad = ds.all_data()
x = ad['x']
y = ad['y']
mag_vort = ad['mag_vort']
The arrays you get back from accessing a data object are YTArray instances. YTArray is a subclass of numpy's ndarray that has units attached.
Before you pass these arrays to matplotlib, convert them to whichever units you want to do the plot in, then cast them to numpy arrays:
x_plot = np.array(x.to('km'))
y_plot = np.array(y.to('km'))
plt.scatter(x_plot, y_plot, c=np.array(mag_vort))

How save bidimensional list to image in python?

I have a big bidimensional list of integer value. Each value represent a pixel and needs to match a color but obviously similar value needs to have similar color. Here an example of my list:
list=[[0,10,3,9,23,0], [7,0,0,0,0,10], [12,1,2,7,11,12], [0,0,0,34,1,9]]
"list" is a rectangle of 4 rows and each row have 6 columns. 0 value needs to match to no color, in other word 0 value is trasparent color. I try to use PIL but I didn't obtain the right result. Here the test code:
from PIL import Image
list=[[0,10,3,9,23,0], [7,0,0,0,0,10], [12,1,2,7,11,12], [0,0,0,34,1,9]]
new=Image.new("P", (4,6))
new.putdata(list)
new.save('test.tif')
The cause for the failure is during new.putdata(list), which expects a sequence object (I guess a 2D array doesn't count as a sequence object).
The fix is to convert your 2D array into a 1D array. One example of how to do this is:
sequence = [list[x][y] for x in range(len(list)) for y in range(len(list[0]))]
So the following code should work properly:
from PIL import Image
list=[[0,10,3,9,23,0], [7,0,0,0,0,10], [12,1,2,7,11,12], [0,0,0,34,1,9]]
new=Image.new("P", (6,4))
sequence = [list[x][y] for x in range(len(list)) for y in range(len(list[0]))]
new.putdata(sequence)
new.save('test.tif')

Finding area of the image

I used connected component labeling algorithm (bwconncomp) to label the different parts of a binary image (MATLAB). Now i need to calculate the area of different labels and remove the labels with smaller area. Can i use the default area finding command or is there any specific commands for that in matlab...Help..
From the documentation:
CC = bwconncomp(BW) returns the connected components CC found in BW.
The binary image BW can have any dimension. CC is a structure with
four fields...
The final field in CC is PixelIdxList, which is:
[a] 1-by-NumObjects cell array where the kth element in the cell array is
a vector containing the linear indices of the pixels in the kth object.
You can find the area of each label by looking at the length of the corresponding entry in the cell array. Something like:
areas_in_pixels = cellfun(#length, CC.PixelIdxList);
The PixelIdxList is a cell array, each member of which contains the linear indexes of the pixels present in that connected component. The line of code above finds the length of each cell in the cell array - i.e. the number of pixels in each connected component.
I've used cellfun to keep the code short and efficient. A different way of writing the same thing would be something like:
areas_in_pixels = nan(1, length(CC.PixelIdxList);
for i = 1:length(CC.PixelIdxList)
areas_in_pixels(i) = length(CC.PixelIdxList{i});
end
For each connected component, you can then find the size of that component in pixels by accessing an element in areas_in_pixels:
areas_in_pixels(34) %# area of connected component number 34
If you don't want to write lots of code like above just use built-in functions of MATLAB to detect the area. Label your components and from the properties of the component you can find out the area of that component. Suppose Bw is the binary image:
[B,L] = bwboundaries(Bw,'noholes');
stats = regionprops(L,'Area','perimeter');
for k = 1:length(B)
area(k)=stats.Area;
end
You can make this better still by avoiding the for loop with the following:
[B,L] = bwboundaries(Bw,'noholes');
stats = regionprops(L,'Area','perimeter');
area = [stats.Area];
Best,
-Will

Resources