Showing posts with label graphic. Show all posts
Showing posts with label graphic. Show all posts

Thursday, February 14, 2013

[Matlab] show a normal random heart

% Just for fun, not really useful....
% @ http://scriptdemo.blogspot.com 
clear; close all;
r=0.618; n=10000; re=sqrt(1-r*r);
x=normrnd(0,1,n,1);
y=x*r+normrnd(0,1,n,1)*re;y(x<0)=-y(x<0);
plot(x,y,'o','markerEdgeColor',[1 0 1],'markerFaceColor','none');
axis equal tight off;
set(gcf,'MenuBar','none','color','w')

Monday, August 27, 2012

[Matlab] bar/tube plot along a 3d path

function hbarplot=barplot(x,y,z,varargin)
% plot a 3d surface/tube centered at (x,y,z)
% usage:
%           hbarplot=barplot(x,y,z,varargin)
%           varargin:
%                       'v' : the cdata values, same size as z
%                       'n' : N-isogon as the basic shape
%                       'r' : radius of the N-isogon
%    e.g.,
%          zz=0:0.5:10;
%          hh=barplot(cos(zz/10*pi),5,zz,'v',randn(1,numel(zz))+sin(zz/10*pi),'n',4,'r',sin(zz/10*pi)); view(3)
%          http://scriptdemo.blogspot.com

clc;
myN=3; myR=0.5; isV=0;
if nargin>3
   while(size(varargin,2)>0)
      switch lower(varargin{1})
      case {'v','cdata','colordata','facecolordata'}
          v=varargin{2};
          varargin(1:2)=[];
          isV=1;
      case {'n','nshape'}
          myN=varargin{2};
          varargin(1:2)=[];
      case {'r','radius'}
          myR=varargin{2};
          varargin(1:2)=[];
      otherwise
          error(['Not defined properties!',varargin{1}])
      end
   end
elseif nargin==0
   % demo case
   zz=0:0.5:10;
   hbarplot=barplot(cos(zz/10*pi),5,zz,'v',randn(1,numel(zz))+sin(zz/10*pi),'n',4,'r',sin(zz/10*pi));
   view(-150,30);
   return
elseif nargin<3
   help barplot
   return
end

