Showing posts with label matlab. Show all posts
Showing posts with label matlab. Show all posts
Saturday, 27 July 2013
Taking the Grunt out of Geotags
Here's a matlab script to automatically compile all geo-tagged images from a directory and all its subdirectories into a Google Earth kml file showing positions and thumbnails
Like most of my matlab scripts, it's essentially just a wrapper for a system command. It requires exiftool for the thumbnail creation (available on both *nix and for Windows). It also needs the (free) Google Earth toolbox for Matlab.
Right now it's just set up for JPG/jpg files, but could easily be modified or extended. As well as the kml file (Google Earth will launch as soon as the script is finished) it will save a matlab format file contining the lats, longs, times and filenames.
Outputs look a little like this (a selection of over 30,000 photos taken in Grand Canyon)
Wednesday, 24 July 2013
Destination point given distance and bearing from start point
You have starting points:
xcoordinate, a list of x-coordinates (longitudes)
ycoordinate, a list of y-coordinates (latitudes)
num_samples, the number of samples in the plane towards the destination point
bearings:
heading, a list of headings (degrees)and distances:
range, a list of distances in two directions (metres)
This is how you find the coordinates (x, y) along the plane defining a starting point and two end points, in MATLAB.
Tuesday, 27 November 2012
em1 to ethX on Fedora 17 (how to install matlab if you don't have eth)
I have just moved from Ubuntu 12.04 to Fedora 17. No reason other than necessity for my new job. I'm still happy with Ubuntu and even don't mind Unity!
First thing I wanted to do, of course, was install matlab. It turns out I had a bit of work to do to get it installed on my Dell Precision machine! So here's a post to help out anyone who has the same problem.
If you don't have some eth listed when you ifconfig (I had the NIC listed as em1), matlab will install but you can't activate it. The problem is described on their website
Basically, Fedora udev names NICs (network cards) embedded on the motherboard as em1, em2 (etc) rather then eth0, eth1 (etc). More details here
The two solutions listed on the Mathworks for changing the names back to eth do not work in my Fedora install. The reason why the first one doesn't work is because there is no /etc/iftab file. the reason why the second one works is because udev rules are not listed in etc (they are in lib instead and have different names and structures)
Thankfully, Fedora has built in a mechanism to modify the names of NICs post install. You do it by editing the following file
/lib/udev/rules.d/71-biosdevname.rules
so the line which reads
GOTO="netdevicename_end"
commented by default, is uncommented
/etc/default/grub
by adding the following line to the bottom:
biosdevname=0
Then I backed up my ifcfg em1 network script by issuing
cp /etc/sysconfig/network-scripts/ifcfg-em1 /etc/sysconfig/network-scripts/ifcfg-em1.old
then I renamed it eth0 (the number can be anything, I believe, between 0 and 9, and matlab will figure it out when it activates):
mv /etc/sysconfig/network-scripts/ifcfg-em1 /etc/sysconfig/network-scripts/ifcfg-eth0
and edited ifcfg-eth0 so the line which read
DEVICE="em1"
to read:
DEVICE="eth0"
This is all the information the machine needs, when it boots up, to change the naming convention from em1 back over to eth0.
Upon reboot, ifconfig shows eth0 where em1 was before (dmesg | grep eth would also show the change), and matlab installs perfectly.
A satisfyingly geeky end to a Tuesday!
Labels:
Dell,
fedora,
linux,
matlab,
network card names
Saturday, 29 September 2012
Downloading Photobucket albums with Matlab and wget
Here's a script to take the pain out of downloading an album of photos from photobucket.
It uses matlab to search a particular url for photo links (actually it looks for the thumbnail links and modifies the string to give you the full res photo link), then uses a system command call to wget to download the photos All in 8 lines of code!
Ok to start you need the full url for your album. The '?start=all' bit at the end is important because this will show you all the thumbnails on a single page. Then simply use regexp to find the instances of thumbnail urls. Then loop through each link, strip the unimportant bits out, remove the 'th_' from the string which indicates the thumbnail version of the photo you want, and call wget to download the photo. Easy-peasy!
It uses matlab to search a particular url for photo links (actually it looks for the thumbnail links and modifies the string to give you the full res photo link), then uses a system command call to wget to download the photos All in 8 lines of code!
Ok to start you need the full url for your album. The '?start=all' bit at the end is important because this will show you all the thumbnails on a single page. Then simply use regexp to find the instances of thumbnail urls. Then loop through each link, strip the unimportant bits out, remove the 'th_' from the string which indicates the thumbnail version of the photo you want, and call wget to download the photo. Easy-peasy!
Saturday, 15 September 2012
Alternative to bwconvhull
Matlab's bwconvhull is a fantastic new addition to the image processing library. It is a function which, in its full capacity, will return either the convex hull of the entire suite of objects in a binary image, or alternatively the convex hull of each individual object.
I use it, in the latter capacity, for filling multiple large holes (holes large enough that imfill has no effect) in binary images containing segmented objects
For those who do not have a newer Matlab version with bwconvhull included, I have written this short function designed to be an alternative to the usage
and here it is:
It uses the IP toolbox function regionprops, around for some time, to find the convex hull images of objects present, then inscribes them onto the output image using the bounding box coordinates. Simples!
For those who do not have a newer Matlab version with bwconvhull included, I have written this short function designed to be an alternative to the usage
P= bwconvhull(BW,'objects');
and here it is:
It uses the IP toolbox function regionprops, around for some time, to find the convex hull images of objects present, then inscribes them onto the output image using the bounding box coordinates. Simples!
Sunday, 9 September 2012
Craigslist Part 2: using matlab to plot your search results in Google Maps
In 'Craigslist Part 1' I demonstrated a way to use matlab to automatically search craigslist for properties with certain attributes. In this post I show how to use matlab and python to create a kml file for plotting the results in Google Earth.
Download the matlab googleearth toolbox from here
Add google earth toolbox to path. Import search results data and get map links (location strings). Loop through each map location and string the address from the url, then geocode to obtain coordinates.
The function 'geocode' writes and executes a python script to geocode the addresses (turn the address strings into longitude and latitude coordinates). The python module may be downloaded here
Once we have the coordinates, we then need to get rid of nans and outliers (badly converted coordinates due to unreadable address strings). Use the google earth toolbox to build the kml file. Finally, run google earth and open the kml file using a system command:
The above is a simple scatter plot which only shows the location of the properties and not any information about them. Next shows a more complicated example where the points are plotted with labels (the asking price) and text details (the google map links) in pop-up boxes
First each coordinate pair is packaged with the map and name tags. Concatenate the strings for each coordinate and make a kml file. Finally, run google earth and open the kml file using a system command:


Labels:
craigslist,
google earth,
internet,
matlab,
python
Friday, 7 September 2012
Craigslist Part 1: Using matlab to search according to your criteria and retrieve posting urls
I have a certain fondness for using matlab for obtaining data from websites. It simply involves understanding the way in which urls are constructed and a healthy does of regexp. In this example, I've written a matlab script to search craiglist for rental properties in Flagstaff with the following criteria:
1) 2 bedrooms
2) has pictures
3) within the price range 500 to 1250 dollars a month
4) allows pets
5) are not part of a 'community' housing development.
This script will get their urls, prices, and google maps links, and write the results to a csv file.
First, get the url and find indices of the hyperlinks only, then get only the indices of urls which are properties. Then get only the indices of urls which have a price in the advert description; find the prices; strip the advert urls from the string; sort the prices lowest to highest; and get rid of urls which mention a community housing development.
Finally, get the links to google maps in the adverts if there are some, and write the filtered urls, maps, and prices to csv file.
Save and execute in matlab, or perhaps add this line to your crontab for a daily update!
/usr/local/MATLAB/R2011b/bin/matlab -nodesktop -nosplash -r "craigslist_search;quit;"
Wednesday, 22 August 2012
Write and execute a Matlab script without opening Matlab
Here's an example of using cat to write your m-file and then execute from the command line. This particular example will just plot and print 10 random numbers.
Saturday, 10 September 2011
Ellipse Fitting to 2D points, part 3: Matlab
The last of 3 posts presenting algorithms for the ellipsoid method of Khachiyan for 2D point clouds. This version in Matlab will return: 1) the ellipse radius in x, 2) the ellipse radius in y, 3) the centre in x, 4) the centre in y, and 5) orientation of the ellipse, and coordinates of the ellipse
Non-linear least squares fit forced through a point
Sometimes you want a least-squares polynomial fit to data but to constrain it so it passes through a certain point. Well ...
Inputs: x, y (data); x0 and y0 are the coordinates of the point you want it to pass through, and n is the degree of polynomial
Matlab function to generate a homogeneous 3-D Poisson spatial distribution
This is based on Computational Statistics Toolbox by W. L. and A. R. Martinez, which has a similar algorithm in 2D. It uses John d'Errico's inhull function
Inputs: N = number of data points which you want to be uniformly distributed over XP, YP, ZP which represent the vertices of the region in 3 dimensions
Outputs: x,y,z are the coordinates of generated points
3D spectral noise in Matlab with specified autocorrelation
Here is a function to generate a 3D matrix of 1/frequency noise
Inputs are 1)rows, 2) cols (self explanatory I hope), 3) dep (the 3rd dimension - number of images in the stack) and 4) factor, which is the degree of autocorrelation in the result. The larger this value, the more autocorrelation an the bigger the 'blobs' in 3D
Enjoy!
Computational geometry with Matlab and MPT
For computational geometry problems there is a rather splendid tool called the Multi Parametric Toolbox for Matlab
Here are a few examples of using this toolbox for a variety of purposes using 3D convex polyhedra represented as polytope arrays. In the following examples, P is always a domain bounded 3D polytope array
Sunday, 27 March 2011
Wrapping and interfacing compiled code into more flexible and user-friendly programs using Zenity and Bash
Subtitles include:
1. How to reconstruct the three-dimensional shape of an object in a scene in a very inexpensive way using shadow-casting
2. How to write and execute a matlab script from a bash script
I've written a bash script - shadowscan.sh - which is a wrapper for a set of programs for the reconstruction 3D surface of an object in a series of photographs using the ingenious shadow-casting algorithm of Jean-Yves Bouguet and Pietro Perona
The script relies heavily on the GUI-style interfacing tools of Zenity and acts as an interface and wrapper for the algorithm as implemented by these guys. It will also write and execute a matlab script for visualising the outputs.
This script should live in a directory with the following compiled programs, all available here:
1. ccalib (performs the camera calibration to retrieve the intrinsic parameters of camera and desk)
2. find_light (performs the light calibration to find light-source coordinates)
3. desk_scan (does the 3d reconstruction)
4. merge (merges 2 3d reconstructions, e.g. from different angles)
and the following matlab script:
1. selectdata.m (available here)
When the makefile is run, it creates the compiled programs in the ./bin directory. It's important to consult the README in the main folder as well as within the 'desk_scan' folder to have a clear idea of what the program does and what the input parameters mean.
My program will check if the camera calibration and light calibration files exist in the folder and if not will carry them out accordingly then several reconstructions are carried out, and the outputs merged. Finally matlab is called from the command line to run 'p_lightscan_data.m' to visualize the results.
when the script finishes there will be the following output files:
1. xdim.txt - max dimension to scan to
2. params - camera calibration parameters
3. data - camera calibration data
4. light.txt - light calibration parameters
5. sample.pts - [x,y,z] of object, in coordinates relative to light source
6. sample_lightscan1.tif - filled colour contour plot of reconstructed object
7. sample_lightscan2.tif - mesh plot of reconstructed object
I've tried to keep it flexible. It will run only the elements it needs to. For example, if the camera or lighting has been carried out before for a different object it will pick up on that. Also, the program can be invoked by passing it two arguments (path to folder where sample images are, and what sequence of contrasts to use for the reconstruction), which avoids having to input with the graphical menus. Example usage:
1. bash shadowscan.sh
2. bash shadowscan.sh /home/daniel/Desktop/shadow_scanning/sample/bottle 30.35.40.45
1. How to reconstruct the three-dimensional shape of an object in a scene in a very inexpensive way using shadow-casting
2. How to write and execute a matlab script from a bash script
I've written a bash script - shadowscan.sh - which is a wrapper for a set of programs for the reconstruction 3D surface of an object in a series of photographs using the ingenious shadow-casting algorithm of Jean-Yves Bouguet and Pietro Perona
The script relies heavily on the GUI-style interfacing tools of Zenity and acts as an interface and wrapper for the algorithm as implemented by these guys. It will also write and execute a matlab script for visualising the outputs.
This script should live in a directory with the following compiled programs, all available here:
1. ccalib (performs the camera calibration to retrieve the intrinsic parameters of camera and desk)
2. find_light (performs the light calibration to find light-source coordinates)
3. desk_scan (does the 3d reconstruction)
4. merge (merges 2 3d reconstructions, e.g. from different angles)
and the following matlab script:
1. selectdata.m (available here)
When the makefile is run, it creates the compiled programs in the ./bin directory. It's important to consult the README in the main folder as well as within the 'desk_scan' folder to have a clear idea of what the program does and what the input parameters mean.
My program will check if the camera calibration and light calibration files exist in the folder and if not will carry them out accordingly then several reconstructions are carried out, and the outputs merged. Finally matlab is called from the command line to run 'p_lightscan_data.m' to visualize the results.
when the script finishes there will be the following output files:
1. xdim.txt - max dimension to scan to
2. params - camera calibration parameters
3. data - camera calibration data
4. light.txt - light calibration parameters
5. sample.pts - [x,y,z] of object, in coordinates relative to light source
6. sample_lightscan1.tif - filled colour contour plot of reconstructed object
7. sample_lightscan2.tif - mesh plot of reconstructed object
I've tried to keep it flexible. It will run only the elements it needs to. For example, if the camera or lighting has been carried out before for a different object it will pick up on that. Also, the program can be invoked by passing it two arguments (path to folder where sample images are, and what sequence of contrasts to use for the reconstruction), which avoids having to input with the graphical menus. Example usage:
1. bash shadowscan.sh
2. bash shadowscan.sh /home/daniel/Desktop/shadow_scanning/sample/bottle 30.35.40.45
Sunday, 6 June 2010
Granular Therapy
Here's a relaxing movie I just made of spinning modelled sand grains:
I'm not going to divulge the details of the model of how to create the sand grains (a current research project of mine). I can tell you I used these rather excellent functions for MATLAB:
Volume interpolation Crust algorithm, described more here
A toolbox for Multi-Parametric Optimisation
I used 'recordmydesktop' to capture the grains in my MATLAB figure window. It created an OGV format video (which I renamed to 'beautiful_grains.ogv'). I then used the following code to decode the video into jpegs
I needed to crop the pictures to just the grains, then turn the cropped pictures back into a video. I used this:
et voila! Now sit back with a cuppa and relax to those spinning grains.
I'm not going to divulge the details of the model of how to create the sand grains (a current research project of mine). I can tell you I used these rather excellent functions for MATLAB:
Volume interpolation Crust algorithm, described more here
A toolbox for Multi-Parametric Optimisation
I used 'recordmydesktop' to capture the grains in my MATLAB figure window. It created an OGV format video (which I renamed to 'beautiful_grains.ogv'). I then used the following code to decode the video into jpegs
mkdir out_pics
mplayer -ao null -ss 00:00:03 -endpos 50 beautiful_grains.ogv -vo jpeg:outdir=out_pics
I needed to crop the pictures to just the grains, then turn the cropped pictures back into a video. I used this:
cd out_pics
for image in *.jpg
do
# crop the image
convert $image -crop 600x600+350+135 grains%05d.tiff
done
# make movie from the cropped tiffs
ffmpeg -r 25 -i grains%05d.tiff -y -an spinning_grains_small.avi
et voila! Now sit back with a cuppa and relax to those spinning grains.
Friday, 5 June 2009
Flower Bed
Recently I investigated Apollonian gaskets (a type of space-filling fractal composed of ever-repeating circles) for use as 'pore-space fillers' in a model I am creating for synthetic sediment beds. I came across a most excellent script here:
http://www.mathworks.com/matlabcentral/fileexchange/15987
In my Friday afternoon boredom, I have just modified some aspects of the program to create a function which simulates a pretty flower bed
Some example outputs below - enjoy! Right, now back to work ...


