Beispiel #1
0
/*!
  \fn VImage VDTDilate(VImage src,VImage dest,VDouble radius)
  \brief 3D morphological dilation
  \param src   input image (bit repn)
  \param dest  output image (bit repn)
  \param radius radius of the spherical structural element
*/
VImage
VDTDilate(VImage src,VImage dest,VDouble radius)
{
  VImage float_image;
  VBit *bin_pp;
  VFloat *float_pp;
  int i,nbands,nrows,ncols,npixels;

  if (VPixelRepn(src) != VBitRepn) 
    VError("Input image must be of type VBit");

  nbands  = VImageNBands(src);
  nrows   = VImageNRows(src);
  ncols   = VImageNColumns(src);
  npixels = nbands * nrows * ncols;

  float_image = VChamferDist3d(src,NULL,VFloatRepn);
  if (! float_image) 
    VError("VDTDilate failed.\n");

  dest = VSelectDestImage("VDTDilate",dest,nbands,nrows,ncols,VBitRepn);
  if (! dest) return NULL;

  float_pp  = (VFloat *) VPixelPtr(float_image,0,0,0);
  bin_pp    = (VBit *) VPixelPtr(dest,0,0,0);
  for (i=0; i<npixels; i++)
    *bin_pp++ = ((*float_pp++ > radius) ? 0 : 1);

  VDestroyImage(float_image);

  VCopyImageAttrs (src,dest);
  return dest;
}
Beispiel #2
0
VImage VCombineBands (int nels, VImage src_images[], VBand src_bands[],
		      VImage dest)
{
  int n, i;
  VImage result, src = src_images[0];

  /* Count the number of bands needed in the destination image: */
  for (i = n = 0; i < nels; i++)
    n += (src_bands[i] == VAllBands) ? VImageNBands (src_images[i]) : 1;

  /* Check or allocate the destination image: */
  result = VSelectDestImage ("VCombineBands", dest, n,
			     VImageNRows (src), VImageNColumns (src), 
			     VPixelRepn (src));
  if (! result)
    return NULL;

  /* Copy each source band into the destination image: */
  for (i = n = 0; i < nels; i++) {
    if (! VCopyBand (src_images[i], src_bands[i], result, n)) {
      if (result != dest)
	VDestroyImage (result);
      return NULL;
    }
    n += (src_bands[i] == VAllBands) ? VImageNBands (src_images[i]) : 1;
  }
  return result;
}
Beispiel #3
0
int main(int argc, char **argv) {
    static VString filename = "";
    static VLong neighb = 2;
    static VLong iter = 1;
    static VOptionDescRec options[] = {
        {
            "n", VLongRepn, 1, &neighb, VOptionalOpt, TYPDict,
            "type of neighbourhood used for smoothing"
        },
        {
            "iter", VLongRepn, 1, &iter, VOptionalOpt, NULL,
            "number of iterations"
        },
        {
            "image", VStringRepn, 1, &filename, VOptionalOpt, NULL,
            "grey value image"
        },
    };
    FILE *in_file, *out_file, *fp;
    VAttrList list, list1;
    VImage src = NULL, dest, image = NULL;
    VAttrListPosn posn;
    /* Parse command line arguments: */
    VParseFilterCmd(VNumber(options), options, argc, argv, &in_file, &out_file);
    /* Read transformation image: */
    fp = VOpenInputFile(filename, TRUE);
    list1 = VReadFile(fp, NULL);
    if(! list1)
        VError("Error reading image");
    fclose(fp);
    for(VFirstAttr(list1, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & image);
        if(VPixelRepn(image) != VUByteRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & image);
        break;
    }
    if(image == NULL)
        VError(" image not found");
    /* Read source image(s): */
    if(!(list = VReadFile(in_file, NULL)))
        exit(1);
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & src);
        dest = VTopSmoothImage3d(src, image, NULL, neighb, iter);
        if(dest == NULL)
            exit(1);
        VSetAttrValue(& posn, NULL, VImageRepn, dest);
        VDestroyImage(src);
    }
    /* Write the results to the output file: */
    if(VWriteFile(out_file, list))
        fprintf(stderr, "%s: done.\n", argv[0]);
    return 0;
}
Beispiel #4
0
CVImage::~CVImage()
{
	for( std::list<VImage>::iterator it = images.begin(); it != images.end(); it++ ) {
		assert( refCnt[*it] > 0 );

		if( refCnt[*it] == 1 )VDestroyImage( *it );
		else refCnt[*it]--;
	}
}
Beispiel #5
0
void
VReleaseStorage(VAttrList list) {
    VImage src;
    VAttrListPosn posn;
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & src);
        VDestroyImage(src);
        src = NULL;
    }
}
Beispiel #6
0
void FunctionalResize (VImage& Image, int Bands, int Rows, int Columns)
{
   VImage zero;   /* empty image */


   /* resize image */
   zero = VCreateImage (Bands, Rows, Columns, VShortRepn);
   VImageAttrList (zero) = VCopyAttrList (VImageAttrList (Image));
   VFillImage (zero, VAllBands, 0);
   VDestroyImage (Image);
   Image = zero;

} /* FunctionalResize */
Beispiel #7
0
int 
main (int argc,char *argv[])
{
  static VShort first = 0;
  static VShort last = -1;
  static VOptionDescRec options[] = {
    { "first", VShortRepn, 1, (VPointer) & first,
      VOptionalOpt, NULL, "First slice" },
    { "last", VShortRepn, 1, (VPointer) & last,
      VOptionalOpt, NULL, "Last slice " }
  };

  FILE *in_file, *out_file;
  VAttrList list;
  VAttrListPosn posn;
  VImage src=NULL, result=NULL;
  char prg[50];	
  sprintf(prg,"vselbands V%s", getVersion());
  fprintf (stderr, "%s\n", prg);

  /* Parse command line arguments and identify files: */
  VParseFilterCmd (VNumber (options), options, argc, argv,& in_file, & out_file);


  /* Read the input file: */
  list = VReadFile (in_file, NULL);
  if (! list) exit (1);


  /* process */
  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {

    if (VGetAttrRepn (& posn) != VImageRepn) continue;
    VGetAttrValue (& posn, NULL, VImageRepn, & src);
    result = VSelSlices (src, NULL,first,last);
    if (! result) exit (1);
    VSetAttrValue (& posn, NULL, VImageRepn, result);
    VDestroyImage (src);
  }


  /* Write out the results: */
  VHistory(VNumber(options),options,prg,&list,&list);
  if (! VWriteFile (out_file, list)) exit (1);
  fprintf (stderr, "%s: done.\n", argv[0]);
  return 0;
}
Beispiel #8
0
int main(int argc, char *argv[]) {
    static VBoolean x_axis = FALSE;
    static VBoolean y_axis = FALSE;
    static VBoolean z_axis = FALSE;
    static VOptionDescRec options[] = {
        { "x", VBooleanRepn, 1, (VPointer) &x_axis, VOptionalOpt, NULL, "Flip x-axis" },
        { "y", VBooleanRepn, 1, (VPointer) &y_axis, VOptionalOpt, NULL, "Flip y-axis" },
        { "z", VBooleanRepn, 1, (VPointer) &z_axis, VOptionalOpt, NULL, "Flip z-axis" },
    };
    FILE *in_file, *out_file;
    VAttrList list;
    VAttrListPosn posn;
    VImage src = NULL, result = NULL;
	char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vflip3d V%s", ver);
	fprintf(stderr, "%s\n", prg_name);
	VWarning("It is recommended to use the program vswapdim since vflip3d does not support extended header informations");
    /* Parse command line arguments and identify files: */
    VParseFilterCmd(VNumber(options), options, argc, argv, &in_file, &out_file);
    /* Read the input file: */
    list = VReadFile(in_file, NULL);
    if(! list)
        exit(1);
    /* For each attribute read... */
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & src);
        result = Flip3dImage(src, NULL, VAllBands, x_axis, y_axis, z_axis);
        if(! result)
            exit(1);
        VSetAttrValue(& posn, NULL, VImageRepn, result);
        VDestroyImage(src);
    }
    /* Write out the results: */
    if(! VWriteFile(out_file, list))
        exit(1);
    fprintf(stderr, "%s: done.\n", argv[0]);
    return 0;
}
Beispiel #9
0
int main (int argc,char *argv[])
{
  FILE *in_file, *out_file;
  VAttrList list;
  VAttrListPosn posn;
  VImage src=NULL, dest=NULL;
  char prg[50];	
  sprintf(prg,"vthin3d V%s", getVersion());
  fprintf (stderr, "%s\n", prg);
  
  /* Parse command line arguments and identify files: */
  VParseFilterCmd (0,NULL, argc, argv, & in_file, & out_file);
  
  /* Read the input file: */
  list = VReadFile (in_file, NULL);
  if (! list) exit (1);
  fclose(in_file);
  

  /* For each attribute read... */
  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {

    if (VGetAttrRepn (& posn) != VImageRepn) continue;
    VGetAttrValue (& posn, NULL, VImageRepn, & src);
    if (VPixelRepn(src) != VBitRepn) continue;

    dest = VThin3d(src, NULL,(int)26);
    if (! dest) exit (1);

    VSetAttrValue (& posn, NULL, VImageRepn, dest);
    VDestroyImage (src);
  }
  

  /* output */
  VHistory(0,NULL,prg,&list,&list);
  if (! VWriteFile (out_file, list)) exit (1);  
  fprintf (stderr, "%s: done.\n", argv[0]);
  return 0;
}
Beispiel #10
0
VImage VCombineBandsVa (VImage dest, ...)
{
  va_list args;
  VImage src, result;
  int nbands;
  VBand src_band, dest_band;

  /* Count the number of bands to be combined: */
  va_start (args, dest);
  for (nbands = 0; (src = va_arg (args, VImage)) != 0; nbands +=
	 (va_arg (args, VBand) == VAllBands) ? VImageNBands (src) : 1) ;
  va_end (args);

  /* Check or allocate the destination image: */
  va_start (args, dest);
  src = va_arg (args, VImage);
  va_end (args);
  result = VSelectDestImage ("VCombineBandsVa", dest, nbands,
			     VImageNRows (src), VImageNColumns (src),
			     VPixelRepn (src));
  if (! result)
    return NULL;

  /* Copy each source band into the destination image: */
  va_start (args, dest);
  for (dest_band = 0; (src = va_arg (args, VImage)) != 0; ) {
    src_band = va_arg (args, VBand);
    if (! VCopyBand (src, src_band, result, dest_band)) {
      if (result != dest)
	VDestroyImage (result);
      return NULL;
    }
    dest_band += (src_band == VAllBands) ? VImageNBands (src) : 1;
  }
  va_end (args);
  return result;
}
Beispiel #11
0
/*!
  \fn VImage VDTClose(VImage src,VImage dest,VDouble radius)
  \brief 3D morphological closing (dilation+erosion)
  \param src   input image (bit repn)
  \param dest  output image (bit repn)
  \param radius radius of the spherical structural element
*/
VImage
VDTClose(VImage src,VImage dest,VDouble radius)
{
  VImage float_image=NULL,tmp=NULL;
  VBit *bin_pp;
  VFloat *float_pp;
  int i,nbands,nrows,ncols,npixels,b,r,c;
  int border = 7;

  border = (int) (radius - 1);

  if (VPixelRepn(src) != VBitRepn) 
    VError("Input image must be of type VBit");

  nbands  = VImageNBands(src) + 2*border;
  nrows   = VImageNRows(src) + 2*border;
  ncols   = VImageNColumns(src) + 2*border;
  npixels = nbands * nrows * ncols;

  tmp = VCreateImage(nbands,nrows,ncols,VBitRepn);

  for (b=border; b<nbands-border; b++) {
    for (r=border; r<nrows-border; r++) {
      for (c=border; c<ncols-border; c++) {
	VPixel(tmp,b,r,c,VBit) = VPixel(src,b-border,r-border,c-border,VBit);
      }
    }
  }

  float_image = VChamferDist3d(tmp,NULL,VFloatRepn);
  if (! float_image) 
    VError("VDTClose failed.\n");

  float_pp  = (VFloat *) VPixelPtr(float_image,0,0,0);
  bin_pp    = (VBit *) VPixelPtr(tmp,0,0,0);
  for (i=0; i<npixels; i++)
    *bin_pp++ = ((*float_pp++ > radius) ? 1 : 0);

  float_image = VChamferDist3d(tmp,float_image,VFloatRepn);
  if (! float_image) 
    VError("VDTClose failed.\n");

  float_pp = (VFloat *) VPixelPtr(float_image,0,0,0);
  bin_pp   = (VBit *) VPixelPtr(tmp,0,0,0);
  for (i=0; i<npixels; i++)
    *bin_pp++ = ((*float_pp++ > radius) ? 1 : 0);

  VDestroyImage(float_image);


  dest = VSelectDestImage("VDTClose",dest,VImageNBands(src),VImageNRows(src),VImageNColumns(src),
			  VBitRepn);
			  
  if (! dest) return NULL;

  for (b=border; b<nbands-border; b++) {
    for (r=border; r<nrows-border; r++) {
      for (c=border; c<ncols-border; c++) {
	VPixel(dest,b-border,r-border,c-border,VBit) = VPixel(tmp,b,r,c,VBit);
      }
    }
  }
  VDestroyImage(tmp);

  VCopyImageAttrs (src, dest);
  return dest;
}
Beispiel #12
0
/*!
\fn VImage VSkel3d (VImage src,VImage dest)
\param src   input image (bit repn)
\param dest  output image (bit repn)
*/
VImage
VSkel3d(VImage src,VImage dest)
{
  int b,r,c,nbands,nrows,ncols,npixels;
  int ndel=0;
  VBit *tmp_pp,*dst_pp;
  VImage tmp=NULL,dt=NULL;
  int i,j,n,n0,n1,mdel;

  float depth,maxdepth,step=0.5;
  VPoint *array;
  VBit *src_pp,*dest_pp;


  nrows  = VImageNRows (src);
  ncols  = VImageNColumns (src);
  nbands = VImageNBands (src);
  npixels = nbands*nrows*ncols;

  dest = VCopyImage(src,dest,VAllBands);
  VFillImage(dest,VAllBands,0);
  tmp = VCreateImage(nbands,nrows,ncols,VBitRepn);
  VFillImage(tmp,VAllBands,0);

  for (b=2; b<nbands-2; b++) {
    for (r=2; r<nrows-2; r++) {
      for (c=2; c<ncols-2; c++) {
	VPixel(dest,b,r,c,VBit) = VPixel(src,b,r,c,VBit);
      }
    }
  }

  /*
  ** generate masks
  */
  GenerateMaps();


  /*
  ** sort foreground voxels by depth
  */
  src_pp  = (VBit *) VPixelPtr(src, 0, 0, 0);
  dest_pp = (VBit *) VPixelPtr(dest, 0, 0, 0);
  n = 0;
  for (i=0; i<npixels; i++) {
    if (*src_pp > 0) n++;
    *src_pp = (*src_pp > 0) ? 0 : 1;
    src_pp++;
  }

  dt = VChamferDist3d(src,NULL,VFloatRepn);

  src_pp  = (VBit *) VPixelPtr(src, 0, 0, 0);
  for (i=0; i<npixels; i++) {
    *src_pp = (*src_pp > 0) ? 0 : 1;
    src_pp++;
  }

  array = (VPoint *) VMalloc(sizeof(VPoint) * (n+1));

  array[0].b = 0;
  array[0].r = 0;
  array[0].c = 0;
  array[0].val = 0;

  n = 1;
  for (b=0; b<nbands; b++) {
    for (r=0; r<nrows; r++) {
      for (c=0; c<ncols; c++) {
        if (VPixel(dt, b, r, c,VFloat) > 0.1) {
          array[n].b = b;
          array[n].r = r;
          array[n].c = c;
          array[n].val = VPixel(dt,b,r,c,VFloat);
          n++;
        }
      }
    }
  }
  VDestroyImage(dt);
  VPoint_hpsort((n-1),array);


  /*
  ** now start deleting voxels
  */  
  maxdepth = array[n-1].val;
  fprintf(stderr," maxdepth= %f\n",maxdepth);

  mdel = 0;
  for (depth=0; depth <= maxdepth; depth += step) {

    fprintf(stderr,"   depth= %7.2f\r",depth); fflush(stderr);

    n0 = 1;
    for (j=n-1; j>=1; j--) {
      if (array[j].val < depth-2.0*step) {
        n0 = j;
        break;
      }
    }

    n1 = n;
    for (j=1; j<=n; j++) {
      if (array[j].val > depth) {
        n1 = j-1;
        break;
      }
    }

    /*
    ** delete all deletable voxels within this depth level
    */
    ndel = 1;
    while (ndel > 0) {
      ndel = 0;

      VFillImage(tmp,VAllBands,0);

      for (j=n0; j<=n1; j++) {

	if (array[j].val > depth) continue;

	b = array[j].b;
	r = array[j].r;
	c = array[j].c;
	if (b < 2 || b >= nbands-2) continue;
	if (r < 2 || r >= nrows-2) continue;
	if (c < 2 || c >= ncols-2) continue;


	if (VPixel(dest,b,r,c,VBit) == 0) continue;
	if (Border_3d(dest,b,r,c) == FALSE) continue;

	if (Beta1_3d(dest,b,r,c) == FALSE) continue;
	if (Beta0_3d(dest,b,r,c) == FALSE) continue;

	/* alpha conditions */
	if (Alpha_3d(dest,alpha0_pos,alpha0_neg,b,r,c) == FALSE &&
	    Alpha_3d(dest,alpha1_pos,alpha1_neg,b,r,c) == FALSE &&
	    Alpha_3d(dest,alpha2_pos,alpha2_neg,b,r,c) == FALSE) continue;

	/* mark for deletion */
	VPixel(tmp,b,r,c,VBit) = 1; 
	ndel++;
      }
    
      /* perform parallel deletion */
      tmp_pp = (VBit *) VPixelPtr(tmp,0,0,0);
      dst_pp = (VBit *) VPixelPtr(dest,0,0,0);

      for (i=0; i<npixels; i++) {
	if (*tmp_pp == 1) *dst_pp = 0;
	tmp_pp++;
	dst_pp++;
      }
    }
  }

  VDestroyImage(tmp);
  return dest;
}
Beispiel #13
0
/*
** general linear regression
*/
VAttrList
VRegression(ListInfo *linfo, int nlists, VShort minval, VImage design, VFloat sigma, VLong itr) {
    VAttrList out_list;
    VImageInfo *xinfo;
    int nbands = 0, nslices = 0, nrows = 0, ncols = 0, slice, row, col, nr, nc;
    VImage src[NSLICES], res_image = NULL;
    VImage beta_image[MBETA], BCOV = NULL, KX_image = NULL;
    VImage res_map[ETMP];
    float  smooth_fwhm = 0, vx = 0, vy = 0, vz = 0;
    VFloat *float_pp, df;
    VRepnKind repn;
    float d, err;
    int   i, k, l, n, m = 0, nt, fd = 0, npix = 0;
    int   i0 = 0, i1 = 0;
    double u, sig, trace = 0, trace2 = 0, var = 0, sum = 0, nx = 0, mean = 0, sum2;
    float *ptr1, *ptr2;
    double x;
    gsl_matrix_float *X = NULL, *XInv = NULL, *SX = NULL;
    gsl_vector_float *y, *z, *beta, *ys;
    gsl_vector *kernel;
    gsl_matrix_float *S = NULL, *Vc = NULL, *F = NULL, *P = NULL, *Q = NULL;
    gsl_matrix_float *R = NULL, *RV = NULL;
    VBoolean smooth = TRUE;  /* no smoothness estimation */
    gsl_set_error_handler_off();
    /*
    ** read input data
    */
    nslices = nbands = nrows = ncols = 0;
    for(k = 0; k < nlists; k++) {
        n  = linfo[k].nslices;
        nr = linfo[k].nrows;
        nc = linfo[k].ncols;
        nt = linfo[k].ntimesteps;
        nbands += nt;
        if(nslices == 0)
            nslices = n;
        else if(nslices != n)
            VError(" inconsistent image dimensions, slices: %d %d", n, nslices);
        if(nrows == 0)
            nrows = nr;
        else if(nrows != nr)
            VError(" inconsistent image dimensions, rows: %d %d", nr, nrows);
        if(ncols == 0)
            ncols = nc;
        else if(ncols != nc)
            VError(" inconsistent image dimensions, cols: %d %d", nc, ncols);
    }
    fprintf(stderr, " num images: %d,  image dimensions: %d x %d x %d\n",
            nlists, nslices, nrows, ncols);
    /*
    ** get design dimensions
    */
    m = VImageNRows(design);      /* number of timesteps   */
    n = VImageNColumns(design);   /* number of covariates */
    fprintf(stderr, " ntimesteps=%d,   num covariates=%d\n", m, n);
    if(n >= MBETA)
        VError(" too many covariates (%d), max is %d", n, MBETA);
    if(m != nbands)
        VError(" design dimension inconsistency: %d %d", m, nbands);
    fprintf(stderr, " working...\n");
    /*
    ** read design matrix
    */
    X = gsl_matrix_float_alloc(m, n);
    for(k = 0; k < m; k++) {
        for(l = 0; l < n; l++) {
            x = VGetPixel(design, 0, k, l);
            fmset(X, k, l, (float)x);
        }
    }
    /*
    ** pre-coloring, set up K-matrix, S=K, V = K*K^T with K=S
    */
    S  = gsl_matrix_float_alloc(m, m);
    GaussMatrix((double)sigma, S);
    Vc = fmat_x_matT(S, S, NULL);
    /*
    ** compute pseudoinverse
    */
    SX = fmat_x_mat(S, X, NULL);
    XInv = fmat_PseudoInv(SX, NULL);
    /*
    ** get variance estimate
    */
    Q = fmat_x_mat(XInv, Vc, Q);
    F = fmat_x_matT(Q, XInv, F);
    BCOV = VCreateImage(1, n, n, VFloatRepn);
    float_pp = VImageData(BCOV);
    ptr1 = F->data;
    for(i = 0; i < n * n; i++)
        *float_pp++ = *ptr1++;
    gsl_matrix_float_free(Q);
    gsl_matrix_float_free(F);
    /*
    ** get effective degrees of freedom
    */
    R  = gsl_matrix_float_alloc(m, m);
    P = fmat_x_mat(SX, XInv, P);
    gsl_matrix_float_set_identity(R);
    gsl_matrix_float_sub(R, P);
    RV = fmat_x_mat(R, Vc, NULL);
    trace = 0;
    for(i = 0; i < m; i++)
        trace += fmget(RV, i, i);
    P = fmat_x_mat(RV, RV, P);
    trace2 = 0;
    for(i = 0; i < m; i++)
        trace2 += fmget(P, i, i);
    df = (trace * trace) / trace2;
    fprintf(stderr, " df= %.3f\n", df);
    /*
    ** create output images
    */
    xinfo = linfo[0].info;
    out_list = VCreateAttrList();
    res_image = VCreateImage(nslices, nrows, ncols, VFloatRepn);
    VFillImage(res_image, VAllBands, 0);
    VSetAttr(VImageAttrList(res_image), "name", NULL, VStringRepn, "RES/trRV");
    VSetAttr(VImageAttrList(res_image), "modality", NULL, VStringRepn, "RES/trRV");
    VSetAttr(VImageAttrList(res_image), "df", NULL, VFloatRepn, df);
    VSetAttr(VImageAttrList(res_image), "patient", NULL, VStringRepn, xinfo->patient);
    VSetAttr(VImageAttrList(res_image), "voxel", NULL, VStringRepn, xinfo->voxel);
    VSetAttr(VImageAttrList(res_image), "repetition_time", NULL, VLongRepn, itr);
    VSetAttr(VImageAttrList(res_image), "talairach", NULL, VStringRepn, xinfo->talairach);

    /* neu */
    VSetAttr(VImageAttrList(res_image),"indexOrigin",NULL,VStringRepn,xinfo->indexOrigin);
    VSetAttr(VImageAttrList(res_image),"columnVec",NULL,VStringRepn,xinfo->columnVec);
    VSetAttr(VImageAttrList(res_image),"rowVec",NULL,VStringRepn,xinfo->rowVec);
    VSetAttr(VImageAttrList(res_image),"sliceVec",NULL,VStringRepn,xinfo->sliceVec);
    VSetAttr(VImageAttrList(res_image),"FOV",NULL,VStringRepn,xinfo->FOV);
    /*--------*/

    if(xinfo->fixpoint[0] != 'N')
        VSetAttr(VImageAttrList(res_image), "fixpoint", NULL, VStringRepn, xinfo->fixpoint);
    if(xinfo->ca[0] != 'N') {
        VSetAttr(VImageAttrList(res_image), "ca", NULL, VStringRepn, xinfo->ca);
        VSetAttr(VImageAttrList(res_image), "cp", NULL, VStringRepn, xinfo->cp);
        VSetAttr(VImageAttrList(res_image), "extent", NULL, VStringRepn, xinfo->extent);
    }
    VAppendAttr(out_list, "image", NULL, VImageRepn, res_image);
    for(i = 0; i < n; i++) {
        beta_image[i] = VCreateImage(nslices, nrows, ncols, VFloatRepn);
        VFillImage(beta_image[i], VAllBands, 0);
        VSetAttr(VImageAttrList(beta_image[i]), "patient", NULL, VStringRepn, xinfo->patient);
        VSetAttr(VImageAttrList(beta_image[i]), "voxel", NULL, VStringRepn, xinfo->voxel);
        VSetAttr(VImageAttrList(beta_image[i]), "repetition_time", NULL, VLongRepn, itr);
        VSetAttr(VImageAttrList(beta_image[i]), "talairach", NULL, VStringRepn, xinfo->talairach);

	/* neu */
	VSetAttr(VImageAttrList(beta_image[i]),"indexOrigin",NULL,VStringRepn,xinfo->indexOrigin);
	VSetAttr(VImageAttrList(beta_image[i]),"columnVec",NULL,VStringRepn,xinfo->columnVec);
	VSetAttr(VImageAttrList(beta_image[i]),"rowVec",NULL,VStringRepn,xinfo->rowVec);
	VSetAttr(VImageAttrList(beta_image[i]),"sliceVec",NULL,VStringRepn,xinfo->sliceVec);
	VSetAttr(VImageAttrList(beta_image[i]),"FOV",NULL,VStringRepn,xinfo->FOV);
	/*--------*/


        if(xinfo->fixpoint[0] != 'N')
            VSetAttr(VImageAttrList(beta_image[i]), "fixpoint", NULL, VStringRepn, xinfo->fixpoint);
        if(xinfo->ca[0] != 'N') {
            VSetAttr(VImageAttrList(beta_image[i]), "ca", NULL, VStringRepn, xinfo->ca);
            VSetAttr(VImageAttrList(beta_image[i]), "cp", NULL, VStringRepn, xinfo->cp);
            VSetAttr(VImageAttrList(beta_image[i]), "extent", NULL, VStringRepn, xinfo->extent);
        }
        VSetAttr(VImageAttrList(beta_image[i]), "name", NULL, VStringRepn, "BETA");
        VSetAttr(VImageAttrList(beta_image[i]), "modality", NULL, VStringRepn, "BETA");
        VSetAttr(VImageAttrList(beta_image[i]), "beta", NULL, VShortRepn, i + 1);
        VSetAttr(VImageAttrList(beta_image[i]), "df", NULL, VFloatRepn, df);
        VAppendAttr(out_list, "image", NULL, VImageRepn, beta_image[i]);
    }
    VSetAttr(VImageAttrList(design), "name", NULL, VStringRepn, "X");
    VSetAttr(VImageAttrList(design), "modality", NULL, VStringRepn, "X");
    VAppendAttr(out_list, "image", NULL, VImageRepn, design);
    KX_image = Mat2Vista(SX);
    VSetAttr(VImageAttrList(KX_image), "name", NULL, VStringRepn, "KX");
    VSetAttr(VImageAttrList(KX_image), "modality", NULL, VStringRepn, "KX");
    VAppendAttr(out_list, "image", NULL, VImageRepn, KX_image);
    VSetAttr(VImageAttrList(BCOV), "name", NULL, VStringRepn, "BCOV");
    VSetAttr(VImageAttrList(BCOV), "modality", NULL, VStringRepn, "BCOV");
    VAppendAttr(out_list, "image", NULL, VImageRepn, BCOV);
    /*
    ** create temporary images for smoothness estimation
    */
    /* smoothness estim only for 3D images, i.e. CA/CP known */
/*    if(xinfo->ca[0] == 'N')
        smooth = FALSE;*/
    if(smooth) {
        i0 = 20;
        i1 = i0 + 30;
        if(i1 > m)
            i1 = m;
        for(i = i0; i < i1; i++) {
            if(i - i0 >= ETMP)
                VError(" too many tmp images");
            res_map[i - i0] = VCreateImage(nslices, nrows, ncols, VFloatRepn);
            VFillImage(res_map[i - i0], VAllBands, 0);
        }
    }
    /*
    ** process
    */
    ys   = gsl_vector_float_alloc(m);
    y    = gsl_vector_float_alloc(m);
    z    = gsl_vector_float_alloc(m);
    beta = gsl_vector_float_alloc(n);
    kernel = GaussKernel((double)sigma);
    for(k = 0; k < nlists; k++) {
        src[k] = VCreateImage(linfo[k].ntimesteps, nrows, ncols, linfo[k].repn);
        VFillImage(src[k], VAllBands, 0);
    }
    npix = 0;
    for(slice = 0; slice < nslices; slice++) {
        if(slice % 5 == 0)
            fprintf(stderr, " slice: %3d\r", slice);
        for(k = 0; k < nlists; k++) {
            if(linfo[k].zero[slice] == 0)
                goto next1;
            fd = open(linfo[k].filename, O_RDONLY);
            if(fd == -1)
                VError("could not open file %s", linfo[k].filename);
            nt = linfo[k].ntimesteps;
            if(! VReadBandDataFD(fd, &linfo[k].info[slice], 0, nt, &src[k]))
                VError(" error reading data");
            close(fd);
        }
        repn = linfo[0].repn;
        for(row = 0; row < nrows; row++) {
            for(col = 0; col < ncols; col++) {
                for(k = 0; k < nlists; k++)
                    if(VPixel(src[k], 0, row, col, VShort) < minval + 1)
                        goto next;
                npix++;
                /* read time series data */
                sum = sum2 = nx = 0;
                ptr1 = y->data;
                for(k = 0; k < nlists; k++) {
                    nt  = VImageNBands(src[k]);
                    for(i = 0; i < nt; i++) {
                        u = VPixel(src[k], i, row, col, VShort);
                        (*ptr1++) = u;
                        sum  += u;
                        sum2 += u * u;
                        nx++;
                    }
                }
                mean = sum / nx;
                sig = sqrt((double)((sum2 - nx * mean * mean) / (nx - 1.0)));
                if(sig < 0.001)
                    continue;
                /* centering and scaling, Seber, p.330 */
                ptr1 = y->data;
                for(i = 0; i < m; i++) {
                    u = ((*ptr1) - mean) / sig;
                    (*ptr1++) = u + 100.0;
                }
                /* S x y */
                ys = VectorConvolve(y, ys, kernel);
                /* compute beta's */
                fmat_x_vector(XInv, ys, beta);
                /* residuals */
                fmat_x_vector(SX, beta, z);
                err = 0;
                ptr1 = ys->data;
                ptr2 = z->data;
                for(i = 0; i < m; i++) {
                    d = ((*ptr1++) - (*ptr2++));
                    err += d * d;
                }
                /* sigma^2 */
                var = err / trace;
                /* write residuals output */
                VPixel(res_image, slice, row, col, VFloat) = (VFloat)var;
                /* save residuals of several timesteps for smoothness estimation */
                if(smooth) {
                    ptr1 = ys->data;
                    ptr2 = z->data;
                    err = 0;
                    for(i = i0; i < i1; i++) {
                        d = ((*ptr1++) - (*ptr2++));
                        err += d * d;
                        VPixel(res_map[i - i0], slice, row, col, VFloat) = d;
                    }
                    if (err > 0) err = sqrt(err); 
                    for(i = i0; i < i1; i++) {
                        d = VPixel(res_map[i - i0], slice, row, col, VFloat);
						if (err > 1.0e-6) d /= err;
						else d = 0; 
                        VPixel(res_map[i - i0], slice, row, col, VFloat) = d / err;
                    }
                }
                /* write beta output */
                ptr1 = beta->data;
                for(i = 0; i < n; i++)
                    VPixel(beta_image[i], slice, row, col, VFloat) = (VFloat)(*ptr1++);
next:
                ;
            }
        }
next1:
        ;
    }
    /*
    ** Smoothness estimation based on residual images
    */
    if(smooth) {
        smooth_fwhm = VSmoothnessEstim(res_map, i1 - i0);
        sscanf(xinfo->voxel, "%f %f %f", &vx, &vy, &vz);
        vx = (vx + vy + vz) / 3.0;    /* voxels should be isotropic */
        smooth_fwhm *= vx;
        fprintf(stderr, " smoothness: %f\n", smooth_fwhm);
        VSetAttr(VImageAttrList(res_image), "smoothness", NULL, VFloatRepn, smooth_fwhm);
        for(i = 0; i < n; i++) {
            VSetAttr(VImageAttrList(beta_image[i]), "smoothness", NULL, VFloatRepn, smooth_fwhm);
        }
        for(i = 0; i < i1 - i0; i++)
            VDestroyImage(res_map[i]);
    }
ende:
    if(npix == 0)
        VError(" no voxels above threshold %d found", minval);
    return out_list;
}
Beispiel #14
0
/*!
\fn VImage VCDT3d (VImage src,VImage dest, VLong inside,VLong outside,VLong obstacle,VRepnKind repn)
\param src      input image (VUByte)
\param dest     output image (VFloat)
\param inside   ubyte value representing inside voxels
\param outside  ubyte value representing outside voxels
\param obstacle ubyte value representing obstacle voxels
\param repn     output pixel repn (VShortRepn or VFloatRepn)
*/
VImage 
VCDT3d (VImage src,VImage dest,
	VLong inside,VLong outside,VLong obstacle,VRepnKind repn)
{
  int nbands,nrows,ncols,b,r,c;
  int i,n_new,n_old,iter,npixels;
  VFloat d1,d2,d3;
  VFloat u,x,y;
  VUByte *src_pp;
  VFloat *dest_pp,inf;
  VShort *short_pp;
  VImage result=NULL;


  if (repn != VShortRepn && repn != VFloatRepn)
    VError(" VCDT3d: illegal output pixel repn: %d,  short= %d, float= %d",
	   repn,VShortRepn,VFloatRepn);

  /* Check the input image */
  if (VPixelRepn(src) != VUByteRepn) 
    VError("VCDT3d: input image must be of type VUByte");

  
  nbands = VImageNBands(src);
  nrows  = VImageNRows (src);
  ncols  = VImageNColumns (src);
  npixels = nbands * nrows * ncols;

  dest = VSelectDestImage("VCDT3d",dest,nbands,nrows,ncols,VFloatRepn);
  VFillImage(dest,VAllBands,0);
  inf = VPixelMaxValue(dest) - 2;

  dest_pp = (VFloat *) VPixelPtr(dest,0,0,0);
  src_pp = (VUByte *) VPixelPtr(src,0,0,0);
  npixels = nbands * nrows * ncols;
  for (i=0; i<npixels; i++) {
    x = *src_pp++;
    if (x == (VFloat) inside)
      y = inf;
    else if (x == (VFloat) outside)
      y = 0;
    else
      y = -100.0;
    *dest_pp++ = y;
  }

 
  /* optimal chamfer distances (Borgefors,1984, p. 334) */
  d1 = 1.0;
  d2 = 1.314;
  d3 = 1.628;

  /* optimal distances (see Beckers, Smeulders, 1992). */

  d1 = 0.88750;
  d2 = 1.34224;
  d3 = 1.59772;

  /* optimal distances (see Verwer, 1991). */
/*
  d1 = 0.894;
  d2 = 1.3409;
  d3 = 1.5879;
  */

  /* optimal distances (see Kiryati, 1993). */
  /*
  d1 = 0.9016;
  d2 = 1.289;
  d3 = 1.615;
  */

  iter = 0;
  n_old = 1;
  n_new = 0;
  while (n_old != n_new && iter < 6) {

    /* forward scan */

    for (b=1; b<nbands; b++) {
      for (r=1; r<nrows-1; r++) {
	for (c=1; c<ncols-1; c++) {

	  if (VPixel(src,b,r,c,VUByte) != inside) continue;

	  u = VPixel(dest,b,r,c,VFloat);

	  x = VPixel(dest,b-1,r-1,c-1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r-1,c,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r-1,c+1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r,c-1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r,c,VFloat) + d1;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r,c+1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r+1,c-1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r+1,c,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b-1,r+1,c+1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;


	  x = VPixel(dest,b,r-1,c-1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b,r-1,c,VFloat) + d1;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b,r-1,c+1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b,r,c-1,VFloat) + d1;
	  if (x < u && x >= 0) u = x;

	  if (u >= 0)
	    VPixel(dest,b,r,c,VFloat) = u;
	}
      }
    }

    /* backward scan */

    for (b=nbands-2; b>=0; b--) {
      for (r=nrows-2; r>=1; r--) {
	for (c=ncols-2; c>=1; c--) {

	  if (VPixel(src,b,r,c,VUByte) != inside) continue;

	  u = VPixel(dest,b,r,c,VFloat);
	
	  x = VPixel(dest,b,r,c+1,VFloat) + d1;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b,r+1,c-1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b,r+1,c,VFloat) + d1;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b,r+1,c+1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;
	

	  x = VPixel(dest,b+1,r-1,c-1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b+1,r-1,c,VFloat) + d2;
	  if (x < u && x >= 0) u = x;
	
	  x = VPixel(dest,b+1,r-1,c+1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;


	  x = VPixel(dest,b+1,r,c-1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b+1,r,c,VFloat) + d1;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b+1,r,c+1,VFloat) + d2;
	  if (x < u && x >= 0) u = x;


	  x = VPixel(dest,b+1,r+1,c-1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b+1,r+1,c,VFloat) + d2;
	  if (x < u && x >= 0) u = x;

	  x = VPixel(dest,b+1,r+1,c+1,VFloat) + d3;
	  if (x < u && x >= 0) u = x;

	  if (u >= 0)
	    VPixel(dest,b,r,c,VFloat) = u;
	}
      }
    }

    dest_pp = (VFloat *) VPixelPtr(dest,0,0,0);
    n_old = n_new;
    n_new = 0;
    for (i=0; i<npixels; i++) {
      if (*dest_pp++ >= 9999) n_new++;
    }
    iter++;
  }

  dest_pp = (VFloat *) VPixelPtr(dest,0,0,0);
  for (i=0; i<npixels; i++) {
    if (*dest_pp >= 9999 || *dest_pp < 0) *dest_pp = 0;
    dest_pp++;
  }

  /* copy to a short image */
  if (repn == VShortRepn) {
    result = VCreateImage(nbands,nrows,ncols,VShortRepn);
    dest_pp = (VFloat *) VPixelPtr(dest,0,0,0);
    short_pp = (VShort *) VPixelPtr(result,0,0,0);
    for (i=0; i<npixels; i++) {
      *short_pp = VRint((float)(*dest_pp * 10.0f));
      dest_pp++;
      short_pp++;
    }
    VDestroyImage(dest);
    VCopyImageAttrs (src, result);
    return result;
  }
  else if (repn == VFloatRepn) {
    VCopyImageAttrs (src, dest);
    return dest;
  }
  return NULL;
}
Beispiel #15
0
/*!
\fn VImage VAniso2d(VImage src,VImage dest,VShort numiter,
           VShort type,VFloat kappa,VFloat alpha);
\param src  input image 
\param dest  output image
\param numiter number of iterations
\param type type of diffusion function (0 or 1)
\param kappa parameter for diffusion function
\param alpha parameter for diffusion function
*/
VImage 
VAniso2d(VImage src,VImage dest,VShort numiter,
	 VShort type,VFloat kappa,VFloat alpha)
{
  VImage tmp1=NULL,tmp2=NULL;
  int nbands,nrows,ncols;
  int b,r,c,iter;
  float delta;
  float dx,dy,dz,d,u,v;
  float ux1,ux2,uy1,uy2;
  float r1,r2,c1,c2;
  VDouble xmax,xmin;


  nbands = VImageNBands(src);
  nrows  = VImageNRows(src);
  ncols  = VImageNColumns(src);


  tmp1 = VCreateImage(1,nrows,ncols,VFloatRepn);
  tmp2 = VCreateImage(1,nrows,ncols,VFloatRepn);

  xmax = VPixelMaxValue (tmp1);
  xmin = VPixelMinValue (tmp1);

  dest = VCopyImage(src,dest,VAllBands);


  delta = 1.0 / 6.0;

  dz = 0;
  for (b=0; b<nbands; b++) {
    
    for (r=0; r<nrows; r++) {
      for (c=0; c<ncols; c++) {
	VPixel(tmp1,0,r,c,VFloat) = VGetPixel(src,b,r,c);
      }
    }


    for (iter=0; iter < numiter; iter++) {

      for (r=1; r<nrows-1; r++) {
	for (c=1; c<ncols-1; c++) {

	  u  = VPixel(tmp1,0,r,c,VFloat);

	  c1 = VPixel(tmp1,0,r,c+1,VFloat);
	  c2 = VPixel(tmp1,0,r,c-1,VFloat);

	  r1 = VPixel(tmp1,0,r+1,c,VFloat);
	  r2 = VPixel(tmp1,0,r-1,c,VFloat);

	  /* col-dir */
	  dx = c1-u;
	  dy = r1-r2;
	  d  = diffusion2d(dx,dy,type,kappa,alpha);
	  ux1 = d*(c1 - u);

	  dx = u-c2;
	  d  = diffusion2d(dx,dy,type,kappa,alpha);
	  ux2 = d*(u - c2);


	  /* row-dir */
	  dx = c1-c2;
	  dy = r1-u;
	  d  = diffusion2d(dx,dy,type,kappa,alpha);
	  uy1 = d*(r1 - u);

	  dy = u-r2;
	  d  = diffusion2d(dx,dy,type,kappa,alpha);
	  uy2 = d*(u - r2);


	  /* sum */
	  v = u + delta*(ux1 - ux2 + uy1 - uy2);

	  if (v > xmax) v = xmax;
	  if (v < xmin) v = xmin;
	  VPixel(tmp2,0,r,c,VFloat) = v;
	}
      }
      tmp1 = VCopyImagePixels(tmp2,tmp1,VAllBands);
    }
    
    /*
    ** output
    */
    for (r=1; r<nrows-1; r++) {
      for (c=1; c<ncols-1; c++) {
	v = VPixel(tmp2,0,r,c,VFloat);
	if (v > VPixelMaxValue (dest)) v = VPixelMaxValue (dest);
	if (v < VPixelMinValue (dest)) v = VPixelMinValue (dest);
	VSetPixel(dest,b,r,c,(VDouble) v);
      }
    }
  }

  VDestroyImage(tmp1);
  VDestroyImage(tmp2);

  return dest;
}
Beispiel #16
0
static VImage RotateImage (VImage src, VImage dest, VBand band, double angle)
{
  double shearx, sheary;
  int margin_nrows, margin_ncols;
  int src_nbands; /* src_repn, src_nrows, src_ncols; */
  VImage sx_image, sysx_image, sxsysx_image, cropped_image;
    
  /* Ensure that range of "angle" is valid: */
  if (angle <= -0.5 * M_PI || angle >= 0.5 * M_PI) {
    VWarning ("VRotateImage: Internal error in RotateImage");
    return NULL;
  }

  /* Determine "shearx" and "sheary": */
  shearx = - tan (angle / 2.0);
  sheary = sin (angle);
    
  /* Read properties of "src": */
  /*  src_nrows  = VImageNRows (src); */
  /*  src_ncols  = VImageNColumns (src); */
  /*  src_repn   = VPixelRepn (src); */
  src_nbands = VImageNBands (src);
    
  /* Check to ensure that "band" exists: */
  if (band != VAllBands && (band < 0 || band >= src_nbands)) {
    VWarning ("VRotateImage: Band %d referenced in image of %d bands",
	      band, VImageNBands (src));
    return NULL;
  }

  /* First shear in x direction: */
  sx_image = VShearImageX (src, NULL, band, shearx);
  if (sx_image == NULL)
    return NULL;

  /* Then shear in y direction: */
  sysx_image = VShearImageY (sx_image, NULL, VAllBands, sheary);
  if (sysx_image == NULL)
    return NULL;

  /* Finally, shear in x direction again: */
  sxsysx_image = VShearImageX (sysx_image, NULL, VAllBands, shearx);
  if (sxsysx_image == NULL)
    return NULL;

  /* Calculate margin (unwanted blank space) sizes: */
  margin_nrows = VImageNRows (src) * fabs (shearx) * fabs (sheary);
  margin_ncols =
    (VImageNRows (sysx_image) - VImageNRows (src)) * fabs (shearx);

  /* Remove margins: */
  cropped_image = VCropImage (sxsysx_image, dest, VAllBands,
			      margin_nrows, margin_ncols,
			      VImageNRows (sxsysx_image) -
			      2 * margin_nrows,
			      VImageNColumns (sxsysx_image) -
			      2 * margin_ncols);

  /* Clean up: */
  VDestroyImage (sx_image);
  VDestroyImage (sysx_image);
  VDestroyImage (sxsysx_image);

  VCopyImageAttrs (src, cropped_image);
    
  return cropped_image;
}
Beispiel #17
0
VImage VRotateImage (VImage src, VImage dest, VBand band, double angle)
{
#define Tolerance 0.01

  double angle_remained;
  VImage tmp1 = NULL, tmp2;

  /* Normalize angle to the range [-Pi, +Pi]: */
  angle = fmod (angle, 2.0 * M_PI);
  if (angle > M_PI)
    angle -= 2.0 * M_PI;

  /* 
   * Two stage rotation:
   * 1. Use flipping to rotate the image by a multiple of 90 degrees.
   * 2. Use RotateImage() to rotate the remaining angle.
   */
  if (angle >= -0.25 * M_PI && angle <= 0.25 * M_PI) {

    /* Do nothing: */
    angle_remained = angle;
    tmp2 = src;

  } else if (angle >= 0.25 * M_PI && angle <= 0.75 * M_PI) {

    /* Rotate by 90 degrees: */
    tmp1 = VTransposeImage (src, NULL, band);
    tmp2 = VFlipImage (tmp1, NULL, VAllBands, TRUE);
    angle_remained = angle - 0.5 * M_PI;

  } else if (angle >= 0.75 * M_PI || angle <= -0.75 * M_PI) {

    /* Rotate by 180 degrees: */
    tmp1 = VFlipImage (src, NULL, band, TRUE);
    tmp2 = VFlipImage (tmp1, NULL, VAllBands, FALSE);
    angle_remained = angle > 0.0 ? angle - M_PI : angle + M_PI;

  } else {

    /* Rotate by -90 degress: */
    tmp1 = VTransposeImage (src, NULL, band);
    tmp2 = VFlipImage (tmp1, NULL, VAllBands, FALSE);
    angle_remained = angle + 0.5 * M_PI;
  }

  if (VMax (angle_remained, -angle_remained) > Tolerance) {

    /* Go on to stage 2: */
    dest = RotateImage (tmp2, dest, tmp2 == src ? band : VAllBands, 
			angle_remained);

  } else {

    /* Stage 1 only is good enough: */
    dest = VCopyImage (tmp2, dest, tmp2 == src ? band : VAllBands);
  }
    
  /* Clean up: */
  if (tmp2 != src) {
    VDestroyImage (tmp1);
    VDestroyImage (tmp2);
  }
    
  return dest;
    
#undef Tolerance
}
Beispiel #18
0
VBoolean DemonMatch (VImage S, VImage M, VImage& Dx, VImage& Dy, VImage& Dz, VFloat Sigma, VLong Iter, VLong Scale, VBoolean Verbose)
{
   int Factor = 4;   /* scaling factor of iterations at each step */

   int scale;   /* scaling level       */
   int iter;    /* number of iteration */

   VImage *s, *m;                /* source and model pyramid   */
   VImage gsx, gsy, gsz,  gs2;   /* source gradient field      */
   VImage gmx, gmy, gmz,  gm2;   /* model gradient field       */
   VImage dsx, dsy, dsz;         /* source deformation field   */
   VImage dmx, dmy, dmz;         /* model deformation field    */
   VImage vx,  vy,  vz;          /* optical flow field         */
   VImage rx,  ry,  rz;          /* residual deformation field */

   int width = 2 * (2 * (int) floor (Sigma) + 1) + 1;   /* Lohmann, G. "Volumetric Image Analysis", p. 141, Teubner, 1998 */

   VImage tmp;   /* temporal storage */


   /* create multi-scale pyramids */
   s = (VImage*) malloc ((Scale + 1) * sizeof (VImage));
   m = (VImage*) malloc ((Scale + 1) * sizeof (VImage));

   /* compute multi-scale pyramids */
   s[0] = S;
   m[0] = M;
   for (scale = 1; scale <= Scale; scale++, Iter *= Factor)
   {
      RTTI (S, GaussianFilter, (s[scale-1], 0.5, 3, s[scale]));
      RTTI (S, TrilinearScale, (s[scale], 0.5, 0.5, 0.5));

      RTTI (M, GaussianFilter, (m[scale-1], 0.5, 3, m[scale]));
      RTTI (M, TrilinearScale, (m[scale], 0.5, 0.5, 0.5));
   }

   /* create deformation fields */
   dsx = VCreateImage (VImageNBands (s[Scale]), VImageNRows (s[Scale]), VImageNColumns (s[Scale]), VFloatRepn);
   dsy = VCreateImage (VImageNBands (s[Scale]), VImageNRows (s[Scale]), VImageNColumns (s[Scale]), VFloatRepn);
   dsz = VCreateImage (VImageNBands (s[Scale]), VImageNRows (s[Scale]), VImageNColumns (s[Scale]), VFloatRepn);
   dmx = VCreateImage (VImageNBands (m[Scale]), VImageNRows (m[Scale]), VImageNColumns (m[Scale]), VFloatRepn);
   dmy = VCreateImage (VImageNBands (m[Scale]), VImageNRows (m[Scale]), VImageNColumns (m[Scale]), VFloatRepn);
   dmz = VCreateImage (VImageNBands (m[Scale]), VImageNRows (m[Scale]), VImageNColumns (m[Scale]), VFloatRepn);

   /* initialize deformation fields */
   VFillImage (dsx, VAllBands, 0);
   VFillImage (dsy, VAllBands, 0);
   VFillImage (dsz, VAllBands, 0);
   VFillImage (dmx, VAllBands, 0);
   VFillImage (dmy, VAllBands, 0);
   VFillImage (dmz, VAllBands, 0);


   /* multi-scale scheme */
   for (scale = Scale; scale >= 0; scale--, Iter /= Factor)
   {
      /* print status */
      if (Verbose) {fprintf (stderr, "Working hard at scale %d ...                 \n", scale + 1); fflush (stderr);}

      /* compute gradients */
      RTTI (S, Gradient, (s[scale], gsx, gsy, gsz));
      SquaredGradient (gsx, gsy, gsz, gs2);
      RTTI (M, Gradient, (m[scale], gmx, gmy, gmz));
      SquaredGradient (gmx, gmy, gmz, gm2);

      /* diffusion process */
      for (iter = 1; iter <= Iter; iter++)
      {
         /* print status */
         if (Verbose) {fprintf (stderr, "Iteration %d of %d ...\r", iter, Iter); fflush (stderr);}


         /* FORWARD */

         /* interpolate deformed image */
         RTTI (S, TrilinearInverseDeform, (s[scale], dmx, dmy, dmz, tmp));

         /* compute deformation */
         RTTI (M, OpticalFlow, (m[scale], tmp, gmx, gm2, vx));
         RTTI (M, OpticalFlow, (m[scale], tmp, gmy, gm2, vy));
         RTTI (M, OpticalFlow, (m[scale], tmp, gmz, gm2, vz));
         Subtract<VFloat> (dmx, vx);
         Subtract<VFloat> (dmy, vy);
         Subtract<VFloat> (dmz, vz);

         /* clean-up */
         VDestroyImage (tmp);
         VDestroyImage (vx);
         VDestroyImage (vy);
         VDestroyImage (vz);


         /* BACKWARD */

         /* interpolate deformed image */
         RTTI (M, TrilinearInverseDeform, (m[scale], dsx, dsy, dsz, tmp));

         /* compute deformation */
         RTTI (S, OpticalFlow, (s[scale], tmp, gsx, gs2, vx));
         RTTI (S, OpticalFlow, (s[scale], tmp, gsy, gs2, vy));
         RTTI (S, OpticalFlow, (s[scale], tmp, gsz, gs2, vz));
         Subtract<VFloat> (dsx, vx);
         Subtract<VFloat> (dsy, vy);
         Subtract<VFloat> (dsz, vz);

         /* clean-up */
         VDestroyImage (tmp);
         VDestroyImage (vx);
         VDestroyImage (vy);
         VDestroyImage (vz);


         /* BIJECTIVE */

         /* compute residual deformation */
         TrilinearInverseDeform<VFloat> (dsx, dmx, dmy, dmz, rx);
         TrilinearInverseDeform<VFloat> (dsy, dmx, dmy, dmz, ry);
         TrilinearInverseDeform<VFloat> (dsz, dmx, dmy, dmz, rz);
         Add<VFloat> (rx, dmx);
         Add<VFloat> (ry, dmy);
         Add<VFloat> (rz, dmz);
         Multiply<VFloat> (rx, 0.5);
         Multiply<VFloat> (ry, 0.5);
         Multiply<VFloat> (rz, 0.5);

         /* update deformation fields */
         Subtract<VFloat> (dmx, rx);
         Subtract<VFloat> (dmy, ry);
         Subtract<VFloat> (dmz, rz);
         TrilinearInverseDeform<VFloat> (rx, dsx, dsy, dsz);
         TrilinearInverseDeform<VFloat> (ry, dsx, dsy, dsz);
         TrilinearInverseDeform<VFloat> (rz, dsx, dsy, dsz);
         Subtract<VFloat> (dsx, rx);
         Subtract<VFloat> (dsy, ry);
         Subtract<VFloat> (dsz, rz);

         /* clean-up */
         VDestroyImage (rx);
         VDestroyImage (ry);
         VDestroyImage (rz);


         /* regularize deformation fields */
         GaussianFilter<VFloat> (dsx, Sigma, width);
         GaussianFilter<VFloat> (dsy, Sigma, width);
         GaussianFilter<VFloat> (dsz, Sigma, width);
         GaussianFilter<VFloat> (dmx, Sigma, width);
         GaussianFilter<VFloat> (dmy, Sigma, width);
         GaussianFilter<VFloat> (dmz, Sigma, width);
      }

      if (scale > 0)
      {
         /* downscale deformation fields */
         TrilinearScale<VFloat> (dsx, 2.0, 2.0, 2.0); Multiply<VFloat> (dsx, 2.0);
         TrilinearScale<VFloat> (dsy, 2.0, 2.0, 2.0); Multiply<VFloat> (dsy, 2.0);
         TrilinearScale<VFloat> (dsz, 2.0, 2.0, 2.0); Multiply<VFloat> (dsz, 2.0);
         TrilinearScale<VFloat> (dmx, 2.0, 2.0, 2.0); Multiply<VFloat> (dmx, 2.0);
         TrilinearScale<VFloat> (dmy, 2.0, 2.0, 2.0); Multiply<VFloat> (dmy, 2.0);
         TrilinearScale<VFloat> (dmz, 2.0, 2.0, 2.0); Multiply<VFloat> (dmz, 2.0);

         /* clean-up */
         VDestroyImage (s[scale]);
         VDestroyImage (m[scale]);
      }

      /* clean-up */
      VDestroyImage (gsx);
      VDestroyImage (gsy);
      VDestroyImage (gsz);
      VDestroyImage (gs2);
      VDestroyImage (gmx);
      VDestroyImage (gmy);
      VDestroyImage (gmz);
      VDestroyImage (gm2);
   }

   /* return inverse deformation field */
   Dx = dsx;
   Dy = dsy;
   Dz = dsz;

   /* clean-up */
   VDestroyImage (dmx);
   VDestroyImage (dmy);
   VDestroyImage (dmz);
   free (s);
   free (m);

   return TRUE;

} /* DemonMatch */
Beispiel #19
0
int main(int argc, char *argv[]) {
    static VFloat reso   = -1.0;
    static VLong itype   = 0;
    static VBoolean flip = TRUE;
    static VBoolean reorder = TRUE;
    static VOptionDescRec  options[] = {
        {
            "reso", VFloatRepn, 1, (VPointer) &reso,
            VOptionalOpt, NULL, "New voxel resolution in mm, def: -1 means min(1.0,\"best source resolution\")"
        },

        {
            "flip", VBooleanRepn, 1, (VPointer) &flip,
            VOptionalOpt, NULL, "Whether to flip to natural convention"
        },

        {
            "reorder", VBooleanRepn, 1, (VPointer) &reorder,
            VOptionalOpt, NULL, "Whether to reorder axial slices from axial source image"
        },

        {
            "interpolation", VLongRepn, 1, & itype, VOptionalOpt, ITYPDict,
            "Type of interpolation (0: linear, 1: nearest neighbour, 2: cubic spline)"
        }
    };
    FILE *in_file, *out_file;
    VAttrList list;
    VAttrListPosn posn;
    int nobjects = 0;
    VImage src = NULL, dest = NULL, result = NULL;
    int i, b, r, c, nbands, nrows, ncols;
    VString str, newstr, fixpointString, caString, cpString;
    float fix_c, fix_r, fix_b;
    float ca_c, ca_r, ca_b;
    float cp_c, cp_r, cp_b;
    float x, y, z, min;
    VDouble v, scale_band, scale_row, scale_col;
    float scale[3], shift[3];
    /* print information */
    char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "visotrop V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    fflush(stderr);
    /* Parse command line arguments: */
    VParseFilterCmd(VNumber(options), options, argc, argv,
                    & in_file, & out_file);
    /* Read source image(s): */
    if(!(list = VReadFile(in_file, NULL)))
        exit(EXIT_FAILURE);
    /* Scale each object: */
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        switch(VGetAttrRepn(& posn)) {
        case VImageRepn:
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            if(VGetAttr(VImageAttrList(src), "voxel", NULL,
                        VStringRepn, (VPointer) & str) == VAttrFound) {
                sscanf(str, "%f %f %f", &x, &y, &z);
                fprintf(stderr, " voxel: %f %f %f\n", x, y, z);
                min = x < y ? x : y;
                min = z < min ? z : min;
                /* if resolution is not set, use default value 1 or
                   smaler value if the image resolution is better */
                if(reso < 0.0)
                    reso = min < 1.0 ? min : 1.0;
                if(reso <= 0.0)
                    exit(EXIT_FAILURE);
                fprintf(stderr, " new resolution: %f \n", reso);
                scale_col  = x / reso;
                scale_row  = y / reso;
                scale_band = z / reso;
                nbands = VImageNBands(src) * scale_band;
                nrows = VImageNRows(src) * scale_row;
                ncols = VImageNColumns(src) * scale_col;
                if(VImageNBands(src) == nbands
                        && VImageNRows(src) == nrows
                        && VImageNColumns(src) == ncols) {
                    itype = 0;
				}
                fprintf(stderr, " interpolation type: %s\n", ITYPDict[itype].keyword);
                fprintf(stderr, " old dim: %3d %3d %3d\n",
                        VImageNBands(src), VImageNRows(src), VImageNColumns(src));
                for(i = 0; i < 3; i++)
                    shift[i] = scale[i] = 0;
                scale[0] = scale_band;
                scale[1] = scale_row;
                scale[2] = scale_col;
                switch(itype) {
                    /* trilinear interpolation resampling */
                case 0:
                    dest = VTriLinearScale3d(src, NULL, (int)nbands, (int)nrows, (int)ncols,
                                             shift, scale);
                    break;
                    /* nearest neightbour resampling */
                case 1:
                    dest = VNNScale3d(src, NULL, (int)nbands, (int)nrows, (int)ncols,
                                      shift, scale);
                    break;
                    /* cubic spline */
                case 2:
                    dest = VCubicSplineScale3d(src, NULL, (int)nbands, (int)nrows, (int)ncols,
                                               shift, scale);
                    break;
                case 3: /* no interpolation, just reshuffle */
                    dest = VCopyImage(src, NULL, VAllBands);
                    break;
                default:
                    VError(" unknown resampling type %d", itype);
                }
                if(! dest)
                    exit(EXIT_FAILURE);
                /*aa 2003/09/11 added function not to rotate siemens data*/
                if(! VGetAttr(VImageAttrList(src), "orientation", NULL,
                              VStringRepn, (VPointer) & str) == VAttrFound)
                    VError(" attribute 'orientation' missing");
                if(strcmp(str, "axial") == 0) {
                    fprintf(stderr, " new dim: %3d %3d %3d\n", nbands, nrows, ncols);
                    result = VCreateImage(nbands, nrows, ncols, VPixelRepn(src));
                    VFillImage(result, VAllBands, 0);
                    for(b = 0; b < nbands; b++)
                        for(r = 0; r < nrows; r++)
                            for(c = 0; c < ncols; c++) {
                                v = VGetPixel(dest, b, r, c);
                                if((flip == FALSE) && (reorder == FALSE))
                                    VSetPixel(result, b, r, ncols - c - 1, v);
                                else if((flip == TRUE)  && (reorder == FALSE))
                                    VSetPixel(result, b, r, c, v);
                                else if((flip == FALSE) && (reorder == TRUE))
                                    VSetPixel(result, nbands - b - 1, r, ncols - c - 1, v);
                                else if((flip == TRUE)  && (reorder == TRUE))
                                    VSetPixel(result, nbands - b - 1, r, c, v);
                            }
                } else if(strcmp(str, "sagittal") == 0) {
                    /* re-arrange from sagittal to axial orientation */
                    fprintf(stderr, " new dim: %3d %3d %3d\n", nrows, ncols, nbands);
                    result = VCreateImage(nrows, ncols, nbands, VPixelRepn(src));
                    VFillImage(result, VAllBands, 0);
                    for(b = 0; b < nbands; b++)
                        for(r = 0; r < nrows; r++)
                            for(c = 0; c < ncols; c++) {
                                v = VGetPixel(dest, b, r, c);
                                if(flip == FALSE)
                                    VSetPixel(result, r, c, nbands - b - 1, v);
                                else
                                    VSetPixel(result, r, c, b, v);
                            }
                } else if(strcmp(str, "coronal") == 0) {
                    /* re-arrange from coronal to axial orientation */
                    fprintf(stderr, " new dim: %3d %3d %3d\n", nrows, nbands, ncols);
                    result = VCreateImage(nrows, nbands, ncols, VPixelRepn(src));
                    VFillImage(result, VAllBands, 0);
                    for(b = 0; b < nbands; b++)
                        for(r = 0; r < nrows; r++)
                            for(c = 0; c < ncols; c++) {
                                v = VGetPixel(dest, b, r, c);
                                if(flip == FALSE)
                                    VSetPixel(result, r, b, ncols - c - 1, v);
                                else
                                    VSetPixel(result, r, b, c, v);
                            }
                } else {
                    VError(" unknown resampling type %d", itype);
                    exit(EXIT_FAILURE);
                }
                /* copy attributes from source image */
                VCopyImageAttrs(src, result);
                // [TS] 08/03/27
                // correct 'fixpoint', 'ca' and 'cp' if they exist in the source image
                //
                // NOTE:
                // this is only done when no flipping or reordering is requested :-(
                // (WARNING!!!!) '-flip true' actually means that no flipping is done (WHAAAAT ????)
                // and therefore we test for reorder = false and flip = true
                fixpointString = VMalloc(80);
                caString       = VMalloc(80);
                cpString       = VMalloc(80);
                VBoolean _issueWarning = FALSE;
                if(VGetAttr(VImageAttrList(src), "fixpoint", NULL, VStringRepn, (VPointer)&fixpointString) == VAttrFound) {
                    if(reorder == FALSE && flip == TRUE) {
                        sscanf(fixpointString, "%f %f %f", &fix_c, &fix_r, &fix_b);
                        fix_c *= scale_col;
                        fix_r *= scale_row;
                        fix_b *= scale_band;
                        sprintf((char *)fixpointString, "%f %f %f", fix_c, fix_r, fix_b);
                        VSetAttr(VImageAttrList(result), "fixpoint", NULL, VStringRepn, fixpointString);
                    } else {
                        _issueWarning = TRUE;
                    }
                }
                if(VGetAttr(VImageAttrList(src), "ca", NULL, VStringRepn, (VPointer)&caString) == VAttrFound) {
                    if(reorder == FALSE && flip == TRUE) {
                        sscanf(caString, "%f %f %f", &ca_c, &ca_r, &ca_b);
                        ca_c *= scale_col;
                        ca_r *= scale_row;
                        ca_b *= scale_band;
                        sprintf((char *)caString, "%f %f %f", ca_c, ca_r, ca_b);
                        VSetAttr(VImageAttrList(result), "ca", NULL, VStringRepn, caString);
                    } else {
                        _issueWarning = TRUE;
                    }
                }
                if(VGetAttr(VImageAttrList(src), "cp", NULL, VStringRepn, (VPointer)&cpString) == VAttrFound) {
                    if(reorder == FALSE && flip == TRUE) {
                        sscanf(cpString, "%f %f %f", &cp_c, &cp_r, &cp_b);
                        cp_c *= scale_col;
                        cp_r *= scale_row;
                        cp_b *= scale_band;
                        sprintf((char *)cpString, "%f %f %f", cp_c, cp_r, cp_b);
                        VSetAttr(VImageAttrList(result), "cp", NULL, VStringRepn, cpString);
                    } else {
                        _issueWarning = TRUE;
                    }
                }
                if(_issueWarning) {
                    VWarning("Attributes 'fixpoint', 'ca' and 'cp' exist but were not corrected and are therefore likely to be wrong");
                    VWarning("This was caused by setting -flip to false or -reorder to true");
                    VWarning("Please correct the values manually using vattredit");
                }
                /* set the attributes to the changed values */
                newstr = VMalloc(80);
                sprintf((char *)newstr, "%f %f %f", reso, reso, reso);
                VSetAttr(VImageAttrList(result), "voxel", NULL, VStringRepn, newstr);
                VSetAttr(VImageAttrList(result), "orientation", NULL, VStringRepn, "axial");
                if(flip)
                    VSetAttr(VImageAttrList(result), "convention", NULL, VStringRepn, "natural");
                else
                    VSetAttr(VImageAttrList(result), "convention", NULL, VStringRepn, "radiologic");
            }
            VSetAttrValue(& posn, NULL, VImageRepn, result);
            VDestroyImage(src);
            break;
        default:
            continue;
        }
        nobjects++;
    }
    /* Make History */
    VHistory(VNumber(options), options, prg_name, &list, &list);
    /* Write the results to the output file: */
    if(! VWriteFile(out_file, list))
        exit(EXIT_FAILURE);
    fprintf(stderr, "%s: done.\n", argv[0]);
    return EXIT_SUCCESS;
}
Beispiel #20
0
static VPointer VImageDecodeMethod (VStringConst name, VBundle b)
{
  VImage image;
  VLong nbands, nrows, ncolumns, pixel_repn;
  VLong nframes, nviewpoints, ncolors, ncomponents;
  VAttrList list;
  size_t length;

#define Extract(name, dict, locn, required)	\
	VExtractAttr (b->list, name, dict, VLongRepn, & locn, required)

  /* Extract the number of bands, rows, columns, pixel repn, etc.: */
  nbands = nframes = nviewpoints = ncolors = ncomponents = 1;	/* defaults */
  if (! Extract (VNBandsAttr, NULL, nbands, FALSE) ||
      ! Extract (VNRowsAttr, NULL, nrows, TRUE) ||
      ! Extract (VNColumnsAttr, NULL, ncolumns, TRUE) ||
      ! Extract (VRepnAttr, VNumericRepnDict, pixel_repn, TRUE) ||
      ! Extract (VNFramesAttr, NULL, nframes, FALSE) ||
      ! Extract (VNViewpointsAttr, NULL, nviewpoints, FALSE) ||
      ! Extract (VNColorsAttr, NULL, ncolors, FALSE) ||
      ! Extract (VNComponentsAttr, NULL, ncomponents, FALSE))
    return NULL;

  /* Ensure that nbands == nframes * nviewpoints * ncolors * ncomponents.
     For backwards compatibility, set ncomponents to nbands if nbands != 1
     but nframes == nviewpoints == ncolors == ncomponents == 1. */
  if (nbands != nframes * nviewpoints * ncolors * ncomponents) {
    if (nbands != 1 && nframes == 1 && nviewpoints == 1 &&
	ncolors == 1 && ncomponents == 1)
      ncomponents = nbands;
    else {
      VWarning ("VImageDecodeMethod: %s image has inconsistent nbands",
		name);
      return NULL;
    }
  }

  /* Create an image with the specified properties: */
  if (! (image = VCreateImage ((int) nbands, (int) nrows, (int) ncolumns,
			       (VRepnKind) pixel_repn)))
    return NULL;
  VImageNFrames (image) = nframes;
  VImageNViewpoints (image) = nviewpoints;
  VImageNColors (image) = ncolors;
  VImageNComponents (image) = ncomponents;

  /* Give it whatever attributes remain: */
  list = VImageAttrList (image);
  VImageAttrList (image) = b->list;
  b->list = list;

  /* Check that the expected amount of binary data was read: */
  length = VImageNPixels (image);
  if (VPixelRepn (image) == VBitRepn)
    length = (length + 7) / 8;
  else length *= VPixelPrecision (image) / 8;
  if (length != b->length) {
    VWarning ("VImageDecodeMethod: %s image has wrong data length", name);
  Fail:   VDestroyImage (image);
    return NULL;
  }

  /* Unpack the binary pixel data: */
  length = VImageSize (image);
  if (! VUnpackData (VPixelRepn (image), VImageNPixels (image),
		     b->data, VMsbFirst, & length, & VImageData (image),
		     NULL))
    goto Fail;
  return image;

#undef Extract
}
Beispiel #21
0
int main(int argc, char *argv[])
{
  static VLong op = 0;
  static VLong dim = 1;
  static VShort radius = 2;
  static VString mask_filename=" ";
  static VOptionDescRec options[] = {
    { "op", VLongRepn, 1, &op, VOptionalOpt, OPDict,
        "type of operation" },
    { "dim", VLongRepn, 1, &dim, VOptionalOpt, DIMDict,
        "dim of structuring element (2D or 3D)" },
    { "radius", VShortRepn, 1,(VPointer) & radius, 
	VOptionalOpt, NULL,"radius of structuring element" },
    { "file", VStringRepn, 1, & mask_filename, VOptionalOpt, NULL,
      "File containing structuring element" }
  };


  FILE *in_file, *out_file, *mask_file;
  VAttrList list, list2;
  VAttrListPosn posn;
  VImage src=NULL, se=NULL, result, tmp;
  char prg[50];	
  sprintf(prg,"vgreymorph3d V%s", getVersion());
  fprintf (stderr, "%s\n", prg);

  /* Parse command line arguments and identify files: */
  VParseFilterCmd(VNumber(options),options,argc,argv,&in_file,&out_file);

  if (strlen(mask_filename) < 2) {
    if (dim == 0)
      se = VGenSphere2d(radius);
    else if (dim == 1)
      se = VGenSphere3d(radius);
    else
      VError("illegal choice of parameter 'dim' (%d), must be 2 or 3",dim);
  }
  else {
    mask_file = VOpenInputFile (mask_filename, TRUE);
    list2 = VReadFile (mask_file, NULL);
    if (! list2)
      VError("Error reading structuring element");
    fclose(mask_file);
    for (VFirstAttr (list2,&posn); VAttrExists (& posn); VNextAttr (& posn)) {
      if (VGetAttrRepn (& posn) != VImageRepn) continue;
      VGetAttrValue (& posn, NULL, VImageRepn, & se);
      if (VPixelRepn(se) != VBitRepn) 
	VError("Structuring element must be of type VBit"); 
    }
  }


  /* Read the input file: */
  list = VReadFile (in_file, 0); if (! list) exit(1);
  fclose(in_file);

  /* For each attribute read... */
  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr(& posn)) {

    if (VGetAttrRepn (& posn) != VImageRepn) continue;
    VGetAttrValue (& posn, NULL, VImageRepn, & src);
    
    switch (op) {
    case 0:
      result = VGreyDilation3d(src,se,NULL);
      break;
    case 1:
      result = VGreyErosion3d(src,se,NULL);
      break;
    case 2:
      tmp = VGreyErosion3d(src,se,NULL);
      result = VGreyDilation3d(tmp,se,NULL);
      VDestroyImage(tmp);
      break;
    case 3:
      tmp = VGreyDilation3d(src,se,NULL);
      result = VGreyErosion3d(tmp,se,NULL);
      VDestroyImage(tmp);
      break;
    }
      
    if (! result) exit(1);
    VSetAttrValue(&posn, 0, VImageRepn, result);
    VDestroyImage (src);
  } 
  
  /* Write out the results: */
  VHistory(VNumber(options),options,prg,&list,&list);
  if (! VWriteFile (out_file, list)) exit(1);
  fprintf(stderr, "%s: done.\n", argv[0]);
  return 0;
}
Beispiel #22
0
VImage
VDoTrans(VImage src, VImage dest, VImage transform, VFloat resolution, VLong type) {
    VImage src1 = NULL, dest_cor = NULL, dest_sag = NULL, trans = NULL;
    int   i, nbands1 = 0, nrows1 = 0, ncols1 = 0;
    int   xdim, ydim, zdim;
    int   orient = AXIAL;
    float b0, r0, c0;
    float scaleb, scaler, scalec;
    float scale[3], shift[3];
    VString str, str1, str2, str3, str4, str5, str6;
    VShort buf;
    VDouble u;
    float transResX = 1.0, transResY = 1.0, transResZ = 1.0;
    VString _transResString;
    if(VGetAttr(VImageAttrList(transform), "voxel", NULL, VStringRepn, (VPointer) &_transResString) == VAttrFound) {
        sscanf(_transResString, "%f %f %f", &transResX, &transResY, &transResZ);
    }
    /*
    ** get matrix size
    */
    xdim = 160;
    ydim = 200;
    zdim = 160;
    if(VGetAttr(VImageAttrList(transform), "zdim", NULL,
                VShortRepn, (VPointer) & buf) == VAttrFound) {
        zdim = buf;
    }
    if(VGetAttr(VImageAttrList(transform), "ydim", NULL,
                VShortRepn, (VPointer) & buf) == VAttrFound) {
        ydim = buf;
    }
    if(VGetAttr(VImageAttrList(transform), "xdim", NULL,
                VShortRepn, (VPointer) & buf) == VAttrFound) {
        xdim = buf;
    }
    /*
    ** get slice orientation
    */
    if(VGetAttr(VImageAttrList(src), "orientation", NULL,
                VStringRepn, (VPointer) & str) != VAttrFound)
        VError(" attribute 'orientation' missing in input file.");
    if(strcmp(str, "coronal") == 0) {
        orient  = CORONAL;
        nbands1 = ydim;
        nrows1  = zdim;
        ncols1  = xdim;
    } else if(strcmp(str, "axial") == 0) {
        orient  = AXIAL;
        nbands1 = zdim;
        nrows1  = ydim;
        ncols1  = xdim;
    } else if(strcmp(str, "sagittal") == 0) {
        orient  = SAGITTAL;
        nbands1 = zdim;
        nrows1  = xdim;
        ncols1  = ydim;
    } else
        VError("orientation must be axial or coronal");
    nbands1 /= (resolution / transResX);
    nrows1  /= (resolution / transResY);
    ncols1  /= (resolution / transResZ);
    /*
    ** scale to size
    */
    if(VGetAttr(VImageAttrList(src), "voxel", NULL,
                VStringRepn, (VPointer) & str) != VAttrFound)
        VError(" attribute 'voxel' missing in input file.");
    sscanf(str, "%f %f %f", &scalec, &scaler, &scaleb);
    scaleb /= (resolution / transResX);
    scaler /= (resolution / transResY);
    scalec /= (resolution / transResZ);
    scale[0] = scaleb;
    scale[1] = scaler;
    scale[2] = scalec;
    shift[0] = 0;
    shift[1] = (float)nrows1 * 0.5 - scaler * (float)VImageNRows(src) * 0.5;
    shift[2] = (float)ncols1 * 0.5 - scalec * (float)VImageNColumns(src) * 0.5;
    src1 = VShuffleSlices(src, NULL);
    switch(type) {
    case 0:
        src  = VTriLinearScale3d(src1, NULL, nbands1, nrows1, ncols1, shift, scale);
        break;
    case 1:
        src  = VNNScale3d(src1, NULL, nbands1, nrows1, ncols1, shift, scale);
        break;
    default:
        VError(" illegal resampling type");
    }
    /*
    ** resample image
    */
    trans = VCopyImage(transform, NULL, VAllBands);
    for(i = 0; i < 3; i++) {
        u = VPixel(trans, 0, i, 0, VDouble);
        u /= resolution;
        VPixel(trans, 0, i, 0, VDouble) = u;
    }
    b0 = (float)nbands1 * 0.5;
    r0 = (float)nrows1  * 0.5;
    c0 = (float)ncols1  * 0.5;
    switch(type) {
    case 0:
        dest = VTriLinearSample3d(src, dest, trans, b0, r0, c0, nbands1, nrows1, ncols1);
        break;
    case 1:
        dest = VNNSample3d(src, dest, trans, b0, r0, c0, nbands1, nrows1, ncols1);
        break;
    }
    /*
    ** update header
    */
    float _cax, _cay, _caz, _cpx, _cpy, _cpz;
    float _fixpointx, _fixpointy, _fixpointz;
    str1 = str2 = str3 = str4 = NULL;
    str1 = (VString) VMalloc(80);
    sprintf(str1, "%.2f %.2f %.2f", resolution, resolution, resolution);
    if(VGetAttr(VImageAttrList(trans), "ca", NULL,
                VStringRepn, (VPointer) & str2) != VAttrFound) {
        str2 = NULL;
    } else {
        sscanf(str2, "%f %f %f", &_cax, &_cay, &_caz);
        _cax /= (resolution / transResX);
        _cay /= (resolution / transResY);
        _caz /= (resolution / transResZ);
        sprintf(str2, "%.2f %.2f %.2f", _cax, _cay, _caz);
    }
    if(VGetAttr(VImageAttrList(trans), "cp", NULL,
                VStringRepn, (VPointer) & str3) != VAttrFound) {
        str3 = NULL;
    } else {
        sscanf(str3, "%f %f %f", &_cpx, &_cpy, &_cpz);
        _cpx /= (resolution / transResX);
        _cpy /= (resolution / transResY);
        _cpz /= (resolution / transResZ);
        sprintf(str3, "%.2f %.2f %.2f", _cpx, _cpy, _cpz);
    }
    if(VGetAttr(VImageAttrList(trans), "extent", NULL,
                VStringRepn, (VPointer) & str4) != VAttrFound)
        str4 = NULL;
    if(VGetAttr(VImageAttrList(trans), "fixpoint", NULL,
                VStringRepn, (VPointer) & str5) != VAttrFound) {
        str5 = NULL;
    } else {
        sscanf(str5, "%f %f %f", &_fixpointx, &_fixpointy, &_fixpointz);
        _fixpointx /= (resolution / transResX);
        _fixpointy /= (resolution / transResY);
        _fixpointz /= (resolution / transResZ);
        sprintf(str5, "%.2f %.2f %.2f", _fixpointx, _fixpointy, _fixpointz);
    }
    if(VGetAttr(VImageAttrList(trans), "talairach", NULL,
                VStringRepn, (VPointer) & str6) != VAttrFound) {
        str6 = NULL;
    }
    if(orient == CORONAL) {
        dest_cor = VAxial2Coronal(dest, NULL);
        VDestroyImage(dest);
        VCopyImageAttrs(src, dest_cor);
        VSetAttr(VImageAttrList(dest_cor), "voxel", NULL, VStringRepn, str1);
        if(str2)
            VSetAttr(VImageAttrList(dest_cor), "ca", NULL, VStringRepn, str2);
        if(str3)
            VSetAttr(VImageAttrList(dest_cor), "cp", NULL, VStringRepn, str3);
        if(str4)
            VSetAttr(VImageAttrList(dest_cor), "extent", NULL, VStringRepn, str4);
        if(str5)
            VSetAttr(VImageAttrList(dest_cor), "fixpoint", NULL, VStringRepn, str5);
        if(str6)
            VSetAttr(VImageAttrList(dest_cor), "talairach", NULL, VStringRepn, str6);
        return dest_cor;
    } else if(orient == SAGITTAL) {
        dest_sag = VAxial2Sagittal(dest, NULL);
        VDestroyImage(dest);
        VCopyImageAttrs(src, dest_sag);
        VSetAttr(VImageAttrList(dest_sag), "voxel", NULL, VStringRepn, str1);
        if(str2)
            VSetAttr(VImageAttrList(dest_sag), "ca", NULL, VStringRepn, str2);
        if(str3)
            VSetAttr(VImageAttrList(dest_sag), "cp", NULL, VStringRepn, str3);
        if(str4)
            VSetAttr(VImageAttrList(dest_sag), "extent", NULL, VStringRepn, str4);
        if(str5)
            VSetAttr(VImageAttrList(dest_sag), "fixpoint", NULL, VStringRepn, str5);
        if(str6)
            VSetAttr(VImageAttrList(dest_sag), "talairach", NULL, VStringRepn, str6);
        return dest_sag;
    } else {
        VCopyImageAttrs(src, dest);
        VSetAttr(VImageAttrList(dest), "voxel", NULL, VStringRepn, str1);
        if(str2)
            VSetAttr(VImageAttrList(dest), "ca", NULL, VStringRepn, str2);
        if(str3)
            VSetAttr(VImageAttrList(dest), "cp", NULL, VStringRepn, str3);
        if(str4)
            VSetAttr(VImageAttrList(dest), "extent", NULL, VStringRepn, str4);
        if(str5)
            VSetAttr(VImageAttrList(dest), "fixpoint", NULL, VStringRepn, str5);
        if(str6)
            VSetAttr(VImageAttrList(dest), "talairach", NULL, VStringRepn, str6);
        return dest;
    }
}
Beispiel #23
0
int main (int argc, char* argv[])
{
   VString        inname;            /* name of input images      */
   VString        outname;           /* name of output images     */
   VString        fieldname;         /* name of deformation field */
   VBoolean       verbose = TRUE;    /* verbose flag              */
   VOptionDescRec options[] =        /* options of program        */
   {
      {"in",      VStringRepn,  1, &inname,    VRequiredOpt, NULL, "Input image"},
      {"out",     VStringRepn,  1, &outname,   VRequiredOpt, NULL, "Deformed output image"},
      {"field",   VStringRepn,  1, &fieldname, VRequiredOpt, NULL, "3D deformation field"},
      {"verbose", VBooleanRepn, 1, &verbose,   VOptionalOpt, NULL, "Show status messages. Optional"}
   };

   VAttrList in_history=NULL;      /* history of input images      */
   VAttrList field_history=NULL;   /* history of deformation field */

   VAttrList In;           /* input images  */
   VImage    Dx, Dy, Dz;   /* field images  */

   VAttrListPosn pos;   /* position in list */
   VImage        in;    /* image in list    */

   float  fx, fy, fz;   /* scaling factors          */
   VImage dx, dy, dz;   /* scaled deformation field */

   VAttrListPosn rider;                         /* functional data rider   */
   int           bands, rows, columns, steps;   /* size of functional data */
   VImage        data;                          /* functional data         */
   VShort        *src, *dest;                   /* functional data pointer */

   VBoolean success;   /* success flag */

   int n, t, z;   /* indices */


   /* print information */
   char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vdeform V%s", ver);
  
   fprintf (stderr, "%s\n", prg_name); fflush (stderr);

   /* parse command line */
   if (!VParseCommand (VNumber (options), options, &argc, argv))
   {
      if (argc > 1) VReportBadArgs (argc, argv);
      VReportUsage (argv[0], VNumber (options), options, NULL);
      exit (1);
   }

   /* read input images */
   if (verbose) {fprintf (stderr, "Reading input image '%s' ...\n", inname); fflush (stderr);}
   ReadImages (inname, In, in_history);
   if (!In) exit (2);

   /* read deformation field */
   if (verbose) {fprintf (stderr, "Reading 3D deformation field '%s' ...\n", fieldname); fflush (stderr);}
   ReadField (fieldname, Dx, Dy, Dz, field_history);
   if (!Dx || !Dy || !Dz) exit (3);


   /* deform anatomical images */
   for (VFirstAttr (In, &pos); VAttrExists (&pos); VNextAttr (&pos))
   {
      /* get image */
      VGetAttrValue (&pos, NULL, VImageRepn, &in);
      if (VPixelRepn (in) != VUByteRepn) break;

      /* compare image and field */
      if (verbose) {fprintf (stderr, "Comparing anatomical image and deformation field ...\n"); fflush (stderr);}
      if (!Compatible (in, Dx)) exit (4);
      if (!Compatible (in, Dy)) exit (4);
      if (!Compatible (in, Dz)) exit (4);

      /* deform image */
      if (verbose) {fprintf (stderr, "Deforming anatomical image ...\n"); fflush (stderr);}
      RTTI (in, TrilinearInverseDeform, (in, Dx, Dy, Dz));
      VSetAttrValue (&pos, NULL, VImageRepn, in);
   }


   /* deform map images */
   for (; VAttrExists (&pos); VNextAttr (&pos))
   {
      /* get image */
      VGetAttrValue (&pos, NULL, VImageRepn, &in);
      if (VPixelRepn (in) != VFloatRepn) break;

      /* scale field */
      if (verbose) {fprintf (stderr, "Scaling deformation field ...\n"); fflush (stderr);}
      fx = (float) VImageNColumns (in) / (float) VImageNColumns (Dx);
      fy = (float) VImageNRows    (in) / (float) VImageNRows    (Dy);
      fz = (float) VImageNBands   (in) / (float) VImageNBands   (Dz);
      TrilinearScale<VFloat> (Dx, fx, fy, fz, dx); Multiply<VFloat> (dx, fx);
      TrilinearScale<VFloat> (Dy, fx, fy, fz, dy); Multiply<VFloat> (dy, fy);
      TrilinearScale<VFloat> (Dz, fx, fy, fz, dz); Multiply<VFloat> (dz, fz);

      /* compare image and field */
      if (verbose) {fprintf (stderr, "Comparing map image and deformation field ...\n"); fflush (stderr);}
      if (!Compatible (in, dx)) exit (5);
      if (!Compatible (in, dy)) exit (5);
      if (!Compatible (in, dz)) exit (5);

      /* deform image */
      if (verbose) {fprintf (stderr, "Deforming map image ...\n"); fflush (stderr);}
      RTTI (in, TrilinearInverseDeform, (in, dx, dy, dz));
      VSetAttrValue (&pos, NULL, VImageRepn, in);

      /* clean-up */
      VDestroyImage (dx);
      VDestroyImage (dy);
      VDestroyImage (dz);
   }


   /* deform functional images */
   if (VAttrExists (&pos))
   {
      /* get data size */
      bands = rows = columns = steps = 0;
      for (rider = pos; VAttrExists (&rider); VNextAttr (&rider))
      {
         /* get image */
         VGetAttrValue (&rider, NULL, VImageRepn, &data);
         if (VPixelRepn (data) != VShortRepn) break;

         /* store image size */
         if (VImageNBands   (data) > steps)   steps   = VImageNBands   (data);
         if (VImageNRows    (data) > rows)    rows    = VImageNRows    (data);
         if (VImageNColumns (data) > columns) columns = VImageNColumns (data);
         bands++;
      }
      in = VCreateImage (bands, rows, columns, VShortRepn);

      /* scale field */
      if (verbose) {fprintf (stderr, "Scaling deformation field ...\n"); fflush (stderr);}
      fx = (float) VImageNColumns (in) / (float) VImageNColumns (Dx);
      fy = (float) VImageNRows    (in) / (float) VImageNRows    (Dy);
      fz = (float) VImageNBands   (in) / (float) VImageNBands   (Dz);
      TrilinearScale<VFloat> (Dx, fx, fy, fz, dx); Multiply<VFloat> (dx, fx);
      TrilinearScale<VFloat> (Dy, fx, fy, fz, dy); Multiply<VFloat> (dy, fy);
      TrilinearScale<VFloat> (Dz, fx, fy, fz, dz); Multiply<VFloat> (dz, fz);

      /* compare image and field */
      if (verbose) {fprintf (stderr, "Comparing functional images and deformation field ...\n"); fflush (stderr);}
      if (!Compatible (in, dx)) exit (6);
      if (!Compatible (in, dy)) exit (6);
      if (!Compatible (in, dz)) exit (6);


      /* expand zero images */
      for (rider = pos, z = 0; z < bands; z++, VNextAttr (&rider))
      {
         VGetAttrValue (&rider, NULL, VImageRepn, &data);
         if (FunctionalZero (data))
         {
            FunctionalResize (data, steps, rows, columns);
            VSetAttrValue (&rider, NULL, VImageRepn, data);
         }
      }

      /* deform images */
      if (verbose) {fprintf (stderr, "Deforming functional images ...\n"); fflush (stderr);}
      for (t = 0; t < steps; t++)
      {
         /* collect data */
         dest = (VShort*) VPixelPtr (in, 0, 0, 0);
         for (rider = pos, z = 0; z < bands; z++, VNextAttr (&rider))
         {
            VGetAttrValue (&rider, NULL, VImageRepn, &data);
            src = (VShort*) VPixelPtr (data, t, 0, 0);
            for (n = 0; n < rows * columns; ++n)
               *(dest++) = *(src++);
         }

         /* deform image */
         if (verbose) {fprintf (stderr, "Timestep %d of %d ...\r", t + 1, steps); fflush (stderr);}
         RTTI (in, TrilinearInverseDeform, (in, dx, dy, dz));

         /* spread data */
         src = (VShort*) VPixelPtr (in, 0, 0, 0);
         for (rider = pos, z = 0; z < bands; z++, VNextAttr (&rider))
         {
            VGetAttrValue (&rider, NULL, VImageRepn, &data);
            dest = (VShort*) VPixelPtr (data, t, 0, 0);
            for (n = 0; n < rows * columns; ++n)
               *(dest++) = *(src++);
         }
      }

      /* collapse zero images */
      for (rider = pos, z = 0; z < bands; z++, VNextAttr (&rider))
      {
         VGetAttrValue (&rider, NULL, VImageRepn, &data);
         if (FunctionalZero (data))
         {
            FunctionalResize (data, 1, 1, 1);
            VSetAttrValue (&rider, NULL, VImageRepn, data);
         }
      }


      /* clean-up */
      VDestroyImage (in);
      VDestroyImage (dx);
      VDestroyImage (dy);
      VDestroyImage (dz);

      /* proceed */
      pos = rider;
   }


   /* check list */
   if (VAttrExists (&pos))
   {
      VError ("Remaining image does not contain valid data");
      exit (7);
   }

   /* Prepend History */
   VPrependHistory(VNumber(options),options,prg_name,&in_history);

   /* write output images */
   if (verbose) {fprintf (stderr, "Writing output image '%s' ...\n", outname); fflush (stderr);}
   success = WriteImages (outname, In, in_history);
   if (!success) exit (8);


   /* clean-up 
      VDestroyAttrList (inhistory);
      VDestroyAttrList (fieldhistory);
      VDestroyAttrList (In);
      VDestroyImage (Dx);
      VDestroyImage (Dy);
      VDestroyImage (Dz); */

   /* exit */
   if (verbose) {fprintf (stderr, "Finished.\n"); fflush (stderr);}
   return 0;

} /* main */
Beispiel #24
0
VImage 
VAniso3d(VImage src,VImage dest,VShort numiter,
	 VShort type,VFloat kappa,VFloat alpha)
{
  VImage tmp1=NULL,tmp2=NULL;
  int nbands,nrows,ncols;
  int b,r,c,iter;
  float delta;
  float dx,dy,dz,d,u,v;
  float ux1,ux2,uy1,uy2,uz1,uz2;
  float b1,b2,r1,r2,c1,c2;
  VDouble xmax,xmin;
  VBoolean ignore = TRUE;


  nbands = VImageNBands(src);
  nrows  = VImageNRows(src);
  ncols  = VImageNColumns(src);

  if (nbands < 3) VError(" min number of slices is 3");

  tmp1 = VConvertImageCopy(src,NULL,VAllBands,VFloatRepn);
  tmp2 = VCreateImage(nbands,nrows,ncols,VFloatRepn);
  VFillImage(tmp2,VAllBands,0);

  xmax = VPixelMaxValue (tmp1);
  xmin = VPixelMinValue (tmp1);

  delta = 1.0 / 7.0;

  dx = dy = dz = 0;

  for (iter=0; iter < numiter; iter++) {

    for (b=1; b<nbands-1; b++) {
      for (r=1; r<nrows-1; r++) {
	for (c=1; c<ncols-1; c++) {

	  u  = VPixel(tmp1,b,r,c,VFloat);
	  if (ignore && ABS(u) < 1.0e-10) continue;

	  c1 = VPixel(tmp1,b,r,c+1,VFloat);
	  c2 = VPixel(tmp1,b,r,c-1,VFloat);

	  r1 = VPixel(tmp1,b,r+1,c,VFloat);
	  r2 = VPixel(tmp1,b,r-1,c,VFloat);

	  b1 = VPixel(tmp1,b+1,r,c,VFloat);
	  b2 = VPixel(tmp1,b-1,r,c,VFloat);

	  /* col-dir */
	  dx = c1-u;
	  dy = r1-r2;
	  dz = b1-b2;
	  d  = diffusion3d(dx,dy,dz,type,kappa,alpha);
	  ux1 = d*(c1 - u);

	  dx = u-c2;
	  d  = diffusion3d(dx,dy,dz,type,kappa,alpha);
	  ux2 = d*(u - c2);


	  /* row-dir */
	  dx = c1-c2;
	  dy = r1-u;
	  dz = b1-b2;
	  d  = diffusion3d(dx,dy,dz,type,kappa,alpha);
	  uy1 = d*(r1 - u);

	  dy = u-r2;
	  d  = diffusion3d(dx,dy,dz,type,kappa,alpha);
	  uy2 = d*(u - r2);


	  /* slice-dir */
	  dx = c1-c2;
	  dy = r1-r2;
	  dz = b1-u;
	  d  = diffusion3d(dx,dy,dz,type,kappa,alpha);
	  uz1 = d*(b1 - u);

	  dz = u-b2;
	  d  = diffusion3d(dx,dy,dz,type,kappa,alpha);
	  uz2 = d*(u - b2);

	  /* sum */
	  v = u + delta*(ux1 - ux2 + uy1 - uy2 + uz1 - uz2);

	  if (v > xmax) v = xmax;
	  if (v < xmin) v = xmin;
	  VPixel(tmp2,b,r,c,VFloat) = v;
	}
      }
    }
    tmp1 = VCopyImagePixels(tmp2,tmp1,VAllBands);
  }


  /*
  ** output
  */
  dest = VCopyImage(src,dest,VAllBands);

  xmax = VPixelMaxValue (dest);
  xmin = VPixelMinValue (dest);

  for (b=1; b<nbands-1; b++) {
    for (r=1; r<nrows-1; r++) {
      for (c=1; c<ncols-1; c++) {
	v = VPixel(tmp2,b,r,c,VFloat);
	if (v > xmax) v = xmax;
	if (v < xmin) v = xmin;
	VSetPixel(dest,b,r,c,(VDouble) v);
      }
    }
  }

  VDestroyImage(tmp1);
  VDestroyImage(tmp2);

  return dest;
}
Beispiel #25
0
int main(int argc, char *argv[]) {
    VAttrList list, out_list;
    VImage src;
    VImage dest = NULL;
    VAttrListPosn posn;
    VString str;
    int nimages;
    char historystr[] = "history";
    char prg_name[100];
    char ver[100];
    getLipsiaVersion(ver, sizeof(ver));
    sprintf(prg_name, "vdelcereb V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /* Parse command line arguments: */
    if(!VParseCommand(VNumber(options), options, &argc, argv) ||
            ! VIdentifyFiles(VNumber(options), options, "in", & argc, argv, 0) ||
            ! VIdentifyFiles(VNumber(options), options, "out", & argc, argv, -1))
        goto Usage;
    if(argc > 1) {
        VReportBadArgs(argc, argv);
Usage:
        VReportUsage(argv[0], VNumber(options), options, NULL);
        exit(EXIT_FAILURE);
    }
    /* Read source image(s): */
    if(strcmp(in_filename, "-") == 0)
        in_file = stdin;
    else {
        in_file = fopen(in_filename, "r");
        if(! in_file)
            VError("Failed to open input file %s", in_filename);
    }
    if(!(list = VReadFile(in_file, NULL)))
        exit(EXIT_FAILURE);
    fclose(in_file);
    /* Process image */
    nimages = 0;
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & src);
        dest = VCerebellum(src);
        VSetAttrValue(& posn, NULL, VImageRepn, dest);
        VDestroyImage(src);
        nimages++;
        break;
    }
    /* Create outlist */
    out_list = VCreateAttrList();
    /* Make History */
    VHistory(VNumber(options), options, prg_name, &list, &out_list);
    /*  Alle Attribute (ausser history:) in die neue Liste schreiben: */
    for(VFirstAttr(list, &posn); VAttrExists(&posn); VNextAttr(&posn)) {
        if(strncmp(VGetAttrName(&posn), historystr, strlen(historystr)) == 0)
            continue;
        switch(VGetAttrRepn(&posn)) {
        case VImageRepn:
            VGetAttrValue(&posn, NULL, VImageRepn, &src);
            VAppendAttr(out_list, VGetAttrName(&posn), NULL, VImageRepn, src);
            break;
        case VStringRepn:
            VGetAttrValue(&posn, NULL, VStringRepn, &str);
            VAppendAttr(out_list, VGetAttrName(&posn), NULL, VImageRepn, str);
            break;
        default:
            break;
        }
    }
    /* Write the results to the output file: */
    if(strcmp(out_filename, "-") == 0)
        out_file = stdout;
    else {
        out_file = fopen(out_filename, "w");
        if(! out_file)
            VError("Failed to open output file %s", out_filename);
    }
    if(VWriteFile(out_file, out_list)) {
        if(verbose >= 1)
            fprintf(stderr, "%s: processed %d image%s.\n",
                    argv[0], nimages, nimages == 1 ? "" : "s");
        fprintf(stderr, "%s: done.\n", argv[0]);
    }
    return 0;
}
Beispiel #26
0
void
VSpatialFilter(VAttrList list,VDouble fwhm)
{
  VAttrListPosn posn;
  VImage src[NSLICES],xsrc=NULL,tmp=NULL,dest=NULL,kernel=NULL,tmp2d=NULL;
  VString str=NULL;
  float v0,v1,v2,v3;
  int b,r,c,i,size;
  int n,nslices,nrows,ncols,dim;
  double u, sigma=0;
  extern VImage VGaussianConv (VImage,VImage,VBand,double,int);


  /* get image dimensions */
  dim = 3;
  v0 = v1 = v2 = v3 = 1;
  n = i = nrows = ncols = 0;
  str = VMalloc(100);
  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {
    if (i >= NSLICES) VError(" too many slices");
    if (VGetAttrRepn (& posn) != VImageRepn) continue;
    VGetAttrValue (& posn, NULL,VImageRepn, & xsrc);
    if (VPixelRepn(xsrc) != VShortRepn) continue;
    if (VImageNBands(xsrc) > n) n = VImageNBands(xsrc);
    if (VImageNRows(xsrc) > nrows) nrows = VImageNRows(xsrc);
    if (VImageNColumns(xsrc) > ncols) ncols = VImageNColumns(xsrc);
    if (VGetAttr (VImageAttrList (xsrc), "voxel", NULL,VStringRepn, (VPointer) & str) == VAttrFound) {
      sscanf(str,"%f %f %f",&v1,&v2,&v3);
    }
    src[i] = xsrc;
    i++;    
  }
  nslices = i;


  /* in general, apply 3D spatial filtering */
  dim = 3;

  /* only if clearly non-isotropic apply 2D filtering */
  v0 = 0.5*(v1+v2);
  if (ABS(v0-v3) > 0.5) dim = 2;


  /*
  ** Sigma
  */
  sigma  = fwhm/sqrt(8.0*log(2.0));
  sigma /= (double)v1;


  /*
  ** 2D gauss filtering
  */
  if (dim==2) {
    fprintf(stderr," 2D spatial filter: fwhm=  %.3f mm sigma= %.3f vox\n",fwhm,sigma); 

    size = (int)(6.0 * sigma + 1.5);
    if ((size & 1) == 0) size++;
    fprintf(stderr," size= %d\n",size);

    for (b=0; b<nslices; b++) {
      if (VImageNRows(src[b]) < 2) continue;
      tmp2d  = VGaussianConv(src[b],tmp2d, VAllBands, sigma, size);
      src[b] = VCopyImagePixels(tmp2d,src[b],VAllBands);
    }
    VDestroyImage(tmp2d);
  }


  /*
  ** 3D gauss filtering
  */
  if (dim==3) {
    fprintf(stderr," 3D spatial filter: fwhm=  %.3f mm sigma= %.3f vox\n",fwhm,sigma); 

    kernel = VSGaussKernel(sigma);

    tmp = VCreateImage(nslices,nrows,ncols,VFloatRepn);
    VFillImage(tmp,VAllBands,0);
    
    for (i=0; i<n; i++) {
      if (i%20 == 0) fprintf(stderr," i= %5d\r",i);
      
      VFillImage(tmp,VAllBands,0);
      for (b=0; b<nslices; b++) {
	if (VImageNRows(src[b]) < 2) continue;
	for (r=0; r<nrows; r++) {
	  for (c=0; c<ncols; c++) {
	    u = VPixel(src[b],i,r,c,VShort);
	    VPixel(tmp,b,r,c,VFloat) = u;
	  }
	}
      }
      
      dest = VGauss3d (tmp,dest,kernel);
      
      for (b=0; b<nslices; b++) {
	if (VImageNRows(src[b]) < 2) continue;
	for (r=0; r<nrows; r++) {
	  for (c=0; c<ncols; c++) {
	    u = VPixel(dest,b,r,c,VFloat);
	    VPixel(src[b],i,r,c,VShort) = u;
	  }
	}
      }
    }
  }


}