[xx,yy,zz]=getMeshN(x,y,z,myR,myN);
if isV==0
   hbarplot=surface(xx',yy',zz');
else
   if numel(v)==numel(z)
      vv=repmat(reshape(v,[],1),1,size(xx,2));
   end
   hbarplot=surface(xx',yy',zz');
   set(hbarplot,'cdata',vv');
end
set(hbarplot,'tag','barplot','linestyle','none','facecolor','interp');
axis off equal
set(gcf,'color','w');

function [xx,yy,zz]=getMeshN(x0,y0,z,myR,N)
if nargin==3
   myR=0.5;
   N=3;
elseif nargin==4
   N=3;
elseif nargin~=5
   error('Usage: [xx,yy,zz]=getMeshN(x,y,z,myR,N)');
end
z=reshape(z,[],1);
numZ=numel(z);

myAng=linspace(0,2*pi,N+1);
xslab=cos(myAng); yslab=sin(myAng);
%N=numel(xslab)-1; % could be other shape as well.

if numel(x0)==1
   x0=repmat(x0,numZ,N+1);
elseif numel(x0)==numZ
   x0=repmat(reshape(x0,[],1),1,N+1);
end
if numel(y0)==1
   y0=repmat(y0,numZ,N+1);
elseif numel(y0)==numZ
   y0=repmat(reshape(y0,[],1),1,N+1);
end

if numel(myR)==1
   xx=repmat(xslab*myR,numZ,1)+x0;
   yy=repmat(yslab*myR,numZ,1)+y0;
else
   myR=repmat(reshape(myR,[],1),1,N+1);
   xx=repmat(xslab,numZ,1).*myR+x0;
   yy=repmat(yslab,numZ,1).*myR+y0;
end
zz=repmat(z,1,N+1);




Sunday, August 26, 2012

[Matlab] fill a specific-value region with a given color

function FillIt(lon,lat,Land,FillC,TagType,FillValue)
% To fill a specific-value region with a given color
% Usage:
%            FillIt(lon,lat,Land,FillC,TagType,FillValue)
%                   TagType: could be 'RU' or 'LD', 
%                                 to fill right-up square or left-down square
%                   FillValue: nan [default] or specific value to fill with color [FillC]
%            Note: lon, lat, Land must be the same size
%      e.g.,
%            FillIt(lon,lat,lsmask,[0.0 0.3 0.3],'RU')
%      http://scriptdemo.blogspot.com

if nargin==0
   %demo
   load topo topo;
   topo(topo>0)=nan;
   xx=1:360; yy=1:180;
   [xx,yy]=meshgrid(xx,yy);
   FillIt(xx,yy,topo,[0.4 0.3 0.4],'RU');
   set(gca,'tickdir','out','linewidth',2,'xminortick','on','yminortick','on','box','on','fontweight','bold');
   set(gcf,'color','w'); axis equal; axis tight;
   return
end

if nargin==3
   FillC=[0.3 0.3 0.3];
   TagType='RU';
   FillValue='nan';
elseif nargin==4
   TagType='RU';
   FillValue='nan';
elseif nargin==5
   FillValue='nan';
elseif nargin~=6
   help FillIt;
   return
end

if numel(lon)~=numel(lat)
   disp('lon and lat must be the same size')
   return
end
if numel(lon)~=numel(Land)
   disp('lon/lat and land must be the same size')
   return
end

[Ny,Nx]=size(Land);
if ischar(FillValue)
   if strcmpi(FillValue,'nan')
      [Indy,Indx]=find(isnan(Land));
   else
      disp(['invalid fill value: ',FillValue])
      return
   end
elseif isnumeric(FillValue)
      [Indy,Indx]=find(Land==FillValue);
else
      disp('invalid fill value')
      return
end

switch upper(TagType)
   case 'RU'
      % Right Up
      % 4----3
      % |      |
      % 1----2
      Indx(Indy==Ny)=[];Indy(Indy==Ny)=[];
      Indy(Indx==Nx)=[];Indx(Indx==Nx)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx)*Ny+Indy);
      Fillx(3,:)=lon((Indx)*Ny+Indy+1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy+1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);

      Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Filly(2,:)=lat((Indx)*Ny+Indy);
      Filly(3,:)=lat((Indx)*Ny+Indy+1);
      Filly(4,:)=lat((Indx-1)*Ny+Indy+1);
      Filly(5,:)=lat((Indx-1)*Ny+Indy);
   case 'LD'
      % Left Down
      % 2----1
      % |     |
      % 3----4
      Indx(Indy==1)=[];Indy(Indy==1)=[];
      Indy(Indx==1)=[];Indx(Indx==1)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx-2)*Ny+Indy);Filly(2,:)=lat((Indx-2)*Ny+Indy);
      Fillx(3,:)=lon((Indx-2)*Ny+Indy-1);Filly(3,:)=lat((Indx-2)*Ny+Indy-1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy-1);Filly(4,:)=lat((Indx-1)*Ny+Indy-1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);Filly(5,:)=lat((Indx-1)*Ny+Indy);
   otherwise
     disp('Not defined Fill Type')
     help FillIt
     return
end

if ~ishold; hold on; end
hf=patch(Fillx,Filly,FillC);
set(hf,'linestyle','none','tag','fillIt');

Friday, August 24, 2012

[Matlab] show 2d mesh grid

function ShowGridLine(lon,lat,NSkip,LineC,LineS,LineM)
% To show a 2d mesh-grid defined by given grid points
% similar to the function mesh?
% Example:
%          ShowGridLine(lon,lat,2,'k','-','.')
%          http://scriptdemo.blogspot.com
%

if (nargin>3)
    if exist('LineC','var')~=1 LineC='k'; end
    if exist('LineS','var')~=1 LineS='-'; end
    if exist('LineM','var')~=1 LineM='none'; end