Thursday, 16 April 2009
Frequency Transforms on Images
As part of my work, I have to do a lot of spectral analysis with images. Traditionally I have used MATLAB to do this - it is exceptionally easy and powerful, and works just fine. As a simple example, if I want a power-spectrum of an image, treated as a 2D matrix of 8-bit numbers, the sequence of commands is this:
Seven lines of commands. Couldn't be simpler. That's the beauty of MATLAB. The snag is that it costs several hundreds to thousands of dollars for the program, which makes it difficult to share your code with other people. So recently I've thought about coding up some things I want to share with other people in Python.
Python is a cross-platform, open-source programming language and environment. It is not too dissimilar to MATLAB in many respects, especially when you install the right libraries. In order to do the same in Python as above, as easy as possible, I needed to install Python Imaging Library (PIL), NumPy and SciPy. Then the sequence of operations is as follows:
Same answer. Not bad - not harder, just different. And completely free. Oh, and this'll work on UNIX, Linux, Mac, and PC when Python is installed (with a couple of extra libraries). Great!
%------------------- MATLAB
% read image in, convert to greyscale and double-precision
image=double(rgb2gray(imread('myimage.jpg')));
% crop to smallest dimension
[m,n]=size(im);
im=im(1:min(m,n),1:min(m,n));
% find image mean
imMean=mean(im(:));
% and subtract mean from the image
demean=im-imMean;
% find the 2D fourier transform
ft=fft2(demean);
% power spectrum is the element-by-element square of the fourier transform
spectrum=abs(ft).^2;
Seven lines of commands. Couldn't be simpler. That's the beauty of MATLAB. The snag is that it costs several hundreds to thousands of dollars for the program, which makes it difficult to share your code with other people. So recently I've thought about coding up some things I want to share with other people in Python.
Python is a cross-platform, open-source programming language and environment. It is not too dissimilar to MATLAB in many respects, especially when you install the right libraries. In order to do the same in Python as above, as easy as possible, I needed to install Python Imaging Library (PIL), NumPy and SciPy. Then the sequence of operations is as follows:
# ----------------PYTHON
#-----------------------
# declare libraries to use
import Image
import scipy.fftpack
from pylab import*
import cmath
from numpy import*
# load image, convert to greyscale
im=Image.open('myimage.jpg').convert("L")
# crop to smallest dimension
box=(0,0,im.ny,im.nx)
region=im.crop(box)
# find mean
imMean=mean(asarray(region))
# 2D fourier transform of demeaned image
ft=fft2(region-imMean)
# power spectrum
spectrum=pow(abs(ft),2)
Same answer. Not bad - not harder, just different. And completely free. Oh, and this'll work on UNIX, Linux, Mac, and PC when Python is installed (with a couple of extra libraries). Great!
Hmm, I thought, I wonder if it is possible to do the same in a piece of non-numerical software. I tried ImageMagick because its free and ubiquitous on Linux and Mac, and also available for PC, and it has a massive user-community. It is incredibly powerful as a command-line graphics package - even more powerful than PhotoShop and Illustrator, and like all UNIX-based applications, infinitely flexible. It turns out it is a little more tricky to calculate the power spectrum in ImageMagick, but here's how.
First, you need the right tools - ImageMagick is usually already present on most Linux distributions - if not, if a debian/Ubuntu user use sudo apt-get install imagemagick, or download from the webiste hyperlinked above. Then you'll need an open-source C-program for calculation of FFTs: this is provided by FTW - download fftw-3.2.1.tar.gz, untar, cd to that directory, then install the binary by issuing the usual commands:
This C-program is no good on its own, so the last ingredient is a wrapper for ImageMagick. Fortunately - nay, crucially, this has been provided by Sean Burke and Fred Weinhaus - introducing IMFFT! The program can be downloaded and installed from here. And here is an in-depth tutorial of how to use it (I'm only just getting to grips with it myself). For some reason the compiled program is called 'demo'. I move it to my /bin directory so my computer can see it wherever I am working, and in the process change the name to something more suitable - fft:
Right, it's a little bit more involved, but here is the bash shell script for the power spectrum in ImageMagick:
Voila! The spectrum is the image 'ggc_dm_F_Q16_spec.tiff'. I haven't yet worked out how to keep all the data inside the program, to eliminate the need (and cumulative errors associated with) writing the outputs at every stage to file, and eading them back in again. This means I can't use the spectrum for any scientific application. But in theory it should be possible. Any suggestions welcome!
./configure
sudo make && make install
This C-program is no good on its own, so the last ingredient is a wrapper for ImageMagick. Fortunately - nay, crucially, this has been provided by Sean Burke and Fred Weinhaus - introducing IMFFT! The program can be downloaded and installed from here. And here is an in-depth tutorial of how to use it (I'm only just getting to grips with it myself). For some reason the compiled program is called 'demo'. I move it to my /bin directory so my computer can see it wherever I am working, and in the process change the name to something more suitable - fft:
cp demo ./fft && sudo mv ./fft /bin
Right, it's a little bit more involved, but here is the bash shell script for the power spectrum in ImageMagick:
#----------------------------- IMAGEMAGICK
#-------------------------------------------------
#!/bin/bash
# read image and convert to greyscale
convert myimage.tif -colorspace gray input_grey.tiff
# find min dimension for cropping
min=`convert input_grey.tiff -format "%[fx: min(w,h)]" info:`
# crop image
convert input_grey.tiff -background white -gravity center -extent ${min}x${min} input_grey_crop.tiff
# de-mean image
# get data
data=`convert input_grey_crop.tiff -verbose info:`
# find mean as proportion
mean=`echo "$data" | sed -n '/^.*[Mm]ean:.*[(]\([0-9.]*\).*$/{ s//\1/; p; q; }'`
# convert mean to percent
m=`echo "scale=1; $mean *100 / 1" | bc`
# de-mean image
convert input_grey_crop.tiff -evaluate subtract ${m}% ggc_dm.tiff
# pad to power of 2
p2=`convert ggc_dm.tiff -format "%[fx:2^(ceil(log(max(w,h))/log(2)))]" info:`
convert ggc_dm.tiff -background white -gravity center -extent ${p2}x${p2} ggc_dm_pad.tiff
# forward fast fourier transform
fft f ggc_dm_pad.tiff
# creates ggc_dm_F_Q16.tiff, on which get spectrum
convert ggc_dm_F_Q16.tiff -contrast-stretch 0% -gamma .5 -fill "rgb(1,1,1)" -opaque black ggc_dm_F_Q16_spec.tiff
Voila! The spectrum is the image 'ggc_dm_F_Q16_spec.tiff'. I haven't yet worked out how to keep all the data inside the program, to eliminate the need (and cumulative errors associated with) writing the outputs at every stage to file, and eading them back in again. This means I can't use the spectrum for any scientific application. But in theory it should be possible. Any suggestions welcome!
Friday, 16 January 2009
How to read and search your blog page with the imaginative use of the 'regexp' in matlab
Just a quickie - there may be some application for this (?)
You start with your blog url:
>> url='http://thezestyblogfarmer.blogspot.com/';
read it in, then you can start searching through its contents:
>> text=urlread(url);
for example, I can list all the unix commands I have mentioned - its easy because they all start with a dollar sign
>> text_linux=regexp(text,'>\$[^<\r\n]*<','match')' which gives me the output:
'>$ sudo apt-get update<' '>$ sudo apt-get upgrade<' '>$ sudo apt-get clean<' '>$ sudo apt-get autoclean<' '>$ sudo apt-get -f install<' '>$ sudo badblocks -v /dev/sda1<' '>$ sudo aptitude install debsums<' '>$ debsums <' '>$ sudo apt-get install firestarter<' '>$ sudo apt-get install youtube-dl<' '>$ youtube-dl http://uk.youtube.com/watch?v=r9OjoPskf_c<' '>$ ffmpeg -i r9OjoPskf_c.flv people_everyday.avi<' [1x97 char] '>$ sudo su | sudo apt-get install skype<' '>$ sudo jhas -jh 837afm$^&qeiuhn>>KOUUIG4n we8f-&hcjku8hujbn ok?<' '>$ sudo su | python setup.py install<' [1x75 char] '>$ sudo dpkg -i skysentials_1.0.1-1_all.deb<' '>$ konsole<' or maybe the matlab commands which all start with 2 > signs:
>> text_matlab=regexp(text,'>\>>[^<\r\n]*<','match')'
'>>> cf=0; %current frame<' '>> for k=10:50 % identity matrix from [10,10] to [50,50]<' '>> clf;<' '>> plot(fft(eye(k))) %plot<' '>> axis equal; axis off; axis([-1 1 -1 1]); % sort out axes<' '>> pause(0.01) %take a break<' '>> cf=cf+1; %update current frame<' [1x87 char] '>> end<' [1x94 char] '>>KOUUIG4n we8f-&hcjku8hujbn ok?<' '>>> convert my_image.jpg -resize 200% my_new_image.jpg<' '>>> direc=dir([pwd,filesep,'*.','jpeg']);<' '>>> filenames={};<' '>>> [filenames{1:length(direc),1}] = deal(direc.name);<' '>>> filenames=sortrows(char(filenames{:}));<' '>>> mkdir([pwd,filesep,'james_and_the_giant_peach'])<' '>>> mkdir([pwd,filesep,'thumblina'])<' '>>> for i=1:size(filenames,1)<' '>>> system(['convert ',deblank(filenames(i,:))...<' '>>> system(['convert ',deblank(filenames(i,:))...<' '>>> end<' '>>> url='http://www.mathworks.com/moler/ncm.tar.gz';<' '>>> gunzip(url,'ncm')<' '>>> untar('ncm/ncm.tar','ncm')<' '>>> cd([pwd,filesep,'ncm'])<' '>>> [U,G]=surfer('http://www.thedailydanielblog.blogspot.com',200);<' '>>> fid=fopen('dansweb.txt','wt');<' '>>> for i=1:size(char(U),1), fprintf(fid,'%s\n',char(U(i,:))); end<' '>>> fclose(fid)<' '>>> pagerank(U,G)<' and finally how to list the websites you refer to - I can't post the code into my blog because it involves html code which blogger doesn't like - replace '>\>>' with '< [the first letter of the alphabet] href'
enjoy!
You start with your blog url:
>> url='http://thezestyblogfarmer.blogspot.com/';
read it in, then you can start searching through its contents:
>> text=urlread(url);
for example, I can list all the unix commands I have mentioned - its easy because they all start with a dollar sign
>> text_linux=regexp(text,'>\$[^<\r\n]*<','match')' which gives me the output:
'>$ sudo apt-get update<' '>$ sudo apt-get upgrade<' '>$ sudo apt-get clean<' '>$ sudo apt-get autoclean<' '>$ sudo apt-get -f install<' '>$ sudo badblocks -v /dev/sda1<' '>$ sudo aptitude install debsums<' '>$ debsums <' '>$ sudo apt-get install firestarter<' '>$ sudo apt-get install youtube-dl<' '>$ youtube-dl http://uk.youtube.com/watch?v=r9OjoPskf_c<' '>$ ffmpeg -i r9OjoPskf_c.flv people_everyday.avi<' [1x97 char] '>$ sudo su | sudo apt-get install skype<' '>$ sudo jhas -jh 837afm$^&qeiuhn>>KOUUIG4n we8f-&hcjku8hujbn ok?<' '>$ sudo su | python setup.py install<' [1x75 char] '>$ sudo dpkg -i skysentials_1.0.1-1_all.deb<' '>$ konsole<' or maybe the matlab commands which all start with 2 > signs:
>> text_matlab=regexp(text,'>\>>[^<\r\n]*<','match')'
'>>> cf=0; %current frame<' '>> for k=10:50 % identity matrix from [10,10] to [50,50]<' '>> clf;<' '>> plot(fft(eye(k))) %plot<' '>> axis equal; axis off; axis([-1 1 -1 1]); % sort out axes<' '>> pause(0.01) %take a break<' '>> cf=cf+1; %update current frame<' [1x87 char] '>> end<' [1x94 char] '>>KOUUIG4n we8f-&hcjku8hujbn ok?<' '>>> convert my_image.jpg -resize 200% my_new_image.jpg<' '>>> direc=dir([pwd,filesep,'*.','jpeg']);<' '>>> filenames={};<' '>>> [filenames{1:length(direc),1}] = deal(direc.name);<' '>>> filenames=sortrows(char(filenames{:}));<' '>>> mkdir([pwd,filesep,'james_and_the_giant_peach'])<' '>>> mkdir([pwd,filesep,'thumblina'])<' '>>> for i=1:size(filenames,1)<' '>>> system(['convert ',deblank(filenames(i,:))...<' '>>> system(['convert ',deblank(filenames(i,:))...<' '>>> end<' '>>> url='http://www.mathworks.com/moler/ncm.tar.gz';<' '>>> gunzip(url,'ncm')<' '>>> untar('ncm/ncm.tar','ncm')<' '>>> cd([pwd,filesep,'ncm'])<' '>>> [U,G]=surfer('http://www.thedailydanielblog.blogspot.com',200);<' '>>> fid=fopen('dansweb.txt','wt');<' '>>> for i=1:size(char(U),1), fprintf(fid,'%s\n',char(U(i,:))); end<' '>>> fclose(fid)<' '>>> pagerank(U,G)<' and finally how to list the websites you refer to - I can't post the code into my blog because it involves html code which blogger doesn't like - replace '>\>>' with '< [the first letter of the alphabet] href'
enjoy!
Sunday, 23 November 2008
Fourier transform of an identity matrix
... and how to get your matlab plots into animated gifs, and into your blog!
I noted the other day that the fast fourier transform of an identity matrix can look really cool when plotted, and that stringing matrices of increasing size along in an animation looked really cool.
So when it came to sharing it this morning I came across a little fault in blogger which means that you can't directly load animated .gif files into your blog posts. The solution is to upload your image onto the web, get the html for the link, and embed that into your blog post. I used Tinypic - uploaded the image, and embedded the html code here:

Here's the matlab code for the animation
>> cf=0; %current frame
>> for k=10:50 % identity matrix from [10,10] to [50,50]
>> clf;
>> plot(fft(eye(k))) %plot
>> axis equal; axis off; axis([-1 1 -1 1]); % sort out axes
>> pause(0.01) %take a break
>> cf=cf+1; %update current frame
>> saveas(gcf, sprintf('frame%d', 1000+cf), 'jpg') %save the current frame as a jpg
>> end
This next bit of code tells the operating system (the bang command, !) to use the unix program 'convert' to make an animated gif out of all of those frames (i've set it to compress and downsize by half to save on file space)
>> !convert -antialias -loop 1000 -delay 5 -geometry 50% -compress LZW frame10* ffteye.gif
Gif creation is my new favourite toy - watch out Daily Daniel!
I noted the other day that the fast fourier transform of an identity matrix can look really cool when plotted, and that stringing matrices of increasing size along in an animation looked really cool.
So when it came to sharing it this morning I came across a little fault in blogger which means that you can't directly load animated .gif files into your blog posts. The solution is to upload your image onto the web, get the html for the link, and embed that into your blog post. I used Tinypic - uploaded the image, and embedded the html code here:

Here's the matlab code for the animation
>> cf=0; %current frame
>> for k=10:50 % identity matrix from [10,10] to [50,50]
>> clf;
>> plot(fft(eye(k))) %plot
>> axis equal; axis off; axis([-1 1 -1 1]); % sort out axes
>> pause(0.01) %take a break
>> cf=cf+1; %update current frame
>> saveas(gcf, sprintf('frame%d', 1000+cf), 'jpg') %save the current frame as a jpg
>> end
This next bit of code tells the operating system (the bang command, !) to use the unix program 'convert' to make an animated gif out of all of those frames (i've set it to compress and downsize by half to save on file space)
>> !convert -antialias -loop 1000 -delay 5 -geometry 50% -compress LZW frame10* ffteye.gif
Gif creation is my new favourite toy - watch out Daily Daniel!
Saturday, 15 November 2008
in 5 minutes, for free (or 'balanced restored')
Originally posted in The Daily Daniel
--------------------------------------
People have said to me words along the lines of "why do you both with linux? it seems as though all it ever gives you is problems blah blah blah ..." - i don't know, I never listen to the rest. Yes, I do moan about linux a lot, and even in these pages ... well here's just 1 example of some routine thing I wanted to do where linux came to the rescue. I did it in 5 minutes
I had a folder full of pictures, and I wanted to make 2 copies of each - one a fraction of the size (for a thumbnail gallery), and one loads bigger - the images were smaller than the CCD used to capture them, so I knew I couldnt alias them. Right, well there's a linux command which does the job called 'convert'. Quick, really simple to use, e.g.:
>> convert my_image.jpg -resize 200% my_new_image.jpg
Does exactly what it says on the quick drying woodstain. But how to do the whole folder in one go? My old friend matlab comes to the rescue, and my personal favourite command 'system' - this bit of code will read in a folder of images, create 2 new folders, copy and resize each image, save it in the correct folder and append the file name with the operation done to it. All in the time it takes you to sneeze.
% find all the jpegs in the folder
>> direc=dir([pwd,filesep,'*.','jpeg']);
% create an empty cell to stick them in
>> filenames={};
% deal inputs into outputs
>> [filenames{1:length(direc),1}] = deal(direc.name);
% sort them and turn them into character arrays
>> filenames=sortrows(char(filenames{:}));
% make 2 directories - one called 'james_and_the_giant_peach' and one called 'thumblina'
>> mkdir([pwd,filesep,'james_and_the_giant_peach'])
>> mkdir([pwd,filesep,'thumblina'])
% simple loop
>> for i=1:size(filenames,1)
% giant images (500% size)
>> system(['convert ',deblank(filenames(i,:))...
,' -resize 500% ./james_and_the_giant_peach/',deblank(filenames(i,:)),'_giant.jpeg'])
% thumbnail images (20% size)
>> system(['convert ',deblank(filenames(i,:))...
,' -resize 20% ./thumblina/',deblank(filenames(i,:)),'_thumb.jpeg'])
>> end
Another example where matlab and linux combine beautifully. Matlab would have done it on its own (using imresize and imwrite commands), but it would have taken considerably longer.
Today is Boomtime. Good night
--------------------------------------
People have said to me words along the lines of "why do you both with linux? it seems as though all it ever gives you is problems blah blah blah ..." - i don't know, I never listen to the rest. Yes, I do moan about linux a lot, and even in these pages ... well here's just 1 example of some routine thing I wanted to do where linux came to the rescue. I did it in 5 minutes
I had a folder full of pictures, and I wanted to make 2 copies of each - one a fraction of the size (for a thumbnail gallery), and one loads bigger - the images were smaller than the CCD used to capture them, so I knew I couldnt alias them. Right, well there's a linux command which does the job called 'convert'. Quick, really simple to use, e.g.:
>> convert my_image.jpg -resize 200% my_new_image.jpg
Does exactly what it says on the quick drying woodstain. But how to do the whole folder in one go? My old friend matlab comes to the rescue, and my personal favourite command 'system' - this bit of code will read in a folder of images, create 2 new folders, copy and resize each image, save it in the correct folder and append the file name with the operation done to it. All in the time it takes you to sneeze.
% find all the jpegs in the folder
>> direc=dir([pwd,filesep,'*.','jpeg']);
% create an empty cell to stick them in
>> filenames={};
% deal inputs into outputs
>> [filenames{1:length(direc),1}] = deal(direc.name);
% sort them and turn them into character arrays
>> filenames=sortrows(char(filenames{:}));
% make 2 directories - one called 'james_and_the_giant_peach' and one called 'thumblina'
>> mkdir([pwd,filesep,'james_and_the_giant_peach'])
>> mkdir([pwd,filesep,'thumblina'])
% simple loop
>> for i=1:size(filenames,1)
% giant images (500% size)
>> system(['convert ',deblank(filenames(i,:))...
,' -resize 500% ./james_and_the_giant_peach/',deblank(filenames(i,:)),'_giant.jpeg'])
% thumbnail images (20% size)
>> system(['convert ',deblank(filenames(i,:))...
,' -resize 20% ./thumblina/',deblank(filenames(i,:)),'_thumb.jpeg'])
>> end
Another example where matlab and linux combine beautifully. Matlab would have done it on its own (using imresize and imwrite commands), but it would have taken considerably longer.
Today is Boomtime. Good night
Subscribe to:
Posts (Atom)