Exemple #1
0
RDColX XMath::trigonResampling(int newSize, const RDColX &original) {
    int nslices = original.rows();
    if (newSize == nslices) {
        return original;
    }
    if (equalRows(original)) {
        return RDColX::Constant(newSize, original(0));
    }
    
    // fft
    PreloopFFTW::getR2C_RMat(nslices) = original;
    PreloopFFTW::computeR2C(nslices);
    CDColX &fourier = PreloopFFTW::getR2C_CMat(nslices);
    
    // densed sampling
    double dphi = 2. * pi / newSize;
    RDColX densed(newSize);
    for (int islice = 0; islice < newSize; islice++) {
        double phi = islice * dphi;
        double value_phi = fourier(0).real();
        for (int alpha = 1; alpha < fourier.size(); alpha++) {
            double factor = (nslices % 2 == 0 && alpha == fourier.size() - 1) ? 1. : 2.;
            value_phi += factor * (fourier(alpha) * exp(alpha * phi * iid)).real();
        }
        densed(islice) = value_phi;
    }
    return densed; 
}
Exemple #2
0
IMG* deblur2( const IMG* src, const IMG* psf, int size)
{
  double imgIn[FFT_SIZE][FFT_SIZE] = { 0 };
  double psfIn[FFT_SIZE][FFT_SIZE] = { 0 };
  double dstIn[FFT_SIZE][FFT_SIZE];

  Complex imgFreq[FFT_SIZE][FFT_SIZE];
  Complex psfFreq[FFT_SIZE][FFT_SIZE];
  Complex dstFreq[FFT_SIZE][FFT_SIZE];

  //copy img->imgIn;
  for( int h = 0 ; h < FFT_SIZE; ++h){
    for(int w = 0 ; w < FFT_SIZE; ++w){
      imgIn[h][w] = IMG_ELEM( src, h, w);
    }
  }
  //copy psf -> psfIn
  //deblur過程でpsfは反転する
  for(int h = 0; h < psf->height; ++h){
    for(int w = 0; w < psf->width; ++w){
      int y = psf->height - h;
      int x = psf->width - w;
      psfIn[h][w] = IMG_ELEM(psf, y, x);
    }
  }


  //fourier transform
  fourier(imgFreq, imgIn);
  fourier(psfFreq, psfIn);


  printf("fourier transform done\n");
  printPassedTime();

  //wiener deconvolution
  wienerdeconvolution( imgFreq, psfFreq, dstFreq, 0.0002);

  // invers fourier transform
  inverseFourier( dstIn, dstFreq);

  printf("wiener deconvolution and inverse fouiere transform done\n");
  printPassedTime();

  //copy to IMG structure
  IMG* dst = createImage(FFT_SIZE, FFT_SIZE);
  for(int h = 0; h < FFT_SIZE; ++h){
    for( int w = 0 ; w < FFT_SIZE; ++w){
      IMG_ELEM(dst, h, w) = fabs(dstIn[h][w]) / 3.0;

      if( h%10 == 0 && w%10 ==0)
	printf("dst[%03d][%03d] = %lf\n", h, w, dstIn[h][w]);

    }
  }

  return dst;  

}
Exemple #3
0
//sizeがある程度より小さいときとか
//0スタートじゃないと使いづらいかも
void createPSF( Complex dst[MAX_PSF_SIZE][FFT_SIZE][FFT_SIZE],
		const IMG* basePsf, int minSize, int maxSize)
{
  double psf[FFT_SIZE][FFT_SIZE];
  int h ,w;
  for(int size = minSize; size <= maxSize; ++size)
    {
      if( size <= 0 ) continue;
      printf("createPSF size = %d\n",size);
      IMG* img = createImage(size, size);
      resizeImage( basePsf, img);
      
      for(h=0;h<FFT_SIZE;++h){
	for(w=0;w<FFT_SIZE;++w){
	  psf[h][w] = 0.0;
	}
      }
      
      for(h=0;h<size;++h){
	for(w=0;w<size;++w){
	  psf[h][w] = (double)IMG_ELEM(img, size-h, size-w);
	}
      }
      
      releaseImage(&img);

      fourier(dst[size], psf);

    }

  printf("createPSF done\n");

  return;
}
Exemple #4
0
RDRowN XMath::computeFourierAtPhi(const RDMatXN &data, double phi) {
    int nslices = data.rows();
    RDRowN result;
    for (int col = 0; col < nPntElem; col++) {
        PreloopFFTW::getR2C_RMat(nslices) = data.col(col);
        PreloopFFTW::computeR2C(nslices);
        CDColX &fourier = PreloopFFTW::getR2C_CMat(nslices);
        double value_phi = fourier(0).real();
        for (int alpha = 1; alpha < fourier.size(); alpha++) {
            double factor = (nslices % 2 == 0 && alpha == fourier.size() - 1) ? 1. : 2.;
            value_phi += factor * (fourier(alpha) * exp(alpha * phi * iid)).real();
        }
        result(col) = value_phi;
    }
    return result;
}
Exemple #5
0
 gf<imfreq, T, S> make_gf_from_fourier(gf_const_view<imtime, T, S, E> const& gt, int n_iw = -1) {
  if (n_iw == -1) n_iw = (gt.mesh().size() - 1) / 2;
  auto m = gf_mesh<imfreq>{gt.mesh().domain(), n_iw};
  auto gw = gf<imfreq, T, S>{m, get_target_shape(gt)};
  gw() = fourier(gt);
  return gw;
 }
/**
 * \brief Construct a FourierTransform object from any type of image
 */