elseif (nargin>=2)
    if exist('NSkip','var')==1
        if ischar(NSkip) LineC=NSkip; clear NSkip; end
    end
    if exist('NSkip','var')~=1 NSkip=5; end
    if exist('LineC','var')~=1 LineC='k'; end
    if exist('LineS','var')~=1 LineS='-'; end
    if exist('LineM','var')~=1 LineM='none'; end
elseif (nargin==0)
    close all;
    [xx,yy]=meshgrid(1:19,1:19);
    ShowGridLine(xx,yy,1,'k','-');
    plot(4,4,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(16,16,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(4,16,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    plot(16,4,'o','markerfacecolor','k','markersize',4,'markeredgecolor','k');
    set(gcf,'color','w');
    set(gca,'xtick',2:2:18,'ytick',2:2:18,'ydir','r','xaxislocation','top')
    axis equal; axis tight;
    xlabel('Go Board','fontweight','bold','fontsize',18,'color','red');
    return
else
    help ShowGridLine
    return
end

[N1,N2]=size(lat);
if ~ishold hold on; end
for NL=1:NSkip:N2
    hp=plot(lon(:,NL),lat(:,NL));
    set(hp,'color',LineC,'linestyle',LineS,'Marker',LineM)
end
for NL=1:NSkip:N1
    hp=plot(lon(NL,:),lat(NL,:));
    set(hp,'color',LineC,'linestyle',LineS,'Marker',LineM,'tag','gridLines')
end
Demo:

Saturday, February 25, 2012

[Matlab] create a time series using datenum

function myT=yymmdd2x(inYear,inMonth,inDay)
% create the time axis based on input time [year, mon, date], using datenum
% usage:
%           xTime=yymmdd2x(years, months, days);
% or
%           xTime=yymmdd2x(yyyymmdd);
http://scriptdemo.blogspot.com

if (nargin==0 || nargin>3)
   help yymmdd2x;
   return
end

if nargin==1
   %yyyymmdd case
   yyyymmdd=inYear;
   inYear=floor(yyyymmdd/10000);
   inDay=mod(yyyymmdd,100);
   inMonth=floor(mod(yyyymmdd,10000)/100); clear yyyymmdd
   totalDaysInYear=datenum(inYear+1,1,1)-datenum(inYear,1,1);
   daysInYear=datenum(inYear,inMonth,inDay)-datenum(inYear,1,1)+1;
   myT=daysInYear./totalDaysInYear+inYear;
elseif nargin==2
   % no date, set to 15th, may consider create 12 month for each year if necessary
   if length(inYear)~=length(inMonth) && length(inMonth)<=12
      % repeat inMonth for each year
      inMonth=reshape(inMonth,1,[]);
      mm=repmat(inMonth,1,length(inYear));
      yy=reshape(repmat(reshape(inYear,1,[]),length(inMonth),1),1,[]);
      clear inMonth inYear
      totalDaysInYear=datenum(yy+1,1,1)-datenum(yy,1,1);
      daysInYearA=datenum(yy,mm+1,1)-datenum(yy,1,1)+1;
      daysInYear=datenum(yy,mm,1)-datenum(yy,1,1)+1;
      myT=0.5*(daysInYearA+daysInYear)./totalDaysInYear+yy;

   elseif (length(inYear)==length(inMonth))
      totalDaysInYear=datenum(inYear+1,1,1)-datenum(inYear,1,1);
      daysInYearA=datenum(inYear,inMonth+1,1)-datenum(inYear,1,1)+1;
      daysInYear=datenum(inYear,inMonth,1)-datenum(inYear,1,1)+1;
      myT=0.5*(daysInYearA+daysInYear)./totalDaysInYear+inYear;
   else
       disp('Too difficult for me to guess what your wanna to do...')
       return
   end
else
   totalDaysInYear=datenum(inYear+1,1,1)-datenum(inYear,1,1);
   daysInYear=datenum(inYear,inMonth,inDay)-datenum(inYear,1,1)+1;
   myT=daysInYear./totalDaysInYear+inYear;
end

Friday, August 19, 2011

[Processing] spiral demo using Processing

//@ http://scriptdemo.blogspot.com
float myAngle, myScale, myAlpha0, myAlpha;
float shiftX, shiftY;
int rr,gg,bb;
// to control the shape of spiral
float minScale, dAngle, coefScale;
boolean isLine=false;
boolean isColor=true;

void setup()
{
  size(500,500);
  shiftX=width/2;
  shiftY=height/2;
  myAngle=0;
  myScale=1.0;
  minScale=0.01;
  coefScale=0.99;
  myAlpha0=8;
  dAngle=PI/50;

  noStroke();
  background(255);
  frameRate(30);
  smooth();
}

void draw()
{
   while(myScale>minScale)
   {
      pushMatrix();
      myAngle=myAngle+dAngle;
      myScale=myScale*coefScale;
      translate(shiftX,shiftY);
      rotate(myAngle);
      scale(myScale);
      if (isColor)
      {
         rr=ceil(255*sin(myAngle));
         gg=ceil(255*cos(myAngle));
         if (rr<=0) rr=rr+255;
         if (gg<=0) gg+=255;
         bb=(rr+gg)%256;
      } else {
        rr=10; gg=10; bb=10;
        if (isLine) myAlpha0=max(myAlpha0,20);
      }
      myAlpha=min(myAlpha0*(ceil(myAngle/TWO_PI)),255);
      if (isLine)
      {
        stroke(rr,gg,bb,myAlpha);
        noFill();
        line(-1*shiftX,shiftY,shiftX,shiftY);
      } else {
        noStroke();
        fill(bb,gg,rr,myAlpha);
        rect(-1*shiftX,shiftY,width,height);
      }
      popMatrix();
   }
}

void mouseClicked()
{
  isLine=!isLine;
  myAlpha=myAlpha0;
  myScale=1;
  myAngle=random(-PI,PI);
  background(255);
}
void mouseDragged()
{
   isColor=!isColor;
   myAlpha=myAlpha0;
   myScale=1;
   myAngle=random(-PI,PI);
   background(255);
}

Tuesday, May 10, 2011

png2eps: convert png image to eps with high resolution

#!/bin/bash
# convert a png file into eps file
# Usage:
#           png2eps pngfile.png [-q JPGQuality -r FigResizePercentage]
# e.g.,
#           png2eps aa.png bb.png -q 100 -r 60
# http://scriptdemo.blogspot.com

if [ $# == 0 ]; then
   sed -n '3,6p' png2eps
   exit
fi
JPGQuality='100'
FileResize='80'

nfile=0
while test -n "$1"
do
  case "$1" in
    -q|-quality)
       JPGQuality=$2
       shift
       ;;
    -r|-resize)
       FileResize=$2
       shift
       ;;
    *)
       if [ -e $1 ]; then
          pngfiles[$nfile]=$1
          nfile=`expr $nfile + 1`
       fi
       shift
       ;;
  esac
done
for pngfile in ${pngfiles[*]}
do
  #convert to jpg file first to keep high resolution
  jpgfile=${pngfile%%.*}.jpg
  epsfile=${pngfile%%.*}.eps
  eval "convert -quality ${JPGQuality} -resize ${FileResize}% ${pngfile} ${jpgfile}"
  [ -e ${epsfile} ] && epsfile=tmp_${epsfile}
  eval "convert ${jpgfile} eps3:${epsfile} && rm -f ${jpgfile}"
done
Another solution is to use png2pnm and pnm2ps commands:
#!/bin/bash
# convert a png file into eps file [using pngtopnm, pnmtops]
# Usage:
#           png2eps2 pngfile.png -scale reScale [-o outfile.eps]
# e.g.,
#           png2eps2 aa.png -scale 0.3 -o aa.eps
# http://scriptdemo.blogspot.com

if [ $# == 0 ]; then
   sed -n '3,6p' png2eps2
   exit
fi
reScale='0.3'

nfile=0
while test -n "$1"
do
  case "$1" in
    -s|-r|-scale|-rescale)
       reScale=$2
       shift
       ;;
    -o|-output)
       epsfile=$2
       shift
       ;;
    *)
       if [ -e $1 ]; then
          pngfiles[$nfile]=$1
          nfile=`expr $nfile + 1`
       fi
       shift
       ;;
  esac
