def main(imgname):
    global mycompress,myoutfile

    from FFT2util import FFT2D,iFFT2D,matslice,realintmat
    from FFTjan import mat2dict,dict2mat
    from Tools import find_cutoff_nd

    data, dim = img3mat(imgname)

    print "starting encoding of image %s" % (imgname)
    encoded = map(FFT2D,data)
    print "encoding succesfull"

    dim2 = (len(encoded[0][0]),len(encoded[0]))
    print dim2

    import numpy as np
    cutoff = find_cutoff_nd( np.array(encoded), mycompress )

    print "making dicks"
    dicks = map(lambda x: mat2dict(x,cutoff),encoded)
    
    print len(dicks[0])
    
    print map(lambda x: compress(x[0],x[1]), zip(dicks,encoded))

    print "listing dicks"
    lists = map(lambda x: dict2mat(x,dim2[0],dim2[1]),dicks)
    
    print "starting decoding"
    decoded = map(iFFT2D,lists)
    
    print "decoding succesfull"
    sliced = map(lambda x: matslice(realintmat(x),dim),decoded)

    if myoutfile != None:
        filename = myoutfile
    else:
        filename = imgname.replace('.','_new.')
    print "saving to",filename
    mat3img(sliced,dim).save(filename)
def main():
  x = np.array(
    [[[1,1,1,1],
      [1,1,1,1],
      [1,1,0,1],
      [1,1,1,1]],
     [[1,1,1,1],
      [1,1,1,1],
      [1,1,1,1],
      [1,1,1,1]],
     [[1,1,1,1],
      [1,1,1,1],
      [1,1,2,1],
      [1,1,1,1]],
     [[1,1,1,1],
      [1,1,1,1],
      [1,1,3,1],
      [1,1,1,1]]]
  )
  x_float = x.astype('float')

  wavelet = HaarWavelet

  X = wavelet.dwt(x_float)
  cutoff = find_cutoff_nd( X, 0.3 )

  print X
  print cutoff

  dict = mat_3d_to_dict( X, cutoff )
  X_ = dict_to_mat_3d( dict, X.shape[0], X.shape[1], X.shape[2] )

  print dict

  x_ = wavelet.idwt(X_)
  print x_
  print PSNR( x_float, x_ )
    data = map(lambda x: np.array(x), data)
    data_float = map(lambda x: x.astype('float'),data)

    print "Starting encoding of image %s" % (sys.argv[1])
    print "Image has dimensions : %i,%i" % dim
    print

    encoded = map(mywavelet.dwt,data_float)
    interdims = encoded[0].shape

    print "Encoding done"
    print "Using dimensions:",interdims
    print

    # Temporary bypass to check for problems in main algorithm -- Confirmed 
    compression = find_cutoff_nd( encoded, 0.0 )

    print "Converted to dictionaries:"
    print "Compression cutoff is %f" % compression

    dicks = map(lambda x: mat_3d_to_dict(x,compression),encoded)

    print "Dictionary lengths:"
    for x in dicks: 
      print len(x)

    print "Compression factor per channel:"
    print map(lambda x: compress(x[0],x[1]), zip(dicks,encoded))
    print

    print "Converting dictionaries to matrices"