FourierImage::FourierImage(const ImagePtr image)
	: Image<double>(FourierImage::fsize(image->size())),
	  _orig(image->size()) {
	// first handle the case where the image in fact already is a double
	// image
	const Image<double>	*img = dynamic_cast<Image<double>*>(&*image);
	if (NULL != image) {
		fourier(*img);
		return;
	}

	// All other cases need an adapter to convert the image into a
	// double image first
	adapter::DoubleAdapter	a(image);
	Image<double>	in(a);
	fourier(in);
}
void convolution(const int N, const double W, dcomplex* fw, dcomplex* gw, dcomplex* hw){
    dcomplex *ft, *gt;
    dcomplex phase;
    
    ft = new dcomplex [N];
    gt = new dcomplex [N];

    fourier(N, fw, ft);
    fourier(N, gw, gt);
    
    phase=-1;
     /* "phase" is necessary for [-W/2,W/2] frequency regime, not for [0,W]. */ 
    for(int t=0;t<N;t++){
        phase*=-1;
        hw[t] = ft[t]*gt[t]*(W/N/N)*phase;
    }
    
    ifourier(N, hw, hw);
    
    delete [] ft;
    delete [] gt;
}
Exemple #8
0
/*!
 * \brief MainWindow::do_EPI_fourier
 */
void MainWindow::do_EPI_fourier(){
    if (DEBUG) cout << Q_FUNC_INFO << endl;

    if (EPI_coord_select->size() != 0){
        //Fourier
        bool res = fourier(EPI_coord_fourier, *EPI_coord_select);

        if (res){
            //Min-Max
            int xmin = (int)EPI_coord_fourier->coord(0, XCOORD);
            int xmax = (int)EPI_coord_fourier->coord(EPI_coord_fourier->size()-1, XCOORD);

            //Sliders
            EPI_slider_min_fourier->setRange(xmin, xmax);
            EPI_slider_max_fourier->setRange(xmin, xmax);

            //Boxes
            EPI_box_min_fourier->setRange(xmin, xmax);
            EPI_box_max_fourier->setRange(xmin, xmax);

            EPI_box_min_fourier->setValue(xmax*EPI_coeff_fourier_min);
            EPI_box_max_fourier->setValue(xmax*EPI_coeff_fourier_max);

            //Plot
            plot_EPI_fourier_curve();

            //Sliders
            EPI_slider_min_ifft->setRange(1, xmax*EPI_coeff_fourier_max);
            EPI_slider_max_ifft->setRange(1, xmax*EPI_coeff_fourier_max);

            //Boxes
            EPI_box_min_ifft->setRange(1, xmax*EPI_coeff_fourier_max);
            EPI_box_max_ifft->setRange(1, xmax*EPI_coeff_fourier_max);
            EPI_box_min_ifft->setValue(xmax*EPI_coeff_ifft_min);
            EPI_box_max_ifft->setValue(xmax*EPI_coeff_ifft_max);

            //Status
            status_info("");
        }
        else{
            status_error("");
        }
    }
    else{
        status_error("");
    }
}
Exemple #9
0
  template <typename G1, typename G2> std::enable_if_t<is_gf_v<G2, imfreq>> legendre_matsubara_inverse(G1 &&gl, G2 const &gw) {

    static_assert(is_gf_v<G1, legendre>, "First argument to legendre_matsubara_inverse needs to be a Legendre Green function");
    static_assert(std::is_same_v<typename std::decay_t<G1>::target_t, typename std::decay_t<G2>::target_t>,
                  "Arguments to legendre_matsubara_inverse require same target_t");

    gl() = 0.0;

    // Construct a temporary imaginary-time Green's function gt
    // I set Nt time bins. This is ugly, one day we must code the direct
    // transformation without going through imaginary time
    int Nt  = 50000;
    auto gt = gf<imtime, typename std::decay_t<G1>::target_t>{{gw.domain(), Nt}, gw.data().shape().front_pop()};

    // We first transform to imaginary time because it's been coded with the knowledge of the tails
    gt() = fourier(gw);
    legendre_matsubara_inverse(gl, gt());
  }
Exemple #10
0
main (int argc, char *argv[]) {
    int width, height, x, y, off_x, off_y;
    unsigned char *data;
    double maxPower;
    char fname[1000];

    if(argc != 2) {
        fprintf(stderr, "filter : test fourier transform library.\n");
        fprintf(stderr, "Usage : fourier <file name prefix>\n");
        fprintf(stderr, "file : PGM monochrome\n");
        exit(0);
    }

    // 読み出し ( 画素値型 unsigned char )
    data = readPGM(argv[1], &width, &height);
    printf("size = %d %d\n", width, height);

    fourier(fimage, (unsigned char (*)[FFT_SIZE])data);

    fourierSpectrumImage(image, fimage);

    strcpy(fname, argv[1]);
    strcat(fname, ".fft.pbm");
    writePGM(fname, (unsigned char *)image, FFT_SIZE, FFT_SIZE);

#if 1
    for( x = 0; x < FFT_SIZE; x++) {
        for( y = 0; y < FFT_SIZE; y++) {
            if((x > RAD && x < FFT_SIZE - RAD) || (y > RAD && y < FFT_SIZE - RAD)) {
                fimage[x][y].Re = fimage[x][y].Im = 0;
            }
        }
    }
#endif
    inverseFourier(image, fimage);

    strcpy(fname, argv[1]);
    strcat(fname, ".filt.pbm");
    writePGM(fname, (unsigned char *)image, FFT_SIZE, FFT_SIZE);

    free(data);
}
/**
 * \brief Construct a FourierTransform from an image adapter
 */
FourierImage::FourierImage(const ConstImageAdapter<double>& image)
	: Image<double>(FourierImage::fsize(image.getSize())),
	  _orig(image.getSize()) {
	Image<double>	i(image);
	fourier(i);
}
/**
 * \brief Construct a FourierTransform object from a double image
 */