done
for pngfile in ${pngfiles[*]}
do
  #convert to jpg file first and resize
  [ ! -n "$epsfile" ] && epsfile=${pngfile%%.*}.eps
  [ $nfile -gt 1 ] && epsfile=${pngfile%%.*}.eps
  [ -e ${epsfile} ] && epsfile=tmp_${epsfile}
  eval "pngtopnm ${pngfile} | pnmtops -noturn -nocenter -scale ${reScale} - >${epsfile}"
  eps2eps -dLanguageLevel=3 ${epsfile} thisTmp${epsfile} && mv thisTmp${epsfile} ${epsfile}
done

Thursday, March 3, 2011

[Processing] More Perlin Noise demo with Processing

Actually it is generated with the Perlin Noise Particle System from Dann Van Hasselt (http://www.openprocessing.org/visuals/?visualID=10475)
What I did is set the initial particle position in every loop (within draw()):
e.g., 
           myt=elapseFrames/10/TWO_PI;
           pos.x=0.5*width +(1-sin(myt))*cos(myt)*0.2*width;
           pos.y=0.5*height-(1-sin(myt))*sin(myt)*0.2*height;

Also you can change the color and particle details to get something like (online):
or a colourful one:

Perlin Noise demo with Processing

#copyright @ http://scriptdemo.blogspot.com
// inspired by the Perlin Noise Particle System from Daan van Hasselt (http://www.openprocessing.org/visuals/?visualID=10475)
// I recoded it with more additional features. Also it may be easier to understand without the class.
// Online test  from my dropbox (my Dropbox reference link)
float myw=400.0;
float myh=350.0;
float x, y;
float u=0;
float v=0;
float x0, y0, dx, dy;
float coefx, coefy, coefz;
boolean isAlive=false;
boolean isColor=true;
boolean isSmooth=true;
boolean isLoop=true;

int NumP=400;
float Npi;
void setup()
{
  Npi=2.3; coefx=0.009; coefy=0.011; coefz=0.0013;
  size(floor(myw),floor(myh));
  background(255,255,255);
  if (isSmooth) smooth();
}

void draw()
{

  for (int n=0; n<=NumP; n++)
  {
      if (isAlive)
      {
        float nv=noise(x*coefx,y*coefy,frameCount*coefz);
        if (isColor)
        {
           float mysin=sin((nv-0.3)*TWO_PI*Npi);
           float mycos=cos((nv-0.3)*TWO_PI*Npi);
           if (mycos>=0 & mysin >=0) fill(floor(abs(mysin)*255),floor(abs(mycos)*255),0,10);
           if (mycos>=0 & mysin <0) fill(floor(abs(mysin)*255),0,floor(abs(mycos)*255),10);
           if (mycos<0 & mysin >=0) fill(0,floor(abs(mycos)*255),floor(abs(mysin)*255),10);
           if (mycos<0 & mysin <0) fill(floor(abs(mysin)*255),floor(abs(mycos)*255),0,10);
        } else {
           fill(10,10);
        }
         u=u+cos((nv-0.3)*TWO_PI*Npi);
         v=v+sin((nv-0.3)*TWO_PI*Npi);
         u=u/2;
         v=v/2;
         x=x+u;
         y=y+v;
      } else {
        x0=0.5*myw;
        y0=0.5*myh;
        x=x0; y=y0;
        dx=100*frameCount/2000+50;
        dy=dx;
        isAlive=true;
      }
      noStroke();
      ellipse(x,y,1,1);
  }
  if (x>width || y> height || x <0 || y< 0) isAlive=false;
}

void mouseClicked()
{
  isLoop=!isLoop;
  if (!isLoop)
  {
     noLoop();
  } else {
     loop();
  }
}
Here are some demo videos:

ShowCalendar