def plaatje(plaat):
  global mywavelet, mycompress, myoutfile, mytensor, mydelay, mytensor, mythreshfunc

  print "compressing",plaat
  print "tensor is %s" % ("on" if mytensor else "off")
  print "thresholding :",mythreshfunc
  print "splitting up gif... (this may take a while)"
  call(["gifsicle", "--unoptimize", "-e", plaat, "-o", plaat])

  gifs = sorted(glob(''.join([plaat,".*"])))
  driedlist = [[],[],[],[]]

  for f in gifs:
    data, dim = img3mat( f )
    for i in range( len(data) ):
      driedlist[i].append(data[i])

  data = map( lambda x: np.array( x ), driedlist )
  print np.array(data).shape
  data_float = map( lambda x: x.astype('float'), data )

  encoded = np.array(map( lambda x: mywavelet.dwt(x,tensor=mytensor), data_float ))
  interdims = encoded[0].shape
  print "interdims:", interdims

  compression = find_cutoff_nd( encoded, mycompress )

  dicks = map( lambda x: mat_3d_to_dict( x, compression, mythreshfunc ), encoded )
  print map( lambda x: compress( x[0], x[1] ), zip( dicks, encoded ) )

  lists = map( lambda x: dict_to_mat_3d( x, interdims[0], interdims[1], interdims[2]), dicks )
  lists = map( lambda x: np.array(x), lists )

  decoded = map( lambda x: mywavelet.idwt(x,tensor=mytensor), lists )
  sliced = map( lambda x: np.rint(x).astype( data[0].dtype ), decoded )
  print PSNR( np.array(data), np.array(sliced) )

  frames, rows, cols = sliced[0].shape
  channels = len(sliced)
  frame_list = [] #np.zeros((frames, rows, cols, channels))
  #maak van lijst van channels, een lijst van frames
  for i in range( frames ):
    frame = np.zeros((channels, rows, cols))
    for j in range( channels ):
      frame[j,:,:] = sliced[j][i,:,:]
    frame_list.append(frame)

  print "converting gifs"
  for i, frame in enumerate( frame_list ):
    print "converting frame %i" % i
    fn = ''.join(["gif/temp.", str(i).zfill(3), ".png"])
    mat5img(frame, (rows, cols) ).save( fn )
    os.system(' '.join(["convert", fn, fn.replace("png", "gif")]))

  if myoutfile == None:
    filename = plaat.replace('.','_new.')
  else:
    filename = myoutfile
  print "Saving gif to",filename
  os.system(''.join(
    ["gifsicle -d ",
     str(mydelay),
     " --loopcount=forever -m ",
     "gif/temp.*.gif"
     ," > ",filename]))

  print "removing temp files"
  call(["rm"]+list(glob('gif/temp.*.gif')))
  call(["rm"]+list(glob('gif/temp.*.png')))
def main(infile):
  global mycompress,mywavelet,myoutfile,mytensor,mythreshfunc

  data, dim = img3mat(infile)
  
  data = map(lambda x: np.array(x), data)
  data_float = map(lambda x: x.astype('float'),data)

  print "Starting encoding of image %s" % (argv[1])
  print "TensorProduct =",mytensor
  print "Threshold func =",mythreshfunc
  print "Image has dimensions : %i,%i" % dim
  print

  encoded = map(lambda x: mywavelet.dwt(x,tensor=mytensor),data_float)
  interdims = (len(encoded[0]),len(encoded[0][0]))

  print "Encoding done"
  #  print_dimensions_matlist("Encoded dims:",encoded)
  print "Using dimensions:",interdims
  print

  """ Temporary bypass to check for problems in main algorithm -- Confirmed """
  cutoff = find_cutoff_nd( encoded, mycompress )
  
  print "Converted to dictionaries:"
  print "Compression cutoff is %f" % cutoff

  dicks = map(lambda x: mat5dict(x,cutoff,mythreshfunc),encoded)

  print "Dictionary lengths:"
  for x in dicks:
    print len(x)

  print "Compression factor per channel:"
  print map(lambda x: compress(x[0],x[1]), zip(dicks,encoded))
  print

  print "Converting dictionaries to matrices"
  print "Dimensions are %i,%i" % interdims

  lists = map(lambda x: dict5mat(x,interdims[0],interdims[1]),dicks)  
  lists = map(lambda x: np.array(x), lists)

  print "Starting decoding"

  decoded = map(lambda x: mywavelet.idwt(x,tensor=mytensor),lists)

  print "Decoding done"  
  #  print_dimensions_matlist("Decoded dimensions are:",decoded)
  #  print

  sliced = map(lambda x: np.rint(x).astype(data[0].dtype),decoded)

  #  print_dimensions_matlist("Sliced dimensions are:",sliced)

  if myoutfile == None:
    filename = infile.replace('.','_new.')
  else:
    filename = myoutfile
  print "Saving to",filename
  mat5img(sliced,dim).save(filename)