FourierImage::FourierImage(const Image<double>& image)
	: Image<double>(FourierImage::fsize(image.size())),
	  _orig(image.size()) {
	fourier(image);
}
Exemple #13
0
 gf<refreq, Target, Singularity> make_gf_from_fourier(gf_const_view<retime, Target, Singularity, Evaluator> const& gt) {
  auto gw = gf<refreq, Target>{make_mesh_fourier_compatible(gt.mesh()), get_target_shape(gt)};
  gw() = fourier(gt);
  return gw;
 }
Exemple #14
0
int
ft_cktcoms(bool terse)
{
    wordlist *coms, *command, all;
    char *plottype, *s;
    struct dvec *v;
    static wordlist twl = { "col", NULL, NULL };
    struct plot *pl;
    int i, found;
    char numbuf[BSIZE_SP]; /* For printnum*/

    all.wl_next = NULL;
    all.wl_word = "all";

    if (!ft_curckt)
        return 1;

    plot_cur = setcplot("op");
    if (!ft_curckt->ci_commands && !plot_cur)
        goto nocmds;
    coms = ft_curckt->ci_commands;
    cp_interactive = FALSE;

    /* Listing */
    if (ft_listprint) {
        if (terse)
            fprintf(cp_err, ".options: no listing, rawfile was generated.\n");
        else
            inp_list(cp_out, ft_curckt->ci_deck, ft_curckt->ci_options, LS_DECK);
    }

    /* If there was a .op line, then we have to do the .op output. */
    plot_cur = setcplot("op");
    if (plot_cur != NULL) {
        assert(plot_cur->pl_dvecs != NULL);
        if (plot_cur->pl_dvecs->v_realdata != NULL) {
            if (terse) {
                fprintf(cp_out, "OP information in rawfile.\n");
            } else {
                fprintf(cp_out, "\t%-30s%15s\n", "Node", "Voltage");
                fprintf(cp_out, "\t%-30s%15s\n", "----", "-------");
                fprintf(cp_out, "\t----\t-------\n");
                for (v = plot_cur->pl_dvecs; v; v = v->v_next) {
                    if (!isreal(v)) {
                        fprintf(cp_err,
                                "Internal error: op vector %s not real\n",
                                v->v_name);
                        continue;
                    }
                    if ((v->v_type == SV_VOLTAGE) && (*(v->v_name) != '@')) {
                        printnum(numbuf, v->v_realdata[0]);
                        fprintf(cp_out, "\t%-30s%15s\n", v->v_name, numbuf);
                    }
                }
                fprintf(cp_out, "\n\tSource\tCurrent\n");
                fprintf(cp_out, "\t------\t-------\n\n");
                for (v = plot_cur->pl_dvecs; v; v = v->v_next)
                    if (v->v_type == SV_CURRENT) {
                        printnum(numbuf, v->v_realdata[0]);
                        fprintf(cp_out, "\t%-30s%15s\n", v->v_name, numbuf);
                    }
                fprintf(cp_out, "\n");

                if (!ft_nomod)
                    com_showmod(&all);
                com_show(&all);
            }
        }
    }

    for (pl = plot_list; pl; pl = pl->pl_next)
        if (ciprefix("tf", pl->pl_typename)) {
            if (terse) {
                fprintf(cp_out, "TF information in rawfile.\n");
                break;
            }
            plot_cur = pl;
            fprintf(cp_out, "Transfer function information:\n");
            com_print(&all);
            fprintf(cp_out, "\n");
        }

    /* Now all the '.' lines */
    while (coms) {
        command = cp_lexer(coms->wl_word);
        if (!command)
            goto bad;
        if (eq(command->wl_word, ".width")) {
            do
                command = command->wl_next;
            while (command && !ciprefix("out", command->wl_word));
            if (command) {
                s = strchr(command->wl_word, '=');
                if (!s || !s[1]) {
                    fprintf(cp_err, "Error: bad line %s\n", coms->wl_word);
                    coms = coms->wl_next;
                    continue;
                }
                i = atoi(++s);
                cp_vset("width", CP_NUM, &i);
            }
        } else if (eq(command->wl_word, ".print")) {
            if (terse) {
                fprintf(cp_out,
                        ".print line ignored since rawfile was produced.\n");
            } else {
                command = command->wl_next;
                if (!command) {
                    fprintf(cp_err, "Error: bad line %s\n", coms->wl_word);
                    coms = coms->wl_next;
                    continue;
                }
                plottype = command->wl_word;
                command = command->wl_next;
                fixdotprint(command);
                twl.wl_next = command;
                found = 0;
                for (pl = plot_list; pl; pl = pl->pl_next)
                    if (ciprefix(plottype, pl->pl_typename)) {
                        plot_cur = pl;
                        com_print(&twl);
                        fprintf(cp_out, "\n");
                        found = 1;
                    }
                if (!found)
                    fprintf(cp_err, "Error: .print: no %s analysis found.\n",
                            plottype);
            }
        } else if (eq(command->wl_word, ".plot")) {
            if (terse) {
                fprintf(cp_out,
                        ".plot line ignored since rawfile was produced.\n");
            } else {
                command = command->wl_next;
                if (!command) {
                    fprintf(cp_err, "Error: bad line %s\n",
                            coms->wl_word);
                    coms = coms->wl_next;
                    continue;
                }
                plottype = command->wl_word;
                command = command->wl_next;
                fixdotplot(command);
                found = 0;
                for (pl = plot_list; pl; pl = pl->pl_next)
                    if (ciprefix(plottype, pl->pl_typename)) {
                        plot_cur = pl;
                        com_asciiplot(command);
                        fprintf(cp_out, "\n");
                        found = 1;
                    }
                if (!found)
                    fprintf(cp_err, "Error: .plot: no %s analysis found.\n",
                            plottype);
            }
        } else if (ciprefix(".four", command->wl_word)) {
            if (terse) {
                fprintf(cp_out,
                        ".fourier line ignored since rawfile was produced.\n");
            } else {
                int err;

                plot_cur = setcplot("tran");
                err = fourier(command->wl_next, plot_cur);
                if (!err)
                    fprintf(cp_out, "\n\n");
                else
                    fprintf(cp_err, "No transient data available for "
                            "fourier analysis");
            }
        } else if (!eq(command->wl_word, ".save") &&
                   !eq(command->wl_word, ".op") &&
                   // !eq(command->wl_word, ".measure") &&
                   !ciprefix(".meas", command->wl_word) &&
                   !eq(command->wl_word, ".tf"))
        {
            goto bad;
        }
        coms = coms->wl_next;
    }

nocmds:
    /* Now the node table
       if (ft_nodesprint)
       ;
    */

    /* The options */
    if (ft_optsprint) {
        fprintf(cp_out, "Options:\n\n");
        cp_vprint();
        (void) putc('\n', cp_out);
    }

    /* And finally the accounting info. */
    if (ft_acctprint) {
        static wordlist ww = { "everything", NULL, NULL };
        com_rusage(&ww);
    } else if ((!ft_noacctprint) && (!ft_acctprint)) {
        com_rusage(NULL);
    }
    /* absolutely no accounting if noacct is given */

    putc('\n', cp_out);
    return 0;

bad:
    fprintf(cp_err, "Internal Error: ft_cktcoms: bad commands\n");
    return 1;
}
void 	correct (TrformStr *TrPtr, cPrefs *prefs)
{

    int 	i=0,j,k, kstart, kend, kdone, color;

    double 	scale_params[2];			// scaling factors for resize;
    double 	shear_params[2];			// shear values
    double	radial_params[6];			// coefficients for polynomial correction (0,...3)
    // and source width/2 (4) and correctionradius (5)
    double  lum_params[2];				// parameters to correct luminance variation

    struct  fDesc stack[10];            // Parameters for execute stack function
    struct  fDesc stackinv[10];         // Parameters for execute stack function

    int		destwidth, destheight;
    int 	xoff = 0, yoff = 0;
    int		sizesqr;

    double  xdoff, ydoff;
    Image	im, *dest, *src;
    fDesc	fD;
    fDesc	fDinv;

    im.data = NULL;

    src			= TrPtr->src;
    dest		= TrPtr->dest;

    // Apply filters, if required


    TrPtr->success = 1;

    if( prefs->luminance )
    {


        destwidth 		= TrPtr->src->width;
        destheight 		= TrPtr->src->height;

        // Allocate memory for destination image
        // If no further Xform: simply use SetDest

        if( !( 	prefs->resize 		||
                prefs->shear		||
                prefs->horizontal	||
                prefs->vertical 	||
                prefs->radial 		||
                prefs->cutFrame		||
                prefs->fourier)	)
        {
            if( SetDestImage(TrPtr, destwidth, destheight) != 0 )
            {
                TrPtr->success = 0;
                PrintError( "Not enough Memory.");
                return;
            }
        }
        else // Further Xform requested: use separate new image
        {
            memcpy( &im, TrPtr->src, sizeof(Image) );
            im.data = (unsigned char**) mymalloc( (size_t)im.dataSize );
            if( im.data == NULL )
            {
                TrPtr->success = 0;
                PrintError( "Not enough Memory.");
                return;
            }
            TrPtr->dest 	= &im;
        }

        // JMW 2003/08/25 Use the smaller of the width or height to
        // calculate luminance so that the same change is made to portrait and
        // landscape images.
        // MRDL 2003/08/25 Makes behavior consistent with lens distortion correction
        // algorithm
        if( TrPtr->src->width < TrPtr->src->height )
            sizesqr = (int)((TrPtr->src->width/2.0) * (TrPtr->src->width/2.0));
        else
            sizesqr = (int)((TrPtr->src->height/2.0) * (TrPtr->src->height/2.0));

        if( prefs->lum_params[0] ==  prefs->lum_params[1] &&
                prefs->lum_params[1] ==  prefs->lum_params[2] )  // Color independent
        {
            lum_params[0] =  - prefs->lum_params[0] / sizesqr;
            lum_params[1] =    prefs->lum_params[0] / 2.0 ;
            if( TrPtr->success != 0 )
            {
                filter( TrPtr, radlum, radlum16, (void*) lum_params, 0 );
            }
        }
        else // Color dependent
        {
            for(k=1; k<4; k++)
            {
                lum_params[0] =  - prefs->lum_params[k-1] / sizesqr;
                lum_params[1] =   prefs->lum_params[k-1] / 2.0 ;
                if( TrPtr->success != 0 )
                {
                    filter( TrPtr, radlum, radlum16, (void*) lum_params, k );
                }
            }
        }
    }

    if( TrPtr->success	&&  prefs->fourier )	// Fourier filtering required
    {
        if( prefs->luminance )
        {
            CopyImageData( src, &im );
            TrPtr->src = src;
        }

        if( prefs->fourier_mode == _fresize )
        {
            if( prefs->width == 0 && prefs->height == 0 )
            {
                TrPtr->success = 0;
                PrintError( "Zero Destination Image Size" );
                return;
            }

            if( prefs->width  )
                destwidth 		= prefs->width;
            else
                destwidth 		= (int)((double)TrPtr->src->width * (double)prefs->height / (double)TrPtr->src->height);

            if( prefs->height)
                destheight 		= prefs->height;
            else
                destheight		= (int)((double)TrPtr->src->height * (double)prefs->width / (double)TrPtr->src->width);
        }
        else
        {
            destwidth 		= TrPtr->src->width;
            destheight 		= TrPtr->src->height;
        }

        // Allocate memory for destination image
        // If no further Xform: simply use SetDest

        if( !( 	prefs->resize 		||
                prefs->shear		||
                prefs->horizontal	||
                prefs->vertical 	||
                prefs->radial 		||
                prefs->cutFrame	)	)
        {
            if( SetDestImage(TrPtr, destwidth, destheight) != 0 )
            {
                TrPtr->success = 0;
                PrintError( "Not enough Memory.");
                return;
            }
        }
        else // Further Xform requested: use separate new image
        {
            if( prefs->luminance )  // since then we have allocated im already
            {
                if( im.data ) myfree( (void**)im.data );
            }
            memcpy( &im, TrPtr->src, sizeof(Image) );
            im.width = destwidth;
            im.height = destheight;
            im.bytesPerLine = im.width * im.bitsPerPixel/8;
            im.dataSize = im.height * im.bytesPerLine;
            im.data = (unsigned char**) mymalloc( (size_t)im.dataSize );
            if( im.data == NULL )
            {
                TrPtr->success = 0;
                PrintError( "Not enough Memory.");
                return;
            }
            TrPtr->dest 	= &im;
        }

        fourier( TrPtr, prefs );
    }





    if( TrPtr->success		&&
            ( 	prefs->resize 		||
                prefs->shear		||
                prefs->horizontal	||
                prefs->vertical 	||
                prefs->radial 		||
                prefs->cutFrame)	)			// Displacement Xform requested
    {

        // First check whether recent luminance or fourier filtering
        if( prefs->luminance || prefs->fourier )
            TrPtr->src	= &im;

        TrPtr->dest = dest;

        // Set destination image parameters

        // most Xforms: dest = src

        destwidth 		= TrPtr->src->width;
        destheight 		= TrPtr->src->height;


        if( prefs->cutFrame )
        {
            if( getFrame( TrPtr->src, &xoff, &yoff, prefs->fwidth, prefs->fheight, TrPtr->mode & _show_progress ) != 0 )
            {
                TrPtr->success = 0;
                return;
            }
            //PrintError("x= %d, y= %d", xoff, yoff);
            destwidth 		=  prefs->fwidth ;
            destheight 		=  prefs->fheight ;
        }


        if(prefs->resize)
        {
            if( prefs->width == 0 && prefs->height == 0 )
            {
                TrPtr->success = 0;
                PrintError( "Zero Destination Image Size" );
                return;
            }

            if( prefs->width  )
                destwidth 		= prefs->width;
            else
                destwidth 		= (int)((double)TrPtr->src->width * (double)prefs->height / (double)TrPtr->src->height);

            if( prefs->height)
                destheight 		= prefs->height;
            else
                destheight		= (int)((double)TrPtr->src->height * (double)prefs->width / (double)TrPtr->src->width);
        }

        if( destwidth <= 0 || destheight <= 0 )
        {
            TrPtr->success = 0;
            PrintError( "Zero Destination Image Size" );
            return;
        }



        // Allocate memory for destination image

        if( SetDestImage(TrPtr, destwidth, destheight) != 0 )
        {
            TrPtr->success = 0;
            PrintError( "Not enough Memory.");
            goto _correct_exit;
        }



        // Check to see if the colors have the same or different displacement paras
        if( isColorSpecific( prefs ) )  // Color dependent
        {

            if( haveSameColorParas( prefs,0,1)) // R==G??
            {
                fprintf(stderr, "PT correct "PROGRESS_VERSION" R==G\n" );
                if( ! hasUsefulColorParas(prefs,0))
                {
                    fprintf(stderr, "Red/Green do NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing just the Blue...\n" );
                    kstart=3;
                    kend  =3;
                }
                else if( ! hasUsefulColorParas(prefs,2))
                {
                    fprintf(stderr, "Blue does NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing the Red/Green simultaneously...\n" );
                    kstart=4;
                    kend  =4;
                }
                else
                {
                    kstart=4;
                    kend  =3;
                }


            }
            else if( haveSameColorParas( prefs,1,2)) // G==B??
            {
                fprintf(stderr, "PT correct "PROGRESS_VERSION" G==B\n" );
                if( ! hasUsefulColorParas(prefs,1))
                {
                    fprintf(stderr, "Green/Blue do NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing just the Red...\n" );
                    kstart=1;
                    kend  =1;
                }
                else if( ! hasUsefulColorParas(prefs,0))
                {
                    fprintf(stderr, "Red does NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing the Green/Blue simultaneously...\n" );
                    kstart=6;
                    kend  =6;
                }
                else
                {
                    kstart=6;
                    kend  =1;
                }



            }
            else if( haveSameColorParas( prefs,2,0)) // R==B??
            {
                fprintf(stderr, "PT correct "PROGRESS_VERSION" R==B\n" );
                if( ! hasUsefulColorParas(prefs,0))
                {
                    fprintf(stderr, "Red/Blue do NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing just the Green...\n" );
                    kstart=2;
                    kend  =2;
                }
                else if( ! hasUsefulColorParas(prefs,1))
                {
                    fprintf(stderr, "Green does NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing the Red/Blue simultaneously...\n" );
                    kstart=5;
                    kend  =5;
                }
                else
                {
                    kstart=5;
                    kend  =2;
                }


            }
            else
            {
                fprintf(stderr, "PT correct "PROGRESS_VERSION" R!=G!=B\n" );
                if( ! hasUsefulColorParas(prefs,0))
                {
                    fprintf(stderr, "Red does NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing the Green then Blue separately...\n" );
                    kstart=2;
                    kend  =3;
                }
                else if( ! hasUsefulColorParas(prefs,1))
                {
                    fprintf(stderr, "Green does NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing the Blue then Red separately...\n" );
                    kstart=3;
                    kend  =1;
                }
                else if( ! hasUsefulColorParas(prefs,2))
                {
                    fprintf(stderr, "Blue does NOTHING! Copying image data...\n" );
                    CopyImageData( TrPtr->dest, TrPtr->src );
                    fprintf(stderr, "Displacing the Red then Green separately...\n" );
                    kstart=1;
                    kend  =2;
                }
                else
                {
                    kstart 	= 1;
                    kend	= 3;
                }

            }
        }
        else // Color independent
        {
            fprintf(stderr, "PT correct "PROGRESS_VERSION" R==G==B\n" );
            if( ! hasUsefulColorParas(prefs,0))
            {
                fprintf(stderr, "Red,Green,Blue do NOTHING! But you asked for it...\n" );
            }
            kstart	= 0;
            kend	= 0;
        }

        // Do the necessary displacements, either per color, 2-colors, or on all 3 colors.
        kdone=0;
        k=kstart;
        while(!kdone)
        {
            switch(k) // choose which color's paras to use
            {
            case 0: // RGB
                color = 0;// Use the Red paras
                break;

            case 1: // [0] = R
            case 2: // [1] = G
            case 3: // [2] = B
                color = k-1;
                break;

            case 4:// RG
                color=0;
                break;
            case 5:// RB
                color=0;
                break;
            case 6:// GB
                color=1;
                break;
            default:
                color=0;
                break;
            }

            i = 0;

            if( prefs->resize )
            {
                if(prefs->cutFrame)
                {
                    if( prefs->width )
                        scale_params[0] = ((double)prefs->fwidth)/ prefs->width;
                    else
                        scale_params[0] = ((double)prefs->fheight)/ prefs->height;

                    if( prefs->height )
                        scale_params[1] = ((double)prefs->fheight)/ prefs->height;
                    else
                        scale_params[1] = scale_params[0];
                }
                else
                {
                    if( prefs->width )
                        scale_params[0] = ((double)TrPtr->src->width)/ prefs->width;
                    else
                        scale_params[0] = ((double)TrPtr->src->height)/ prefs->height;

                    if( prefs->height )
                        scale_params[1] = ((double)TrPtr->src->height)/ prefs->height;
                    else
                        scale_params[1] = scale_params[0];
                }
                SetDesc(stack[i],resize,scale_params);
                i++;
            }

            // JMW 2008/01/03 make the order the same as Adjust doing correct
            if( prefs->radial )
            {
                switch( prefs->correction_mode)
                {
                case correction_mode_radial:
                    SetDesc(stack[i],radial, radial_params);
                    i++;
                    radial_params[4] = ( (double)( TrPtr->src->width < TrPtr->src->height ?
                                                   TrPtr->src->width : TrPtr->src->height) ) / 2.0;
                    break;
                case correction_mode_vertical:
                    SetDesc(stack[i],vertical, radial_params);
                    i++;
                    radial_params[4] = ((double)TrPtr->src->height) / 2.0;
                    break;
                case correction_mode_deregister:
                    SetDesc(stack[i],deregister, radial_params);
                    i++;
                    radial_params[4] = ((double)TrPtr->src->height) / 2.0;
                    break;
                }
                for(j=0; j<4; j++)
                    radial_params[j] = prefs->radial_params[color][j];
                radial_params[5] = prefs->radial_params[color][4];
            }

            if (prefs->vertical)
            {
                SetDesc(stack[i],vert,&(prefs->vertical_params[color]));
                i++;
            }

            if (prefs->horizontal)
            {
                SetDesc(stack[i],horiz,&(prefs->horizontal_params[color]) );
                i++;
            }

            if( prefs->shear )
            {
                shear_params[0] = prefs->shear_x / TrPtr->src->height;
                shear_params[1] = prefs->shear_y / TrPtr->src->width;
                SetDesc(stack[i],shear,shear_params);
                i++;
            }

            if( prefs->cutFrame )
            {
                if( xoff != 0 )
                {
                    xdoff = (double) xoff + 0.5 * ( prefs->fwidth - TrPtr->src->width ) ;
                    SetDesc(stack[i],horiz, &xdoff );
                    i++;
                }

                if( yoff != 0 )
                {
                    ydoff = (double)yoff + 0.5 * ( prefs->fheight - TrPtr->src->height) ;
                    SetDesc(stack[i],vert,&ydoff);
                    i++;
                }
            }

            stack[i].func = (trfn)NULL;

            if( 	!prefs->resize 		&&
                    !prefs->shear		&&
                    !prefs->horizontal	&&
                    !prefs->vertical 	&&
                    !prefs->radial 		&&
                    prefs->cutFrame )	// Only cutframe
            {
                ShiftImage(TrPtr, xoff, yoff);
            }
            else if( TrPtr->success != 0 && i != 0 )
            {
                // Copy and reverse the stack to make the inverse stack
                int ii = 0;
                while(i)
                {
                    stackinv[ii] = stack[i-1];
                    i--;
                    ii++;
                }
                stackinv[ii].func = (trfn)NULL;

                fD.func    = execute_stack_new;
                fD.param    = stack;
                fDinv.func = execute_stack_new;
                fDinv.param = stackinv;
                transFormEx( TrPtr, &fD, &fDinv, k, 1 );
                i = ii;
            }

            switch(k) // We use k as control var for a little statemachine:
            {
            case 0:// RGB
                kdone=1;
                break;

            case 1:// R
            case 2:// G
            case 3:// B
                if(k==kend)
                {
                    kdone=1;
                }
                else
                {
                    k++;

                    if(k==4)
                        k=1;
                }
                break;

            case 4:// RG
            case 5:// RB
            case 6:// GB
                if(k==kend)
                {
                    kdone=1;
                }
                else
                {
                    k=kend;
                }
                break;

            default:
                kdone=1;
                break;
            }

        }// END:while(!kdone)
    }


    if( !prefs->luminance && !prefs->fourier && !prefs->cutFrame && i == 0 ) // We did nothing!
    {
        TrPtr->success = 0;
    }

    if( TrPtr->success == 0 && ! (TrPtr->mode & _destSupplied))
        myfree( (void**)TrPtr->dest->data );

_correct_exit:

    TrPtr->src 		= src;
    TrPtr->dest 	= dest;


    if( im.data != NULL )
        myfree((void**)im.data);


}
Exemple #16
0
void
com_fourier(wordlist *wl)
{
    fourier(wl, plot_cur);
}
Exemple #17
0
void ControlWidget::sawtooth()
{
    fourier(2);
}
Exemple #18
0
void ControlWidget::square()
{
    fourier(1);
}
Exemple #19
0
IMG* deblur(const IMG* src, 
	    const IMG* psfBase,
	    const IMG* disparityMap,
	    double param[])
{
  int h,w;
  int maxDisparity = MAX_DISPARITY;
  int BlockRows = ceil( (double)src->height / (double)BLOCK_SIZE );
  int BlockCols = ceil( (double)src->width / (double)BLOCK_SIZE );

  
  //psf
  Complex psf[MAX_PSF_SIZE][CUT_OFF_SIZE][CUT_OFF_SIZE];
  createPSF(psf, psfBase, 1, MAX_PSF_SIZE-1);

  //窓関数
  Mat window = createWindowFunction();
  
  //最終的な結果を保存しておく場所
  Mat dstMat = matrixAlloc( src->height, src->width);
  Mat wegithMat = matrixAlloc( src->height, src->width);

  //0で初期化
  for( h = 0; h < dstMat.row; ++h){
    for( w = 0; w < dstMat.clm; ++w){
      ELEM0(dstMat, h, w) = 0.0;
      ELEM0(wegithMat, h, w) = 0.0;
    }
  }


  //作業用領域
  double srcIn[CUT_OFF_SIZE][CUT_OFF_SIZE];
  double dstIn[CUT_OFF_SIZE][CUT_OFF_SIZE];
  
  Complex srcF[CUT_OFF_SIZE][CUT_OFF_SIZE];
  Complex dstF[CUT_OFF_SIZE][CUT_OFF_SIZE];


  
  for(int row = 0; row < BlockRows; ++row){
    for(int col = 0 ; col < BlockCols; ++col){

      //copy & window function
      for( h = 0; h < CUT_OFF_SIZE; ++h){
	for( w = 0; w < CUT_OFF_SIZE; ++w){
	  srcIn[h][w] = 0.0;
	  
	  int y = h + row * BLOCK_SIZE + ( BLOCK_SIZE - CUT_OFF_SIZE ) / 2;
	  int x = w + col * BLOCK_SIZE + ( BLOCK_SIZE - CUT_OFF_SIZE ) / 2;

	  if( y < 0 || y >= src->height || w < 0 || w >= src->width){
	    continue;
	  }else{
	    srcIn[h][w] = (double)IMG_ELEM(src, y, x) * ELEM0(window, h, w);
	  }
	}
      }
      //copy done

      //kernel sizeの決定
      int disparity = (int)IMG_ELEM(disparityMap, row*BLOCK_SIZE + BLOCK_SIZE/2, col*BLOCK_SIZE + BLOCK_SIZE/2);
      int kernelSize =  param[0]*(double)disparity + param[1] ;
      
      //printf("disprity = %d, kernelSize = %d\n",disparity, kernelSize);

      //srcをDFT
      fourier(srcF, srcIn);

      //wiener deconvolution
      wienerdeconvolution(srcF, psf[kernelSize], dstF, SNR);

      //IDFT
      inverseFourier(dstIn, dstF);
      
      //copy to dstMat
      for(h=0;h<CUT_OFF_SIZE;++h){
	for(w=0;w<CUT_OFF_SIZE;++w){
	  int y = h + row * BLOCK_SIZE + (BLOCK_SIZE-CUT_OFF_SIZE)/2;
	  int x = w + col * BLOCK_SIZE + (BLOCK_SIZE-CUT_OFF_SIZE)/2;

	  if( y < 0 || y >= src->height || x < 0 || x >= src->width){
	    continue;
	  }else{
	    ELEM0(dstMat, y, x) += dstIn[h][w];
	    ELEM0(wegithMat, y, x) += ELEM0(window, h, w);
	  }

	}//w
      }//h
      


    }//col
  }//row

  printPassedTime();


  //最終的に返す構造体
  IMG* dst = createImage( src->height, src->width);

  //weright mean
  for(h=0;h<dstMat.row;++h){
    for(w=0;w<dstMat.clm;++w){
      ELEM0(dstMat, h, w) /= ELEM0(wegithMat, h, w);
    }
  }

  for( h = 0 ; h < dst->height ; ++h ){
    for( w = 0 ; w < dst->width ; ++w ){
      IMG_ELEM( dst, h, w) = fabs( ELEM0( dstMat, h, w) ) / 3.0;
    }
  }


  //後片付け
  matrixFree(dstMat);
  matrixFree(wegithMat);
  matrixFree(window);

  return dst;
}
Exemple #20
0
int main(int argc, char *argv[])
{
    /* Important definitions */
    // Lengths
    size_t N = 0;  // Length of time series
    size_t M = 0;  // Length of sampling vector (number of frequencies)

    // Filenames
    char inname[100];
    char outname[100];

    // Sampling
    double low, high, rate;

    // Frequency of window function
    double winfreq = 0;

    // Options
    int quiet = 0;
    int unit = 1;
    int prep = 1;
    int autosamp = 0;
    int fast = 0;
    int useweight = 0;
    int windowmode = 0;
    int Nclean = 0;
    int filter = 0;

    
    /* Process command line arguments and return line count of the input file */
    N = cmdarg(argc, argv, inname, outname, &quiet, &unit, &prep, &low, &high,\
               &rate, &autosamp, &fast, &useweight, &windowmode, &winfreq,\
               &Nclean, &filter, NULL, NULL);
    
    // Pretty print
    if ( quiet == 0 || fast == 1 ){
        if ( windowmode == 0 && useweight != 0 )
            printf("\nCalculating the weighted power spectrum of \"%s\" ...\n",\
                   inname);
        else if ( windowmode == 0 )
            printf("\nCalculating the power spectrum of \"%s\" ...\n", inname);
        else
            printf("\nCalculating the window function of \"%s\" ...\n", inname);
    }
    

    /* Read data (and weights) from the input file */
    if ( quiet == 0 ) printf(" - Reading input\n");
    double* time = malloc(N * sizeof(double));
    double* flux = malloc(N * sizeof(double));
    double* weight = malloc(N * sizeof(double));
    readcols(inname, time, flux, weight, N, useweight, unit, quiet);
    
    // Do if fast-mode and window-mode is not activated
    if ( fast == 0 && windowmode == 0 ) {
        // Calculate Nyquist frequency
        double* dt = malloc(N-1 * sizeof(double));
        double nyquist;
        arr_diff(time, dt, N);
        nyquist = 1.0 / (2.0 * arr_median(dt, N-1)) * 1e6; // microHz !
        free(dt);

        // Calculate suggested sampling (4 times oversampling)
        double minsamp;
        minsamp = 1.0e6 / (4 * (time[N-1] - time[0])); // microHz !
    
        // Display info?
        if ( quiet == 0 ){
            printf(" -- INFO: Length of time series = %li\n", N);
            printf(" -- INFO: Nyquist frequency = %.2lf microHz\n", nyquist);
            printf(" -- INFO: Suggested minimum sampling = %.3lf microHz\n",\
                   minsamp);
        }

        // Apply automatic sampling?
        if ( autosamp != 0 ) {
            low = 5.0;
            high = nyquist;
            rate = minsamp;
        }
    }

    
    /* Prepare for power spectrum */
    // Calculate proper frequency range for window-function-mode
    double limit = 0;
    if ( windowmode != 0 ) {
        limit = low;
        low = winfreq - limit;
        high = winfreq + limit;
    }
    
    // Get length of sampling vector
    M = arr_util_getstep(low, high, rate);

    // Fill sampling vector with cyclic frequencies
    double* freq = malloc(M * sizeof(double));
    arr_init_linspace(freq, low, rate, M);

    // Initialise arrays for data storage
    double* power = malloc(M * sizeof(double));
    double* alpha = malloc(M * sizeof(double));
    double* beta = malloc(M * sizeof(double));


    /* Calculate power spectrum OR window function */
    if ( windowmode == 0 ) {
        // Subtract the mean to avoid "zero-frequency" problems
        if ( prep != 0 ) {
            if ( quiet == 0 ){
                printf(" - Subtracting the mean from time series\n");
            }
            arr_sca_add(flux, -arr_mean(flux, N), N);
        }
        else {
            if ( quiet == 0 )
                printf(" - Time series used *without* mean subtraction!\n");
        }
    
        // Display info
        if ( quiet == 0 ){
            printf(" - Calculating fourier transform\n");
            if ( autosamp != 0 ) {
                printf(" -- NB: Using automatic sampling!\n");
                printf(" -- INFO: Auto-sampling (in microHz): %.2lf to %.2lf"\
                       " in steps of %.4lf\n", low, high, rate);
            }
            else {
                printf(" -- INFO: Sampling (in microHz): %.2lf to %.2lf in"\
                       " steps of %.4lf\n", low, high, rate);
            }
            printf(" -- INFO: Number of sampling frequencies = %li\n", M);
        }

        // Calculate power spectrum with or without weights
        fourier(time, flux, weight, freq, N, M, power, alpha, beta, useweight);
    }
    else {
        if ( quiet == 0 ){
            printf(" - Calculating window function\n");
            printf(" -- INFO: Window frequency = %.2lf microHz\n", winfreq);
            printf(" -- INFO: Sampling in the range +/- %.2lf microHz in" \
                   " steps of %.4lf microHz\n", limit, rate);
            printf(" -- INFO: Number of sampling frequencies = %li\n", M);
        }

        // Calculate spectral window with or without weights
        windowfunction(time, freq, weight, N, M, winfreq, power, useweight);

        if ( quiet == 0 )
            printf(" - Sum of spectral window = %.4lf\n", arr_sum(power, M));

        // Move frequencies to the origin
        arr_sca_add(freq, -winfreq, M);
    }

        
    /* Write data to file */
    if ( quiet == 0 ) printf(" - Saving to file \"%s\"\n", outname);
    writecols(outname, freq, power, M);

    
    /* Free data */
    free(time);
    free(flux);
    free(weight);
    free(freq);
    free(power);
    free(alpha);
    free(beta);


    /* Done! */
    if ( quiet == 0 || fast ==1 ) printf("Done!\n\n");
    return 0; 
}
Exemple #21
0
 gf<imfreq, Target, Opt> make_gf_from_fourier(gf_impl<imtime, Target, Opt, V, C> const& gt) {
  auto gw = gf<imfreq, Target, Opt>{make_mesh_fourier_compatible(gt.mesh()), get_target_shape(gt)};
  gw() = fourier(gt);
  return gw;
 }