Ejemplo n.º 1
0
int
main(int argc, char *argv[]) {
  char *me, *ninName, *noutName, *err;
  Nrrd *nin;

  me = argv[0];
  if (3 != argc) {
    /*                       0   1     2   (3) */
    fprintf(stderr, "usage: %s <nin> <nout>\n", me);
    exit(1);
  }
  ninName = argv[1];
  noutName = argv[2];
  if (nrrdLoad(nin=nrrdNew(), ninName, NULL)) {
    fprintf(stderr, "%s: couldn't open nrrd \"%s\":\n%s", me, ninName,
            err = biffGetDone(NRRD));
    free(err); exit(1);
  }
  if (nrrdSave(noutName, nin, NULL)) {
    fprintf(stderr, "%s: trouble saving nrrd to \"%s\":\n%s", me, noutName,
            err = biffGetDone(NRRD));
    free(err); exit(1);
  }
  nrrdNuke(nin);
  exit(0);
}
Ejemplo n.º 2
0
int
main(int argc, char **argv) {
  char *me, *err, *key="strong bad", *value;
  Nrrd *nrrd;
  NrrdIoState *io;

  me = argv[0];
  if (2 != argc)
    usage(me);

  io = nrrdIoStateNew();
  nrrdStateVerboseIO = 10;
  
  if (nrrdLoad(nrrd=nrrdNew(), argv[1], NULL)) {
    fprintf(stderr, "%s: trouble loading \"%s\":\n%s", 
            me, argv[1], err = biffGetDone(NRRD));
    free(err);
    exit(1);
  }

  if ((value = nrrdKeyValueGet(nrrd, key))) {
    fprintf(stderr, "%s: '%s':='%s' (%d)\n", me, key, value, 
            (int)strlen(value));
  } else {
    fprintf(stderr, "%s: value not found for key: %s\n", me, key);
  }
  
  nrrdIoStateNix(io);
  nrrdNuke(nrrd);

  exit(0);
}
Ejemplo n.º 3
0
int
main(int argc, char *argv[]) {
  Nrrd *hvol, *info;
  char *iStr, *dStr, *oStr;
  int dim;

  me = argv[0];
  if (argc != 4)
    usage();
  iStr = argv[1];
  dStr = argv[2];
  oStr = argv[3];

  if (nrrdLoad(hvol=nrrdNew(), iStr, NULL)) {
    fprintf(stderr, "%s: trouble reading hvol:\n%s\n", me, biffGet(NRRD));
    usage();
  }
  if (1 != sscanf(dStr, "%d", &dim)) {
    fprintf(stderr, "%s: trouble parsing %s as an int\n", me, dStr);
    usage();
  }
  if (baneOpacInfo(info = nrrdNew(), hvol, dim, nrrdMeasureHistoMean)) {
    fprintf(stderr, "%s: trouble calculting %d-D opacity info:\n%s\n",
            me, dim, biffGet(BANE));
    exit(1);
  }
  if (nrrdSave(oStr, info, NULL)) {
    fprintf(stderr, "%s: trouble saving nrrd to %s:\n%s\n", me, oStr,
            biffGet(NRRD));
    exit(1);
  }
  nrrdNuke(hvol);
  nrrdNuke(info);
  exit(0);
}
Ejemplo n.º 4
0
void
makeSceneGlass2(limnCamera *cam, echoRTParm *parm, echoObject **sceneP) {
  echoObject *cube, *rect;
  echoObject *scene;
  Nrrd *ntext;
  echoPos_t matx[16];
  
  *sceneP = scene = echoObjectNew(echoList);

  ELL_3V_SET(cam->from, 0, 0, 100);
  ELL_3V_SET(cam->at,   0, 0, 0);
  ELL_3V_SET(cam->up,   0, 1, 0);
  cam->uRange[0] = -1.0;
  cam->uRange[1] = 1.0;
  cam->vRange[0] = -1.0;
  cam->vRange[1] = 1.0;

  parm->jitterType = echoJitterNone;
  parm->numSamples = 1;
  parm->imgResU = 300;
  parm->imgResV = 300;
  parm->aperture = 0.0;
  parm->renderLights = AIR_FALSE;
  parm->shadow = 0.0;
  parm->seedRand = AIR_FALSE;
  parm->maxRecDepth = 10;
  parm->mrR = 1.0;
  parm->mrG = 0.0;
  parm->mrB = 1.0;

  ELL_4M_SET_SCALE(matx, 0.5, 0.5, 0.5);
  cube = echoRoughSphere(80, 40, matx);
  /*
  cube = echoObjectNew(echoSphere);
  echoSphereSet(cube, 0, 0, 0, 0.5);
  */
  echoMatterGlassSet(cube,
                     1.0, 1.0, 1.0,
                     1.33333, 0.0, 0.0);
  echoObjectAdd(scene, cube);

  nrrdLoad(ntext=nrrdNew(), "check.nrrd", NULL);
  
  rect = echoObjectNew(echoRectangle);
  printf("rect = %p\n", rect);
  echoRectangleSet(rect,
                         -1, -1, -0.51,
                         2, 0, 0,
                         0, 2, 0);
  echoMatterPhongSet(rect, 1.0, 1.0, 1.0, 1.0,
                     0.0, 1.0, 0.0, 40);
  echoMatterTextureSet(rect, ntext);
  echoObjectAdd(scene, rect);
  
  /*
  light = echoLightNew(echoLightDirectional);
  echoLightDirectionalSet(light, 1, 1, 1, 0, 0, 1);
  echoLightArrayAdd(lightArr, light);
  */
}
Ejemplo n.º 5
0
int
main(int argc, char **argv) {
  char *me, *err;
  Nrrd *nrrd;
  NrrdRange *range;

  me = argv[0];
  if (2 != argc)
    usage(me);

  nrrdStateVerboseIO = 10;
  
  if (nrrdLoad(nrrd=nrrdNew(), argv[1], NULL)) {
    fprintf(stderr, "%s: trouble loading \"%s\":\n%s", 
            me, argv[1], err = biffGet(NRRD));
    free(err);
    exit(1);
  }

  range = nrrdRangeNewSet(nrrd, nrrdBlind8BitRangeState);

  printf("%s: min = %g; max = %g, hasNonExist = %d\n", me,
         range->min, range->max, range->hasNonExist);

  nrrdNuke(nrrd);

  exit(0);
}
Ejemplo n.º 6
0
int
unrrdu_cksumDoit(const char *me, char *inS, int endian,
                 int printendian, FILE *fout) {
  Nrrd *nrrd;
  airArray *mop;
  unsigned int crc;
  char stmp[AIR_STRLEN_SMALL], ends[AIR_STRLEN_SMALL];
  size_t nn;

  mop = airMopNew();
  airMopAdd(mop, nrrd=nrrdNew(), (airMopper)nrrdNuke, airMopAlways);
  if (nrrdLoad(nrrd, inS, NULL)) {
    biffMovef(me, NRRD, "%s: trouble loading \"%s\"", me, inS);
    airMopError(mop); return 1;
  }
  crc = nrrdCRC32(nrrd, endian);
  nn = nrrdElementNumber(nrrd)*nrrdElementSize(nrrd);
  sprintf(ends, "(%s)", airEnumStr(airEndian, endian));
  fprintf(fout, "%u%s %s%s%s\n", crc,
          printendian ? ends : "",
          airSprintSize_t(stmp, nn),
          strcmp("-", inS) ? " " : "",
          strcmp("-", inS) ? inS : "");

  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 7
0
int
unrrdu_minmaxDoit(char *me, char *inS, int blind8BitRange, FILE *fout) {
  char err[BIFF_STRLEN];
  Nrrd *nrrd;
  NrrdRange *range;
  airArray *mop;

  mop = airMopNew();
  airMopAdd(mop, nrrd=nrrdNew(), (airMopper)nrrdNuke, airMopAlways);
  if (nrrdLoad(nrrd, inS, NULL)) {
    sprintf(err, "%s: trouble loading \"%s\"", me, inS);
    biffMove(me, err, NRRD); airMopError(mop); return 1;
  }

  range = nrrdRangeNewSet(nrrd, blind8BitRange);
  airMopAdd(mop, range, (airMopper)nrrdRangeNix, airMopAlways);
  airSinglePrintf(fout, NULL, "min: %g\n", range->min);
  airSinglePrintf(fout, NULL, "max: %g\n", range->max);
  if (0 == range->min && 0 == range->max) {
    fprintf(fout, "# min == max == 0.0 exactly\n");
  }
  if (range->hasNonExist) {
    fprintf(fout, "# has non-existent values\n");
  }

  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 8
0
/*
** _nrrdHestNrrdParse()
**
** Converts a filename into a nrrd for the sake of hest.
** There is no HestMaybeNrrdParse because this already does that:
** when we get an empty string, we give back a NULL pointer, and
** that is just fine
*/
int
_nrrdHestNrrdParse(void *ptr, char *str, char err[AIR_STRLEN_HUGE]) {
  char me[] = "_nrrdHestNrrdParse", *nerr;
  Nrrd **nrrdP;
  airArray *mop;

  if (!(ptr && str)) {
    sprintf(err, "%s: got NULL pointer", me);
    return 1;
  }
  nrrdP = (Nrrd **)ptr;
  if (airStrlen(str)) {
    mop = airMopNew();
    *nrrdP = nrrdNew();
    airMopAdd(mop, *nrrdP, (airMopper)nrrdNuke, airMopOnError);
    if (nrrdLoad(*nrrdP, str, NULL)) {
      airMopAdd(mop, nerr = biffGetDone(NRRD), airFree, airMopOnError);
      airStrcpy(err, AIR_STRLEN_HUGE, nerr);
      airMopError(mop);
      return (strstr(err, "EOF") ? 2 : 1);
    }
    airMopOkay(mop);
  } else {
    /* they gave us an empty string, we give back no nrrd,
       but its not an error condition */
    *nrrdP = NULL;
  }
  return 0;
}
Ejemplo n.º 9
0
void
demoIO(char *filename)
{
  char me[]="demoIO", newname[]="foo.nrrd", *err, *key, *val;
  int kvn, kvi;
  Nrrd *nin;

  /* create a nrrd; at this point this is just an empty container */
  nin = nrrdNew();

  /* read in the nrrd from file */
  if (nrrdLoad(nin, filename, NULL))
  {
    err = biffGetDone(NRRD);
    fprintf(stderr, "%s: trouble reading \"%s\":\n%s", me, filename, err);
    free(err);
    return;
  }

  /* say something about the array */
  printf("%s: \"%s\" is a %d-dimensional nrrd of type %d (%s)\n",
         me, filename, nin->dim, nin->type,
         airEnumStr(nrrdType, nin->type));
  printf("%s: the array contains %d elements, each %d bytes in size\n",
         me, (int)nrrdElementNumber(nin), (int)nrrdElementSize(nin));

  /* print out the key/value pairs present */
  kvn = nrrdKeyValueSize(nin);
  if (kvn)
  {
    for (kvi=0; kvi<kvn; kvi++)
    {
      nrrdKeyValueIndex(nin, &key, &val, kvi);
      printf("%s: key:value %d = %s:%s\n", me, kvi, key, val);
      free(key);
      free(val);
      key = val = NULL;
    }
  }

  /* modify key/value pairs, and write out the nrrd to a different file */
  nrrdKeyValueClear(nin);
  nrrdKeyValueAdd(nin, "new key", "precious value");
  if (nrrdSave(newname, nin, NULL))
  {
    err = biffGetDone(NRRD);
    fprintf(stderr, "%s: trouble writing \"%s\":\n%s", me, newname, err);
    free(err);
    return;
  }

  /* blow away both the Nrrd struct *and* the memory at nin->data
     (nrrdNix() frees the struct but not the data,
     nrrdEmpty() frees the data but not the struct) */
  nrrdNuke(nin);

  return;
}
Ejemplo n.º 10
0
void
makeSceneDOF(limnCamera *cam, echoRTParm *parm, echoScene *scene) {
  echoObject *rect;
  Nrrd *ntext;
  
  ELL_3V_SET(cam->from, 6, 6, 20);
  ELL_3V_SET(cam->at,   0, 0, 0);
  ELL_3V_SET(cam->up,   0, 1, 0);
  cam->uRange[0] = -3.3;
  cam->uRange[1] = 3.3;
  cam->vRange[0] = -3.3;
  cam->vRange[1] = 3.3;

  parm->jitterType = echoJitterJitter;
  parm->numSamples = 4;
  parm->imgResU = 300;
  parm->imgResV = 300;
  parm->aperture = 0.5;
  parm->renderLights = AIR_FALSE;
  parm->renderBoxes = AIR_FALSE;
  parm->seedRand = AIR_FALSE;
  parm->maxRecDepth = 10;
  parm->shadow = 1.0;

  nrrdLoad(ntext = nrrdNew(), "tmp.png", NULL);

  rect = echoObjectNew(scene, echoTypeRectangle);
  echoRectangleSet(rect,
                   -0.5, 1.5, -3,
                   2, 0, 0,
                   0, -2, 0);
  echoColorSet(rect, 1, 0.5, 0.5, 1);
  echoMatterPhongSet(scene, rect, 1.0, 0.0, 0.0, 1);
  echoMatterTextureSet(scene, rect, ntext);
  echoObjectAdd(scene, rect);

  rect = echoObjectNew(scene, echoTypeRectangle);
  echoRectangleSet(rect,
                   -1, 1, 0,
                   2, 0, 0,
                   0, -2, 0);
  echoColorSet(rect, 0.5, 1, 0.5, 1);
  echoMatterPhongSet(scene, rect, 1.0, 0.0, 0.0, 1);
  echoMatterTextureSet(scene, rect, ntext);
  echoObjectAdd(scene, rect);

  rect = echoObjectNew(scene, echoTypeRectangle);
  echoRectangleSet(rect,
                   -1.5, 0.5, 3,
                   2, 0, 0,
                   0, -2, 0);
  echoColorSet(rect, 0.5, 0.5, 1, 1);
  echoMatterPhongSet(scene, rect, 1.0, 0.0, 0.0, 1);
  echoMatterTextureSet(scene, rect, ntext);
  echoObjectAdd(scene, rect);

  return;
}
Ejemplo n.º 11
0
Archivo: data.c Proyecto: BRAINSia/teem
int
unrrdu_dataMain(int argc, const char **argv, const char *me,
                hestParm *hparm) {
  hestOpt *opt = NULL;
  char *err, *inS=NULL;
  Nrrd *nin;
  NrrdIoState *nio;
  airArray *mop;
  int car, pret;

  mop = airMopNew();
  hestOptAdd(&opt, NULL, "nin", airTypeString, 1, 1, &inS, NULL,
             "input nrrd");
  airMopAdd(mop, opt, (airMopper)hestOptFree, airMopAlways);

  USAGE(_unrrdu_dataInfoL);
  PARSE();
  airMopAdd(mop, opt, (airMopper)hestParseFree, airMopAlways);

  nio = nrrdIoStateNew();
  airMopAdd(mop, nio, (airMopper)nrrdIoStateNix, airMopAlways);
  nio->skipData = AIR_TRUE;
  nio->keepNrrdDataFileOpen = AIR_TRUE;
  nin = nrrdNew();
  airMopAdd(mop, nin, (airMopper)nrrdNuke, airMopAlways);

  if (nrrdLoad(nin, inS, nio)) {
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: error reading header:\n%s", me, err);
    airMopError(mop);
    return 1;
  }
  if (_nrrdDataFNNumber(nio) > 1) {
    fprintf(stderr, "%s: sorry, currently can't operate with multiple "
            "detached datafiles\n", me);
    airMopError(mop);
    return 1;
  }
  if (!( nrrdFormatNRRD == nio->format )) {
    fprintf(stderr, "%s: can only print data of NRRD format files\n", me);
    airMopError(mop); return 1;
  }
  car = fgetc(nio->dataFile);
#ifdef _MSC_VER
  /* needed because otherwise printing a carraige return will
     automatically also produce a newline */
  _setmode(_fileno(stdout), _O_BINARY);
#endif
  while (EOF != car) {
    fputc(car, stdout);
    car = fgetc(nio->dataFile);
  }
  airFclose(nio->dataFile);

  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 12
0
Nrrd* LBLReader::Convert(int t, int c, bool get_max)
{
   int64_t pos = m_path_name.find_last_of('.');
   if (pos == -1)
      return 0;
   wstring str_name = m_path_name.substr(0, pos);
   wostringstream strs;
   strs << str_name /*<< "_t" << t << "_c" << c*/ << ".lbl";
   str_name = strs.str();

   Nrrd *output = nrrdNew();
   NrrdIoState *nio = nrrdIoStateNew();
   nrrdIoStateSet(nio, nrrdIoStateSkipData, AIR_TRUE);
   string str;
   str.assign(str_name.length(), 0);
   for (int i=0; i<(int)str_name.length(); i++)
      str[i] = (char)str_name[i];
   if (nrrdLoad(output, str.c_str(), nio))
      return 0;
   nio = nrrdIoStateNix(nio);
   if (output->dim != 3 ||
         (output->type != nrrdTypeInt &&
          output->type != nrrdTypeUInt))
   {
      delete []output->data;
      nrrdNix(output);
      return 0;
   }
   int slice_num = int(output->axis[2].size);
   int x_size = int(output->axis[0].size);
   int y_size = int(output->axis[1].size);
   int data_size = slice_num * x_size * y_size;
   output->data = new unsigned int[data_size];

   if (nrrdLoad(output, str.c_str(), NULL))
   {
      delete []output->data;
      nrrdNix(output);
      return 0;
   }

   return output;
}
Ejemplo n.º 13
0
/* *************************************************************** */
Nrrd *reg_io_readNRRDfile(const char *filename)
{
    /* create a nrrd; at this point this is just an empty container */
    Nrrd *nrrdImage = nrrdNew();
    char *err;

    /* read in the nrrd from file */
    if (nrrdLoad(nrrdImage, filename, NULL)){
        err = biffGetDone(NRRD);
        fprintf(stderr, "[NiftyReg ERROR] Can not read the file \"%s\":\n%s\n", filename, err);
        free(err);
        exit(1);
    }
    return nrrdImage;
}
Ejemplo n.º 14
0
int
main(int argc, char *argv[]) {
  char *bStr, *pStr, *oStr;
  Nrrd *b, *p, *o;

  me = argv[0];
  if (argc != 4) 
    usage();
  bStr = argv[1];
  pStr = argv[2];
  oStr = argv[3];
  if (nrrdLoad(b=nrrdNew(), bStr, NULL)) {
    fprintf(stderr, "%s: trouble reading %s:\n%s\n", me, bStr, biffGet(NRRD));
    usage();
  }

  if (nrrdLoad(p=nrrdNew(), pStr, NULL)) {
    fprintf(stderr, "%s: trouble reading %s:\n%s\n", me, pStr, biffGet(NRRD));
    usage();
  }
  
  if (baneOpacCalc(o = nrrdNew(), b, p)) {
    fprintf(stderr, "%s: trouble calculating opac:\n%s", me, biffGet(BANE));
    exit(1);
  }

  if (nrrdSave(oStr, o, NULL)) {
    fprintf(stderr, "%s: trouble writing %s:\n%s\n", me, oStr, biffGet(NRRD));
    exit(1);
  }

  nrrdNuke(o);
  nrrdNuke(b);
  nrrdNuke(p);
  exit(0);
}
Ejemplo n.º 15
0
int
main(int argc, char *argv[]) {
  Nrrd *info;
  float sigma;

  AIR_UNUSED(argc);
  if (nrrdLoad(info=nrrdNew(), argv[1], NULL)) {
    fprintf(stderr, "trouble:\n%s\n", biffGet(BANE));
  }
  if (baneSigmaCalc(&sigma, info)) {
    fprintf(stderr, "trouble:\n%s\n", biffGet(BANE));
  }
  printf("%g\n", sigma);

  nrrdNuke(info);
  return 0;
}
Ejemplo n.º 16
0
int main(int argc, char * argv[])
{
	Nrrd *nin = nrrdNew();
	Nrrd *nquantized = nrrdNew();
	char *biffErr;

	if(argc < 4) {
		fprintf(stderr,"Usage: %s centerx centery nrrd\n",argv[0]);
		return 1;
	}

	cx = atoi(argv[1]);
	cy = atoi(argv[2]);

	if(nrrdLoad(nin, argv[3], NULL)) {
		biffErr = biffGetDone(NRRD);
		fprintf(stderr, "Error reading file: %s\n", biffErr);
		free(biffErr);
		return 1;
	}

	printf("Read %d-dimensional nrrd of type %d (%s)\n",
			nin->dim, nin->type, airEnumStr(nrrdType, nin->type));

	printf("Axis dimensions: %d x %d x %d\n", nin->axis[0].size,
			nin->axis[1].size, nin->axis[2].size);

	NrrdRange *range = nrrdRangeNewSet(nin, 0);
	printf("min: %g\tmax: %g\n", range->min, range->max);

	if(nrrdQuantize(nquantized, nin, range, 8)) {
		biffErr = biffGetDone(NRRD);
		fprintf(stderr, "Error quantizing: %s\n", biffErr);
		return 1;
	}

	process_slices(nquantized);

	nrrdRangeNix(range);
	nrrdNuke(nin);
	nrrdNuke(nquantized);

	return 0;
}
Ejemplo n.º 17
0
void
makeSceneAntialias(limnCamera *cam, echoRTParm *parm,
                   echoObject **sceneP, airArray **lightArrP) {
  echoObject *scene, *rect;
  Nrrd *ntext;

  *sceneP = scene = echoObjectNew(echoList);
  *lightArrP = echoLightArrayNew();

  ELL_3V_SET(cam->from, 0, 0, 10);
  ELL_3V_SET(cam->at,   0, 0, 0);
  ELL_3V_SET(cam->up,   0, 1, 0);
  cam->uRange[0] = -3.7;
  cam->uRange[1] = 3.7;
  cam->vRange[0] = -3.7;
  cam->vRange[1] = 3.7;

  parm->jitterType = echoJitterGrid;
  parm->numSamples = 1;
  parm->imgResU = 300;
  parm->imgResV = 300;
  parm->aperture = 0.0;
  parm->renderLights = AIR_FALSE;
  parm->renderBoxes = AIR_FALSE;
  parm->seedRand = AIR_FALSE;
  parm->maxRecDepth = 10;
  parm->shadow = 1.0;

  nrrdLoad(ntext = nrrdNew(), "chirp.nrrd", NULL);
  rect = echoObjectNew(echoRectangle);
  echoRectangleSet(rect,
                         -3, -3, 0,
                         6, 0, 0,
                         0, 6, 0);
  echoMatterPhongSet(rect, 1, 1, 1, 1.0,
                     1.0, 0.0, 0.0, 1);
  echoMatterTextureSet(rect, ntext);
  echoObjectAdd(scene, rect);

  return;
}
Ejemplo n.º 18
0
int
main(int argc, char *argv[]) {
  Nrrd *info, *pos;
  float sigma, gthresh;
  char *iStr, *oStr, *sigStr, *gthStr;

  me = argv[0];
  if (argc != 5) {
    usage();
  }
  iStr = argv[1];
  sigStr = argv[2];
  gthStr = argv[3];
  oStr = argv[4];

  if (1 != sscanf(sigStr, "%g", &sigma) ||
      1 != sscanf(gthStr, "%g", &gthresh)) {
    fprintf(stderr, "%s: couldn't parse %s and %s as floats\n", me, 
            sigStr, gthStr);
    usage();
  }

  if (nrrdLoad(info=nrrdNew(), iStr, NULL)) {
    fprintf(stderr, "%s: trouble reading \"%s\" :\n%s\n", me, 
            iStr, biffGet(NRRD));
    exit(1);
  }
  if (banePosCalc(pos = nrrdNew(), sigma, gthresh, info)) {
    fprintf(stderr, "%s: trouble calculating %s:\n%s\n", me,
            2 == info->dim ? "p(v,g)" : "p(v)", biffGet(BANE));
    exit(1);
  }
  if (nrrdSave(oStr, pos, NULL)) {
    fprintf(stderr, "%s: trouble writing output to \"%s\"\n", me, oStr);
    exit(1);
  }
  nrrdNuke(info);
  nrrdNuke(pos);
  exit(0);
}
Ejemplo n.º 19
0
int
tkwbExpandImageInfo(tkwbSlide **slide) {
    char me[]="tkwbExpandImageInfo", err[BIFF_STRLEN], *image;
    Nrrd *nimg;
    int si, sx, sy, len;
    airArray *mop;

    mop = airMopNew();
    nimg = nrrdNew();
    airMopAdd(mop, nimg, (airMopper)nrrdNuke, airMopAlways);
    for (si=0; slide[si]; si++) {
        if (nrrdLoad(nimg, slide[si]->image, NULL)) {
            sprintf(err, "%s: trouble reading slide image \"%s\"",
                    me, slide[si]->image);
            biffMove(TKWB, err, NRRD);
            airMopError(mop);
            return 1;
        }
        if (!nrrdFormatPNG->fitsInto(nimg, nrrdEncodingGzip, AIR_TRUE)) {
            sprintf(err, "%s: slide image \"%s\" doesn't seem to be an image",
                    me, slide[si]->image);
            biffMove(TKWB, err, NRRD);
            airMopError(mop);
            return 1;
        }
        sx = nimg->axis[nimg->dim-2].size;
        sy = nimg->axis[nimg->dim-1].size;
        len = (strlen("<img width=xxxx height=xxxx src=\"\">")
               + strlen(slide[si]->image) + 1);
        image = (char *)calloc(len, sizeof(char));
        sprintf(image, "<img width=%d height=%d src=\"%s\">",
                sx, sy, slide[si]->image);
        free(slide[si]->image);
        slide[si]->image = image;
    }

    airMopOkay(mop);
    return 0;
}
Ejemplo n.º 20
0
float *
_baneTRexRead(char *fname) {
  char me[]="_baneTRexRead";

  if (nrrdLoad(baneNpos=nrrdNew(), fname, NULL)) {
    fprintf(stderr, "%s: !!! trouble reading \"%s\":\n%s\n", me, 
            fname, biffGet(NRRD));
    return NULL;
  }
  if (banePosCheck(baneNpos, 1)) {
    fprintf(stderr, "%s: !!! didn't get a valid p(x) file:\n%s\n", me, 
            biffGet(BANE));
    return NULL;
  }
  if (TREX_LUTLEN != baneNpos->axis[0].size) {
    fprintf(stderr, "%s: !!! need a length %d p(x) (not " _AIR_SIZE_T_CNV
            ")\n", me, TREX_LUTLEN, baneNpos->axis[0].size); 
    return NULL;
  }

  return (float *)baneNpos->data;
}
Ejemplo n.º 21
0
Nrrd* NRRDReader::Convert(int t, int c, bool get_max)
{
   if (t<0 || t>=m_time_num)
      return 0;

   int i;

   m_data_name = m_4d_seq[t].filename.substr(m_4d_seq[t].filename.find_last_of(GETSLASH())+1);

   Nrrd *output = nrrdNew();
   NrrdIoState *nio = nrrdIoStateNew();
   nrrdIoStateSet(nio, nrrdIoStateSkipData, AIR_TRUE);
   string str;
   str.assign(m_4d_seq[t].filename.length(), 0);
   for (i=0; i<(int)m_4d_seq[t].filename.length(); i++)
      str[i] = (char)m_4d_seq[t].filename[i];
   if (nrrdLoad(output, str.c_str(), nio))
      return 0;
   nio = nrrdIoStateNix(nio);
   if (output->dim != 3)
   {
      delete []output->data;
      nrrdNix(output);
      return 0;
   }
   m_slice_num = int(output->axis[2].size);
   m_x_size = int(output->axis[0].size);
   m_y_size = int(output->axis[1].size);
   m_xspc = output->axis[0].spacing;
   m_yspc = output->axis[1].spacing;
   m_zspc = output->axis[2].spacing;
   if (m_xspc>0.0 && m_xspc<100.0 &&
         m_yspc>0.0 && m_yspc<100.0 &&
         m_zspc>0.0 && m_zspc<100.0)
      m_valid_spc = true;
   else
   {
      m_valid_spc = false;
      m_xspc = 1.0;
      m_yspc = 1.0;
      m_zspc = 1.0;
   }
   int data_size = m_slice_num * m_x_size * m_y_size;
   if (output->type == nrrdTypeUShort || output->type == nrrdTypeShort)
      data_size *= 2;
    output->data = new unsigned char[data_size];

   if (nrrdLoad(output, str.c_str(), NULL))
   {
      delete []output->data;
      nrrdNix(output);
      return 0;
   }
    // turn signed into unsigned
    if (output->type == nrrdTypeChar) {
        for (i=0; i<m_slice_num*m_x_size*m_y_size; i++) {
            char val = ((char*)output->data)[i];
            unsigned char n = val + 128;
            ((unsigned char*)output->data)[i] = n;
        }
        output->type = nrrdTypeUChar;
    }
    m_max_value = 0.0;
    // turn signed into unsigned
    unsigned short min_value = 32768, n;
    if (output->type == nrrdTypeShort || output->type == nrrdTypeUShort) {
        for (i=0; i<m_slice_num*m_x_size*m_y_size; i++) {
            if (output->type == nrrdTypeShort) {
                short val = ((short*)output->data)[i];
                n = val + 32768;
                ((unsigned short*)output->data)[i] = n;
                min_value = (n < min_value)?n:min_value;
            } else {
                n =  ((unsigned short*)output->data)[i];
            }
            if (get_max)
                m_max_value = (n > m_max_value)?n:m_max_value;
        }
        output->type = nrrdTypeUShort;
    }
   //find max value
   if (output->type == nrrdTypeUChar)
   {
      //8 bit
      m_max_value = 255.0;
       m_scalar_scale = 1.0;
   }
   else if (output->type == nrrdTypeUShort)
   {
       m_max_value -= min_value;
       //16 bit
       for (i=0; i<m_slice_num*m_x_size*m_y_size; i++) {
           ((unsigned short*)output->data)[i] =
           ((unsigned short*)output->data)[i] - min_value;
       }
      if (m_max_value > 0.0)
         m_scalar_scale = 65535.0 / m_max_value;
      else
         m_scalar_scale = 1.0;
   }
   else
   {
      delete []output->data;
      nrrdNix(output);
      return 0;
   }

   m_cur_time = t;
   return output;
}
Ejemplo n.º 22
0
int
_nrrdHestIterParse(void *ptr, char *str, char err[AIR_STRLEN_HUGE]) {
  char me[]="_nrrdHestIterParse", *nerr;
  Nrrd *nrrd;
  NrrdIter **iterP;
  airArray *mop;
  double val;
  int ret;

  if (!(ptr && str)) {
    sprintf(err, "%s: got NULL pointer", me);
    return 1;
  }
  iterP = (NrrdIter **)ptr;
  mop = airMopNew();
  *iterP = nrrdIterNew();
  airMopAdd(mop, *iterP, (airMopper)nrrdIterNix, airMopOnError);

  /* the challenge here is determining if a given string represents a
     filename or a number.  Obviously there are cases where it could
     be both, so we'll assume its a filename first.  Because: there
     are different ways of writing the same number, such as "3" -->
     "+3", "3.1" --> "3.10", so someone accidently using the file when
     they mean to use the number has easy ways of changing the number
     representation, since these trivial transformations will probably
     not all result in valid filenames. Another problem is that one
     really wants a general robust test to see if a given string is a
     valid number representation AND NOTHING BUT THAT, and sscanf() is
     not that test.  In any case, if there are to be improved smarts
     about this matter, they need to be implemented below and nowhere
     else. */

  nrrd = nrrdNew();
  ret = nrrdLoad(nrrd, str, NULL);
  if (!ret) {
    /* first attempt at nrrdLoad() was SUCCESSFUL */
    nrrdIterSetOwnNrrd(*iterP, nrrd);
  } else {
    /* so it didn't load as a nrrd- if its because fopen() failed,
       then we'll try it as a number.  If its for another reason,
       then we complain */
    nrrdNuke(nrrd);
    if (2 != ret) {
      /* it failed because of something besides the fopen(), so complain */
      nerr = biffGetDone(NRRD);
      airStrcpy(err, AIR_STRLEN_HUGE, nerr);
      airMopError(mop); return 1;
    } else {
      /* fopen() failed, so it probably wasn't meant to be a filename */
      free(biffGetDone(NRRD));
      ret = airSingleSscanf(str, "%lf", &val);
      if (_nrrdLooksLikeANumber(str)
          || (1 == ret && (!AIR_EXISTS(val)
                           || AIR_ABS(AIR_PI - val) < 0.0001))) {
        /* either it patently looks like a number, or,
           it already parsed as a number and it is a special value */
        if (1 == ret) {
          nrrdIterSetValue(*iterP, val);
        } else {
          /* oh, this is bad. */
          fprintf(stderr, "%s: PANIC, is it a number or not?", me);
          exit(1);
        }
      } else {
        /* it doesn't look like a number, but the fopen failed, so
           we'll let it fail again and pass back the error messages */
        if (nrrdLoad(nrrd = nrrdNew(), str, NULL)) {
          nerr = biffGetDone(NRRD);
          airStrcpy(err, AIR_STRLEN_HUGE, nerr);
          airMopError(mop); return 1;
        } else {
          /* what the hell? */
          fprintf(stderr, "%s: PANIC, is it a nrrd or not?", me);
          exit(1);
        }
      }
    }
  }
  airMopAdd(mop, iterP, (airMopper)airSetNull, airMopOnError);
  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 23
0
int
tend_epiregMain(int argc, const char **argv, const char *me,
                hestParm *hparm) {
  int pret, rret;
  hestOpt *hopt = NULL;
  char *perr, *err;
  airArray *mop;
  char *outS, *buff;

  char *gradS;
  NrrdKernelSpec *ksp;
  Nrrd **nin, **nout3D, *nout4D, *ngrad, *ngradKVP, *nbmatKVP;
  unsigned int ni, ninLen, *skip, skipNum;
  int ref, noverbose, progress, nocc, baseNum;
  float bw[2], thr, fitFrac;
  double bvalue;

  hestOptAdd(&hopt, "i", "dwi0 dwi1", airTypeOther, 1, -1, &nin, NULL,
             "all the diffusion-weighted images (DWIs), as separate 3D nrrds, "
             "**OR**: one 4D nrrd of all DWIs stacked along axis 0",
             &ninLen, NULL, nrrdHestNrrd);
  hestOptAdd(&hopt, "g", "grads", airTypeString, 1, 1, &gradS, NULL,
             "array of gradient directions, in the same order as the "
             "associated DWIs were given to \"-i\", "
             "**OR** \"-g kvp\" signifies that gradient directions should "
             "be read from the key/value pairs of the DWI",
             NULL, NULL, nrrdHestNrrd);
  hestOptAdd(&hopt, "r", "reference", airTypeInt, 1, 1, &ref, "-1",
             "which of the DW volumes (zero-based numbering) should be used "
             "as the standard, to which all other images are transformed. "
             "Using -1 (the default) means that 9 intrinsic parameters "
             "governing the relationship between the gradient direction "
             "and the resulting distortion are estimated and fitted, "
             "ensuring good registration with the non-diffusion-weighted "
             "T2 image (which is never explicitly used in registration). "
             "Otherwise, by picking a specific DWI, no distortion parameter "
             "estimation is done. ");
  hestOptAdd(&hopt, "nv", NULL, airTypeInt, 0, 0, &noverbose, NULL,
             "turn OFF verbose mode, and "
             "have no idea what stage processing is at.");
  hestOptAdd(&hopt, "p", NULL, airTypeInt, 0, 0, &progress, NULL,
             "save out intermediate steps of processing");
  hestOptAdd(&hopt, "bw", "x,y blur", airTypeFloat, 2, 2, bw, "1.0 2.0",
             "standard devs in X and Y directions of gaussian filter used "
             "to blur the DWIs prior to doing segmentation. This blurring "
             "does not effect the final resampling of registered DWIs. "
             "Use \"0.0 0.0\" to say \"no blurring\"");
  hestOptAdd(&hopt, "t", "DWI thresh", airTypeFloat, 1, 1, &thr, "nan",
             "Threshold value to use on DWIs, "
             "to do initial separation of brain and non-brain.  By default, "
             "the threshold is determined automatically by histogram "
             "analysis. ");
  hestOptAdd(&hopt, "ncc", NULL, airTypeInt, 0, 0, &nocc, NULL,
             "do *NOT* do connected component (CC) analysis, after "
             "thresholding and before moment calculation.  Doing CC analysis "
             "usually gives better results because it converts the "
             "thresholding output into something much closer to a "
             "real segmentation");
  hestOptAdd(&hopt, "f", "fit frac", airTypeFloat, 1, 1, &fitFrac, "0.70",
             "(only meaningful with \"-r -1\") When doing linear fitting "
             "of the intrinsic distortion parameters, it is good "
             "to ignore the slices for which the segmentation was poor.  A "
             "heuristic is used to rank the slices according to segmentation "
             "quality.  This option controls how many of the (best) slices "
             "contribute to the fitting.  Use \"0\" to disable distortion "
             "parameter fitting. ");
  hestOptAdd(&hopt, "k", "kernel", airTypeOther, 1, 1, &ksp, "cubic:0,0.5",
             "kernel for resampling DWIs along the phase-encoding "
             "direction during final registration stage",
             NULL, NULL, nrrdHestKernelSpec);
  hestOptAdd(&hopt, "s", "start #", airTypeInt, 1, 1, &baseNum, "1",
             "first number to use in numbered sequence of output files.");
  hestOptAdd(&hopt, "o", "output/prefix", airTypeString, 1, 1, &outS, "-",
             "For separate 3D DWI volume inputs: prefix for output filenames; "
             "will save out one (registered) "
             "DWI for each input DWI, using the same type as the input. "
             "**OR**: For single 4D DWI input: output file name. ");

  mop = airMopNew();
  airMopAdd(mop, hopt, (airMopper)hestOptFree, airMopAlways);
  USAGE(_tend_epiregInfoL);
  JUSTPARSE();
  airMopAdd(mop, hopt, (airMopper)hestParseFree, airMopAlways);

  if (strcmp("kvp", gradS)) {
    /* they're NOT coming from key/value pairs */
    if (nrrdLoad(ngrad=nrrdNew(), gradS, NULL)) {
      airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble loading gradient list:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
  } else {
    if (1 != ninLen) {
      fprintf(stderr, "%s: can do key/value pairs only from single nrrd", me);
      airMopError(mop); return 1;
    }
    /* they are coming from key/value pairs */
    if (tenDWMRIKeyValueParse(&ngradKVP, &nbmatKVP, &bvalue,
                              &skip, &skipNum, nin[0])) {
      airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble parsing gradient list:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
    if (nbmatKVP) {
      fprintf(stderr, "%s: sorry, can only use gradients, not b-matrices", me);
      airMopError(mop); return 1;
    }
    ngrad = ngradKVP;
  }
  airMopAdd(mop, ngrad, (airMopper)nrrdNuke, airMopAlways);

  nout3D = AIR_CALLOC(ninLen, Nrrd *);
  airMopAdd(mop, nout3D, airFree, airMopAlways);
  nout4D = nrrdNew();
  airMopAdd(mop, nout4D, (airMopper)nrrdNuke, airMopAlways);
  buff = AIR_CALLOC(airStrlen(outS) + 10, char);
  airMopAdd(mop, buff, airFree, airMopAlways);
  if (!( nout3D && nout4D && buff )) {
    fprintf(stderr, "%s: couldn't allocate buffers", me);
    airMopError(mop); return 1;
  }
  for (ni=0; ni<ninLen; ni++) {
    nout3D[ni]=nrrdNew();
    airMopAdd(mop, nout3D[ni], (airMopper)nrrdNuke, airMopAlways);
  }
  if (1 == ninLen) {
    rret = tenEpiRegister4D(nout4D, nin[0], ngrad,
                            ref,
                            bw[0], bw[1], fitFrac, thr, !nocc,
                            ksp->kernel, ksp->parm,
                            progress, !noverbose);
  } else {
    rret = tenEpiRegister3D(nout3D, nin, ninLen, ngrad,
                            ref,
                            bw[0], bw[1], fitFrac, thr, !nocc,
                            ksp->kernel, ksp->parm,
                            progress, !noverbose);
  }
  if (rret) {
    airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
    fprintf(stderr, "%s: trouble doing epireg:\n%s\n", me, err);
    airMopError(mop); return 1;
  }

  if (1 == ninLen) {
    if (nrrdSave(outS, nout4D, NULL)) {
      airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble writing \"%s\":\n%s\n", me, outS, err);
      airMopError(mop); return 1;
    }
  } else {
    for (ni=0; ni<ninLen; ni++) {
      if (ninLen+baseNum > 99) {
        sprintf(buff, "%s%05d.nrrd", outS, ni+baseNum);
      } else if (ninLen+baseNum > 9) {
        sprintf(buff, "%s%02d.nrrd", outS, ni+baseNum);
      } else {
        sprintf(buff, "%s%d.nrrd", outS, ni+baseNum);
      }
      if (nrrdSave(buff, nout3D[ni], NULL)) {
        airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
        fprintf(stderr, "%s: trouble writing \"%s\":\n%s\n", me, buff, err);
        airMopError(mop); return 1;
      }
    }
  }

  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 24
0
void mexFunction(int nlhs, mxArray *plhs[],
  int nrhs, const mxArray *prhs[])
{
  char me[]="nrrdLoad", *filename, *errPtr, errBuff[AIR_STRLEN_MED];
  int filenameLen, sizeI[NRRD_DIM_MAX];
  mxClassID mtype;
  size_t sizeZ[NRRD_DIM_MAX];
  unsigned int axIdx;
  Nrrd *nrrd;
  NrrdIoState *nio;
  airArray *mop;

  if (!(1 == nrhs && mxIsChar(prhs[0]))) {
    sprintf(errBuff, "%s: requires one string argument (the name of the file)", me);
    mexErrMsgTxt(errBuff);
  }

  mop = airMopNew();
  filenameLen = mxGetM(prhs[0])*mxGetN(prhs[0])+1;
  filename = mxCalloc(filenameLen, sizeof(mxChar));  /* managed by Matlab */
  mxGetString(prhs[0], filename, filenameLen);

  nrrd = nrrdNew();
  airMopAdd(mop, nrrd, (airMopper)nrrdNix, airMopAlways);
  nio = nrrdIoStateNew();
  airMopAdd(mop, nio, (airMopper)nrrdIoStateNix, airMopAlways);
  nrrdIoStateSet(nio, nrrdIoStateSkipData, AIR_TRUE);

  /* read header, but no data */
  if (nrrdLoad(nrrd, filename, nio)) {
    errPtr = biffGetDone(NRRD);
    airMopAdd(mop, errPtr, airFree, airMopAlways);
    sprintf(errBuff, "%s: trouble reading NRRD header:\n%s", me, errPtr);
    airMopError(mop);
    mexErrMsgTxt(errBuff);
  }
  mtype = typeNtoM(nrrd->type);
  if (mxUNKNOWN_CLASS == mtype) {
    sprintf(errBuff, "%s: sorry, can't handle type %s (%d)", me,
            airEnumStr(nrrdType, nrrd->type), nrrd->type);
    airMopError(mop);
    mexErrMsgTxt(errBuff);
  }

  /* allocate matlab array based on nrrd struct */
  for (axIdx=0; axIdx<nrrd->dim; axIdx++) {
    sizeI[axIdx] = nrrd->axis[axIdx].size;
  }
  plhs[0]=mxCreateNumericArray(nrrd->dim,sizeI,mtype,mxREAL);

  /* copy data pointer */
  nrrd->data = mxGetPr(plhs[0]);

  /* read second time, now loading data */
  if (nrrdLoad(nrrd, filename, NULL)) {
    errPtr = biffGetDone(NRRD);
    airMopAdd(mop, errPtr, airFree, airMopAlways);
    sprintf(errBuff, "%s: trouble reading NRRD:\n%s", me, errPtr);
    airMopError(mop);
    mexErrMsgTxt(errBuff);
  }

  airMopOkay(mop);
  return;
}
Ejemplo n.º 25
0
int
main(int argc, char *argv[]) {
  alanContext *actx;
  char *err, *me;
  Nrrd *ninit, *nparm, *npri;

  me = argv[0];

  ninit = nrrdNew();
  if (nrrdLoad(ninit, "init.nrrd", NULL)) {
    fprintf(stderr, "%s: load(init.nrrd) failed\n", me);
    free(biffGetDone(NRRD));
    ninit = nrrdNuke(ninit);
  }
  nparm = nrrdNew();
  if (nrrdLoad(nparm, "parm.nrrd", NULL)) {
    fprintf(stderr, "%s: load(parm.nrrd) failed\n", me);
    free(biffGetDone(NRRD));
    nparm = nrrdNuke(nparm);
  }
  npri = nrrdNew();
  if (nrrdLoad(npri, "pri.nrrd", NULL)) {
    fprintf(stderr, "%s: load(pri.nrrd) failed\n", me);
    free(biffGetDone(NRRD));
    npri = nrrdNuke(npri);
  }
  actx = alanContextNew();
  if (alanDimensionSet(actx, 2)
      || alan2DSizeSet(actx, 100, 100)
      || alanParmSet(actx, alanParmMaxIteration, 100000)
      || alanParmSet(actx, alanParmVerbose, 1)
      || alanParmSet(actx, alanParmTextureType, alanTextureTypeTuring)
      || alanParmSet(actx, alanParmRandRange, 4.0)
      || alanParmSet(actx, alanParmK, 0.0125)
      || alanParmSet(actx, alanParmH, 1.2)
      || alanParmSet(actx, alanParmAlpha, 16.0+0.07)
      || alanParmSet(actx, alanParmBeta, 12.0-0.07)
      || alanParmSet(actx, alanParmSpeed, 1.38)
      || alanParmSet(actx, alanParmMinAverageChange, 0.00002)
      || alanParmSet(actx, alanParmSaveInterval, 500)
      || alanParmSet(actx, alanParmFrameInterval,500)
      || alanParmSet(actx, alanParmConstantFilename, AIR_TRUE)
      || alanParmSet(actx, alanParmWrapAround, AIR_TRUE)
      || alanParmSet(actx, alanParmNumThreads, 10)
      ) {
    err = biffGetDone(ALAN);
    fprintf(stderr, "%s: trouble: %s\n", me, err);
    free(err); return 1;
  }

  if (alanUpdate(actx)
      || alanInit(actx, ninit, nparm)) {
    err = biffGetDone(ALAN);
    fprintf(stderr, "%s: trouble: %s\n", me, err);
    free(err); return 1;
  }
  fprintf(stderr, "%s: going to run (%d threads) . . .\n",
          me, actx->numThreads);
  alanRun(actx);
  fprintf(stderr, "%s: stop = %d: %s\n", me, actx->stop,
          airEnumDesc(alanStop, actx->stop));
  /*
  nrrdSave("lev0.nrrd", actx->nlev[0], NULL);
  nrrdSave("lev1.nrrd", actx->nlev[1], NULL);
  */

  actx = alanContextNix(actx);
  return 0;
}
Ejemplo n.º 26
0
int
main(int argc, const char *argv[]) {
  const char *me;
  size_t vi, ii, qvalLen;
  Nrrd *nval, *nhist, *nimg, *nread, *ncorr;
  double aa, bb, *val;
  airArray *mop;
  char *corrname, explain[AIR_STRLEN_LARGE];
  int differ;

  AIR_UNUSED(argc);
  me = argv[0];
  mop = airMopNew();

  qvalLen = 10*BINS;
  nrrdAlloc_va(nval=nrrdNew(), nrrdTypeDouble, 1, 4*qvalLen);
  airMopAdd(mop, nval, (airMopper)nrrdNuke, airMopAlways);
  val = AIR_CAST(double*, nval->data);

  airSrandMT(999);
  vi = 0;
  for (ii=0; ii<qvalLen; ii++) {
    airNormalRand(&aa, NULL);
    val[vi++] = aa;
  }
  for (ii=0; ii<qvalLen; ii++) {
    airNormalRand(NULL, &bb);
    val[vi++] = bb;
  }
  for (ii=0; ii<qvalLen; ii++) {
    airNormalRand(&aa, &bb);
    val[vi++] = aa;
    val[vi++] = bb;
  }

  nhist=nrrdNew();
  airMopAdd(mop, nhist, (airMopper)nrrdNuke, airMopAlways);
  nimg=nrrdNew();
  airMopAdd(mop, nimg, (airMopper)nrrdNuke, airMopAlways);
  if (nrrdHisto(nhist, nval, NULL, NULL, BINS, nrrdTypeInt)
      || nrrdHistoDraw(nimg, nhist, HGHT, AIR_TRUE, 0.0)
      || nrrdSave(THISNAME, nimg, NULL)) {
    char *err;
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: trouble producing histo:\n%s", me, err);
    airMopError(mop); return 1;
  }

  nread = nrrdNew();
  airMopAdd(mop, nread, (airMopper)nrrdNuke, airMopAlways);
  ncorr = nrrdNew();
  airMopAdd(mop, ncorr, (airMopper)nrrdNuke, airMopAlways);

  corrname = testDataPathPrefix(CORRNAME);
  airMopAdd(mop, corrname, airFree, airMopAlways);
  if (nrrdLoad(ncorr, corrname, NULL)
      || nrrdLoad(nread, THISNAME, NULL)) {
    char *err;
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: trouble reading:\n%s", me, err);
    airMopError(mop); return 1;
  }

  if (nrrdCompare(ncorr, nread, AIR_FALSE /* onlyData */,
                  0.0 /* epsilon */, &differ, explain)) {
    char *err;
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: trouble comparing:\n%s", me, err);
    airMopError(mop); return 1;
  }
  if (differ) {
    fprintf(stderr, "%s: new and correct (%s) images differ: %s\n",
            me, corrname, explain);
    airMopError(mop); return 1;
  } else {
    printf("%s: all good\n", me);
  }

  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 27
0
int
tend_estimMain(int argc, char **argv, char *me, hestParm *hparm) {
  int pret;
  hestOpt *hopt = NULL;
  char *perr, *err;
  airArray *mop;

  Nrrd **nin, *nin4d, *nbmat, *nterr, *nB0, *nout;
  char *outS, *terrS, *bmatS, *eb0S;
  float soft, scale, sigma;
  int dwiax, EE, knownB0, oldstuff, estmeth, verbose, fixneg;
  unsigned int ninLen, axmap[4], wlsi, *skip, skipNum, skipIdx;
  double valueMin, thresh;

  Nrrd *ngradKVP=NULL, *nbmatKVP=NULL;
  double bKVP, bval;

  tenEstimateContext *tec;

  hestOptAdd(&hopt, "old", NULL, airTypeInt, 0, 0, &oldstuff, NULL,
             "instead of the new tenEstimateContext code, use "
             "the old tenEstimateLinear code");
  hestOptAdd(&hopt, "sigma", "sigma", airTypeFloat, 1, 1, &sigma, "nan",
             "Rician noise parameter");
  hestOptAdd(&hopt, "v", "verbose", airTypeInt, 1, 1, &verbose, "0",
             "verbosity level");
  hestOptAdd(&hopt, "est", "estimate method", airTypeEnum, 1, 1, &estmeth,
             "lls",
             "estimation method to use. \"lls\": linear-least squares",
             NULL, tenEstimate1Method);
  hestOptAdd(&hopt, "wlsi", "WLS iters", airTypeUInt, 1, 1, &wlsi, "1",
             "when using weighted-least-squares (\"-est wls\"), how "
             "many iterations to do after the initial weighted fit.");
  hestOptAdd(&hopt, "fixneg", NULL, airTypeInt, 0, 0, &fixneg, NULL,
             "after estimating the tensor, ensure that there are no negative "
             "eigenvalues by adding (to all eigenvalues) the amount by which "
             "the smallest is negative (corresponding to increasing the "
             "non-DWI image value).");
  hestOptAdd(&hopt, "ee", "filename", airTypeString, 1, 1, &terrS, "",
             "Giving a filename here allows you to save out the tensor "
             "estimation error: a value which measures how much error there "
             "is between the tensor model and the given diffusion weighted "
             "measurements for each sample.  By default, no such error "
             "calculation is saved.");
  hestOptAdd(&hopt, "eb", "filename", airTypeString, 1, 1, &eb0S, "",
             "In those cases where there is no B=0 reference image given "
             "(\"-knownB0 false\"), "
             "giving a filename here allows you to save out the B=0 image "
             "which is estimated from the data.  By default, this image value "
             "is estimated but not saved.");
  hestOptAdd(&hopt, "t", "thresh", airTypeDouble, 1, 1, &thresh, "nan",
             "value at which to threshold the mean DWI value per pixel "
             "in order to generate the \"confidence\" mask.  By default, "
             "the threshold value is calculated automatically, based on "
             "histogram analysis.");
  hestOptAdd(&hopt, "soft", "soft", airTypeFloat, 1, 1, &soft, "0",
             "how fuzzy the confidence boundary should be.  By default, "
             "confidence boundary is perfectly sharp");
  hestOptAdd(&hopt, "scale", "scale", airTypeFloat, 1, 1, &scale, "1",
             "After estimating the tensor, scale all of its elements "
             "(but not the confidence value) by this amount.  Can help with "
             "downstream numerical precision if values are very large "
             "or small.");
  hestOptAdd(&hopt, "mv", "min val", airTypeDouble, 1, 1, &valueMin, "1.0",
             "minimum plausible value (especially important for linear "
             "least squares estimation)");
  hestOptAdd(&hopt, "B", "B-list", airTypeString, 1, 1, &bmatS, NULL,
             "6-by-N list of B-matrices characterizing "
             "the diffusion weighting for each "
             "image.  \"tend bmat\" is one source for such a matrix; see "
             "its usage info for specifics on how the coefficients of "
             "the B-matrix are ordered. "
             "An unadorned plain text file is a great way to "
             "specify the B-matrix.\n  **OR**\n "
             "Can say just \"-B kvp\" to try to learn B matrices from "
             "key/value pair information in input images.");
  hestOptAdd(&hopt, "b", "b", airTypeDouble, 1, 1, &bval, "nan",
             "\"b\" diffusion-weighting factor (units of sec/mm^2)");
  hestOptAdd(&hopt, "knownB0", "bool", airTypeBool, 1, 1, &knownB0, NULL,
             "Determines of the B=0 non-diffusion-weighted reference image "
             "is known, or if it has to be estimated along with the tensor "
             "elements.\n "
             "\b\bo if \"true\": in the given list of diffusion gradients or "
             "B-matrices, there are one or more with zero norm, which are "
             "simply averaged to find the B=0 reference image value\n "
             "\b\bo if \"false\": there may or may not be diffusion-weighted "
             "images among the input; the B=0 image value is going to be "
             "estimated along with the diffusion model");
  hestOptAdd(&hopt, "i", "dwi0 dwi1", airTypeOther, 1, -1, &nin, "-",
             "all the diffusion-weighted images (DWIs), as seperate 3D nrrds, "
             "**OR**: One 4D nrrd of all DWIs stacked along axis 0",
             &ninLen, NULL, nrrdHestNrrd);
  hestOptAdd(&hopt, "o", "nout", airTypeString, 1, 1, &outS, "-",
             "output tensor volume");

  mop = airMopNew();
  airMopAdd(mop, hopt, (airMopper)hestOptFree, airMopAlways);
  USAGE(_tend_estimInfoL);
  JUSTPARSE();
  airMopAdd(mop, hopt, (airMopper)hestParseFree, airMopAlways);

  nout = nrrdNew();
  airMopAdd(mop, nout, (airMopper)nrrdNuke, airMopAlways);
  nbmat = nrrdNew();
  airMopAdd(mop, nbmat, (airMopper)nrrdNuke, airMopAlways);

  /* figure out B-matrix */
  if (strcmp("kvp", airToLower(bmatS))) {
    /* its NOT coming from key/value pairs */
    if (!AIR_EXISTS(bval)) {
      fprintf(stderr, "%s: need to specify scalar b-value\n", me);
      airMopError(mop); return 1;
    }
    if (nrrdLoad(nbmat, bmatS, NULL)) {
      airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble loading B-matrix:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
    nin4d = nin[0];
    skip = NULL;
    skipNum = 0;
  } else {
    /* it IS coming from key/value pairs */
    if (1 != ninLen) {
      fprintf(stderr, "%s: require a single 4-D DWI volume for "
              "key/value pair based calculation of B-matrix\n", me);
      airMopError(mop); return 1;
    }
    if (oldstuff) {
      if (knownB0) {
        fprintf(stderr, "%s: sorry, key/value-based DWI info not compatible "
                "with older implementation of knownB0\n", me);
        airMopError(mop); return 1;
      }
    }
    if (tenDWMRIKeyValueParse(&ngradKVP, &nbmatKVP, &bKVP,
                              &skip, &skipNum, nin[0])) {
      airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble parsing DWI info:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
    if (AIR_EXISTS(bval)) {
      fprintf(stderr, "%s: WARNING: key/value pair derived b-value %g "
              "over-riding %g from command-line", me, bKVP, bval);
    }
    bval = bKVP;
    if (ngradKVP) {
      airMopAdd(mop, ngradKVP, (airMopper)nrrdNuke, airMopAlways);
      if (tenBMatrixCalc(nbmat, ngradKVP)) {
        airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
        fprintf(stderr, "%s: trouble finding B-matrix:\n%s\n", me, err);
        airMopError(mop); return 1;
      }
    } else {
      airMopAdd(mop, nbmatKVP, (airMopper)nrrdNuke, airMopAlways);
      if (nrrdConvert(nbmat, nbmatKVP, nrrdTypeDouble)) {
        airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
        fprintf(stderr, "%s: trouble converting B-matrix:\n%s\n", me, err);
        airMopError(mop); return 1;
      }
    }
    /* this will work because of the impositions of tenDWMRIKeyValueParse */
    dwiax = ((nrrdKindList == nin[0]->axis[0].kind ||
              nrrdKindVector == nin[0]->axis[0].kind)
             ? 0
             : ((nrrdKindList == nin[0]->axis[1].kind ||
                 nrrdKindVector == nin[0]->axis[1].kind)
                ? 1
                : ((nrrdKindList == nin[0]->axis[2].kind ||
                    nrrdKindVector == nin[0]->axis[2].kind)
                   ? 2
                   : 3)));
    if (0 == dwiax) {
      nin4d = nin[0];
    } else {
      axmap[0] = dwiax;
      axmap[1] = 1 > dwiax ? 1 : 0;
      axmap[2] = 2 > dwiax ? 2 : 1;
      axmap[3] = 3 > dwiax ? 3 : 2;
      nin4d = nrrdNew();
      airMopAdd(mop, nin4d, (airMopper)nrrdNuke, airMopAlways);
      if (nrrdAxesPermute(nin4d, nin[0], axmap)) {
        airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
        fprintf(stderr, "%s: trouble creating DWI volume:\n%s\n", me, err);
        airMopError(mop); return 1;
      }
    }
  }

  nterr = NULL;
  nB0 = NULL;
  if (!oldstuff) {
    if (1 != ninLen) {
      fprintf(stderr, "%s: sorry, currently need single 4D volume "
              "for new implementation\n", me);
      airMopError(mop); return 1;
    }
    if (!AIR_EXISTS(thresh)) {
      if (tend_estimThresholdFind(&thresh, nbmat, nin4d)) {
        airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
        fprintf(stderr, "%s: trouble finding threshold:\n%s\n", me, err);
        airMopError(mop); return 1;
      }
      /* HACK to lower threshold a titch */
      thresh *= 0.93;
      fprintf(stderr, "%s: using mean DWI threshold %g\n", me, thresh);
    }
    tec = tenEstimateContextNew();
    tec->progress = AIR_TRUE;
    airMopAdd(mop, tec, (airMopper)tenEstimateContextNix, airMopAlways);
    EE = 0;
    if (!EE) tenEstimateVerboseSet(tec, verbose);
    if (!EE) tenEstimateNegEvalShiftSet(tec, fixneg);
    if (!EE) EE |= tenEstimateMethodSet(tec, estmeth);
    if (!EE) EE |= tenEstimateBMatricesSet(tec, nbmat, bval, !knownB0);
    if (!EE) EE |= tenEstimateValueMinSet(tec, valueMin);
    for (skipIdx=0; skipIdx<skipNum; skipIdx++) {
      /* fprintf(stderr, "%s: skipping %u\n", me, skip[skipIdx]); */
      if (!EE) EE |= tenEstimateSkipSet(tec, skip[skipIdx], AIR_TRUE);
    }
    switch(estmeth) {
    case tenEstimate1MethodLLS:
      if (airStrlen(terrS)) {
        tec->recordErrorLogDwi = AIR_TRUE;
        /* tec->recordErrorDwi = AIR_TRUE; */
      }
      break;
    case tenEstimate1MethodNLS:
      if (airStrlen(terrS)) {
        tec->recordErrorDwi = AIR_TRUE;
      }
      break;
    case tenEstimate1MethodWLS:
      if (!EE) tec->WLSIterNum = wlsi;
      if (airStrlen(terrS)) {
        tec->recordErrorDwi = AIR_TRUE;
      }
      break;
    case tenEstimate1MethodMLE:
      if (!(AIR_EXISTS(sigma) && sigma > 0.0)) {
        fprintf(stderr, "%s: can't do %s w/out sigma > 0 (not %g)\n",
                me, airEnumStr(tenEstimate1Method, tenEstimate1MethodMLE),
                sigma);
        airMopError(mop); return 1;
      }
      if (!EE) EE |= tenEstimateSigmaSet(tec, sigma);
      if (airStrlen(terrS)) {
        tec->recordLikelihoodDwi = AIR_TRUE;
      }
      break;
    }
    if (!EE) EE |= tenEstimateThresholdSet(tec, thresh, soft);
    if (!EE) EE |= tenEstimateUpdate(tec);
    if (EE) {
      airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble setting up estimation:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
    if (tenEstimate1TensorVolume4D(tec, nout, &nB0,
                                   airStrlen(terrS) 
                                   ? &nterr 
                                   : NULL, 
                                   nin4d, nrrdTypeFloat)) {
      airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble doing estimation:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
    if (airStrlen(terrS)) {
      airMopAdd(mop, nterr, (airMopper)nrrdNuke, airMopAlways);
    }
  } else {
    EE = 0;
    if (1 == ninLen) {
      EE = tenEstimateLinear4D(nout, airStrlen(terrS) ? &nterr : NULL, &nB0,
                               nin4d, nbmat, knownB0, thresh, soft, bval);
    } else {
      EE = tenEstimateLinear3D(nout, airStrlen(terrS) ? &nterr : NULL, &nB0,
                               (const Nrrd**)nin, ninLen, nbmat,
                               knownB0, thresh, soft, bval);
    }
    if (EE) {
      airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble making tensor volume:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
  }
  if (nterr) {
    /* it was allocated by tenEstimate*, we have to clean it up */
    airMopAdd(mop, nterr, (airMopper)nrrdNuke, airMopAlways);
  }
  if (nB0) {
    /* it was allocated by tenEstimate*, we have to clean it up */
    airMopAdd(mop, nB0, (airMopper)nrrdNuke, airMopAlways);
  }
  if (1 != scale) {
    if (tenSizeScale(nout, nout, scale)) {
      airMopAdd(mop, err=biffGetDone(TEN), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble doing scaling:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
  }
  if (nterr) {
    if (nrrdSave(terrS, nterr, NULL)) {
      airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble writing error image:\n%s\n", me, err);
      airMopError(mop); return 1;
    }
  }
  if (!knownB0 && airStrlen(eb0S)) {
    if (nrrdSave(eb0S, nB0, NULL)) {
      airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble writing estimated B=0 image:\n%s\n",
              me, err);
      airMopError(mop); return 1;
    }
  }

  if (nrrdSave(outS, nout, NULL)) {
    airMopAdd(mop, err=biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: trouble writing:\n%s\n", me, err);
    airMopError(mop); return 1;
  }

  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 28
0
int
main(int argc, char **argv) {
  char *err, *me, *filename;
  Nrrd *nin;
  unsigned int axi;

  me = argv[0];
  if (2 != argc) {
    fprintf(stderr, "usage: %s <filename>\n", me);
    return 1;
  }

  filename = argv[1];

  /* create a nrrd; at this point this is just an empty container */
  nin = nrrdNew();

  /* read in the nrrd from file */
  if (nrrdLoad(nin, filename, NULL)) {
    err = biffGetDone(NRRD);
    fprintf(stderr, "%s: trouble reading \"%s\":\n%s", me, filename, err);
    free(err);
    return 1;
  }

  /* say something about the array */
  printf("%s: \"%s\" is a %d-dimensional nrrd of type %s (%d)\n",
         me, filename, nin->dim,
         airEnumStr(nrrdType, nin->type),
         nin->type);
  for (axi=0; axi<nin->dim; axi++) {
    printf(" axis[%d] size = %u\n", axi, (unsigned int)nin->axis[axi].size);
  }
  printf("%s: the array contains %d elements, each %d bytes in size\n",
         me, (int)nrrdElementNumber(nin), (int)nrrdElementSize(nin));

  /* blow away both the Nrrd struct *and* the memory at nin->data
     (nrrdNix() frees the struct but not the data,
     nrrdEmpty() frees the data but not the struct) */
  nrrdNuke(nin);

  {
    Nrrd *nout;
    unsigned int sx=640, sy=480, xi, yi, idx;
    unsigned char *odata, rr, gg, bb;
    odata = (unsigned char *)(malloc(sx*sy*3));
    for (yi=0; yi<sy; yi++) {
      rr = (unsigned char)(AIR_AFFINE(0, yi, sy, 0, 255));
      for (xi=0; xi<sx; xi++) {
        gg = (unsigned char)(AIR_AFFINE(0, xi, sx, 0, 255));
        bb = (unsigned char)(AIR_AFFINE(0, xi+yi, sx+sy, 0, 255));
        idx = xi + sx*yi;
        odata[0 + 3*idx] = rr;
        odata[1 + 3*idx] = gg;
        odata[2 + 3*idx] = bb;
      }
    }

    //Saves the contents of the buffer as a png image
    //Currently upsidedown
    nout = nrrdNew();
    if (nrrdWrap_va(nout, odata, nrrdTypeUChar, 3,
                    (size_t)3, (size_t)sx, (size_t)sy)
        || nrrdSave("out.png", nout, NULL)) {
      err = biffGetDone(NRRD);
      fprintf(stderr, "%s: trouble wrapping image:\n%s", me, err);
      free(err);
      return 1;
    }
    nrrdNix(nout);
    free(odata);
  }

  return 0;
}
Ejemplo n.º 29
0
int
main(int argc, const char **argv) {
  /* stock variables */
  char me[] = BKEY;
  hestOpt *hopt=NULL;
  hestParm *hparm;
  airArray *mop;
  /* variables specific to this program */
  int negskip, progress;
  Nrrd *nref, *nin;
  size_t *size, ii, nn, tick, pad[2];
  unsigned int axi, refCRC, gotCRC, sizeNum;
  char *berr, *outS[2], stmp[AIR_STRLEN_SMALL], doneStr[AIR_STRLEN_SMALL];
  airRandMTState *rng;
  unsigned int seed, *rdata, printbytes;
  unsigned char *dataUC;
  double time0, time1;
  FILE *fout;

  /* start-up */
  mop = airMopNew();
  hparm = hestParmNew();
  airMopAdd(mop, hparm, (airMopper)hestParmFree, airMopAlways);
  /* learn things from hest */
  hestOptAdd(&hopt, "seed", "N", airTypeUInt, 1, 1, &seed, "42",
             "seed for RNG");
  hestOptAdd(&hopt, "s", "sz0", airTypeSize_t, 1, -1, &size, NULL,
             "sizes of desired output", &sizeNum);
  hestOptAdd(&hopt, "p", "pb pa", airTypeSize_t, 2, 2, pad, "0 0",
             "bytes of padding before, and after, the data segment "
             "in the written data");
  hestOptAdd(&hopt, "ns", "bool", airTypeInt, 0, 0, &negskip, NULL,
             "skipping should be relative to end of file");
  hestOptAdd(&hopt, "pb", "print", airTypeUInt, 1, 1, &printbytes, "0",
             "bytes to print at beginning and end of data, to help "
             "debug problems");
  hestOptAdd(&hopt, "o", "out.data out.nhdr", airTypeString, 2, 2,
             outS, NULL, "output filenames of data and header");
  hestParseOrDie(hopt, argc-1, argv+1, hparm, me, tskipInfo,
                 AIR_TRUE, AIR_TRUE, AIR_TRUE);
  airMopAdd(mop, hopt, (airMopper)hestOptFree, airMopAlways);
  airMopAdd(mop, hopt, (airMopper)hestParseFree, airMopAlways);

  /* generate reference nrrd data */
  nref = nrrdNew();
  airMopAdd(mop, nref, (airMopper)nrrdNuke, airMopAlways);
  if (nrrdMaybeAlloc_nva(nref, nrrdTypeUInt, sizeNum, size)) {
    airMopAdd(mop, berr=biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: error allocating data: %s\n", me, berr);
    airMopError(mop); return 1;
  }
  rng = airRandMTStateNew(seed);
  airMopAdd(mop, rng, (airMopper)airRandMTStateNix, airMopAlways);
  nn = nrrdElementNumber(nref);
  rdata = AIR_CAST(unsigned int *, nref->data);
  fprintf(stderr, "generating data: . . .       "); fflush(stderr);
  time0 = airTime();
  progress = AIR_FALSE;
  tick = nn/100;
  for (ii=0; ii<nn; ii++) {
    rdata[ii] = airUIrandMT_r(rng);
    if (ii && tick && !(ii % tick)) {
      time1 = airTime();
      if (time1 - time0 > 1.0) {
        /* if it took more than a second to do 1% of the thing,
           would be good to generate some progress indication */
        progress = AIR_TRUE;
      }
      if (progress) {
        fprintf(stderr, "%s", airDoneStr(0, ii, nn, doneStr)); fflush(stderr);
      }
    }
  }
  if (progress) {
    fprintf(stderr, "%s\n", airDoneStr(0, ii, nn, doneStr)); fflush(stderr);
  } else {
    fprintf(stderr, "\n");
  }
  fprintf(stderr, "finding reference (big-endian) CRC: "); fflush(stderr);
  refCRC = nrrdCRC32(nref, airEndianBig);
  fprintf(stderr, "%u\n", refCRC);

  /* write data, with padding */
  fprintf(stderr, "saving data . . . "); fflush(stderr);
  if (!(fout = fopen(outS[0], "wb" COMMIT))) {
    fprintf(stderr, "\n%s: couldn't open %s for writing: %s\n", me,
            outS[0], strerror(errno));
    airMopError(mop); return 1;
  }
  airMopAdd(mop, fout, (airMopper)airFclose, airMopAlways);
  for (ii=0; ii<pad[0]; ii++) {
    if (EOF == fputc(1, fout)) {
      fprintf(stderr, "\n%s: error doing pre-padding\n", me);
      airMopError(mop); return 1;
    }
  }
  if (nn != fwrite(nref->data, nrrdElementSize(nref), nn, fout)) {
    fprintf(stderr, "\n%s: error writing data\n", me);
    airMopError(mop); return 1;
  }
  for (ii=0; ii<pad[1]; ii++) {
    if (EOF == fputc(2, fout)) {
      fprintf(stderr, "\n%s: error doing post-padding\n", me);
      airMopError(mop); return 1;
    }
  }
  if (EOF == fflush(fout)) {
    fprintf(stderr, "\n%s: error fflushing data: %s\n", me,
            strerror(errno));
  }
  fprintf(stderr, "\n");
  if (printbytes) {
    size_t bi, rpb, nn;
    char stmp[AIR_STRLEN_SMALL];
    nn = nrrdElementSize(nref)*nrrdElementNumber(nref);
    rpb = AIR_MIN(printbytes, nn);
    dataUC = AIR_CAST(unsigned char *, nref->data);
    fprintf(stderr, "CORRECT %s bytes at beginning:\n",
            airSprintSize_t(stmp, rpb));
    for (bi=0; bi<rpb; bi++) {
      fprintf(stderr, "%x ", dataUC[bi]);
    }
    fprintf(stderr, "...\n");
    fprintf(stderr, "CORRECT %s bytes at end:\n",
            airSprintSize_t(stmp, rpb));
    fprintf(stderr, "...");
    for (bi=nn - rpb; bi<nn; bi++) {
      fprintf(stderr, " %x", dataUC[bi]);
    }
    fprintf(stderr, "\n");
  }
  airMopSingleOkay(mop, fout);
  airMopSingleOkay(mop, nref); nref = NULL;

  /* write header; for now just writing the header directly */
  fprintf(stderr, "writing header . . . \n");
  if (!(fout = fopen(outS[1], "w"))) {
    fprintf(stderr, "%s: couldn't open %s for writing: %s\n", me,
            outS[1], strerror(errno));
    airMopError(mop); return 1;
  }
  airMopAdd(mop, fout, (airMopper)airFclose, airMopAlways);
  fprintf(fout, "NRRD0005\n");
  fprintf(fout, "type: unsigned int\n");
  fprintf(fout, "dimension: %u\n", sizeNum);
  fprintf(fout, "sizes:");
  for (axi=0; axi<sizeNum; axi++) {
    fprintf(fout, " %s", airSprintSize_t(stmp, size[axi]));
  }
  fprintf(fout, "\n");
  fprintf(fout, "endian: %s\n", airEnumStr(airEndian, airMyEndian()));
  fprintf(fout, "encoding: %s\n", airEnumStr(nrrdEncodingType,
                                             nrrdEncodingTypeRaw));
  if (!negskip) {
    if (pad[0]) {
      fprintf(fout, "byte skip: %s\n", airSprintSize_t(stmp, pad[0]));
    }
  } else {
    fprintf(fout, "byte skip: -%s\n", airSprintSize_t(stmp, pad[1]+1));
  }
  fprintf(fout, "data file: %s\n", outS[0]);
  airMopSingleOkay(mop, fout);

  /* read it in, make sure it checks out */
  fprintf(stderr, "reading data . . . \n");
  nin = nrrdNew();
  airMopAdd(mop, nin, (airMopper)nrrdNuke, airMopAlways);
  if (nrrdLoad(nin, outS[1], NULL)) {
    airMopAdd(mop, berr=biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: error reading back in: %s\n", me, berr);
    airMopError(mop); return 1;
  }
  if (printbytes) {
    size_t bi, rpb, nn;
    char stmp[AIR_STRLEN_SMALL];
    nn = nrrdElementSize(nin)*nrrdElementNumber(nin);
    rpb = AIR_MIN(printbytes, nn);
    dataUC = AIR_CAST(unsigned char *, nin->data);
    fprintf(stderr, "FOUND %s bytes at beginning:\n",
            airSprintSize_t(stmp, rpb));
    for (bi=0; bi<rpb; bi++) {
      fprintf(stderr, "%x ", dataUC[bi]);
    }
    fprintf(stderr, "...\n");
    fprintf(stderr, "FOUND %s bytes at end:\n",
            airSprintSize_t(stmp, rpb));
    fprintf(stderr, "...");
    for (bi=nn - rpb; bi<nn; bi++) {
      fprintf(stderr, " %x", dataUC[bi]);
    }
    fprintf(stderr, "\n");
  }
  fprintf(stderr, "finding new CRC . . . \n");
  gotCRC = nrrdCRC32(nin, airEndianBig);
  if (refCRC != gotCRC) {
    fprintf(stderr, "%s: got CRC %u but wanted %u\n", me, gotCRC, refCRC);
    airMopError(mop); return 1;
  }
  fprintf(stderr, "(all ok)\n");

  /* HEY: to test gzip reading, we really want to do a system call to
     gzip compress the data, and write a new header to point to the
     compressed data, and make sure we can read in that just the same */

  airMopOkay(mop);
  return 0;
}
Ejemplo n.º 30
0
int
main(int argc, const char **argv) {
  const char *me;
  Nrrd *nscl;
  double *dscl;
  airArray *mop;
  char *fullname;
  gageContext *igctx[INTERP_KERN_NUM], *bgctx[BLUR_KERN_NUM];
  const NrrdKernel *ikern[INTERP_KERN_NUM] = {
    nrrdKernelBox,
    nrrdKernelTent,
    nrrdKernelBCCubic,
    nrrdKernelCatmullRom,
  };
  double ikparm[INTERP_KERN_NUM][NRRD_KERNEL_PARMS_NUM] = {
    {1.0},
    {1.0},
    {1.0, 0.0, 0.5},
    {AIR_NAN},
  };
  const NrrdKernel *bkern[BLUR_KERN_NUM] = {
    nrrdKernelTent,
    nrrdKernelBSpline3,
    nrrdKernelBSpline5,
    nrrdKernelBCCubic,
    nrrdKernelGaussian,
  };
  const NrrdKernel *bkernD[BLUR_KERN_NUM] = {
    nrrdKernelForwDiff,
    nrrdKernelBSpline3D,
    nrrdKernelBSpline5D,
    nrrdKernelBCCubicD,
    nrrdKernelGaussianD,
  };
  const NrrdKernel *bkernDD[BLUR_KERN_NUM] = {
    nrrdKernelZero,
    nrrdKernelBSpline3DD,
    nrrdKernelBSpline5DD,
    nrrdKernelBCCubicDD,
    nrrdKernelGaussianDD,
  };
  double bkparm[BLUR_KERN_NUM][NRRD_KERNEL_PARMS_NUM] = {
    {1.0},
    {AIR_NAN},
    {AIR_NAN},
    {2.0, 1.0, 0.0},
    {1.2, 5.0},
  };
  const double *ivalAns[INTERP_KERN_NUM], *bvalAns[BLUR_KERN_NUM],
    *bgrdAns[BLUR_KERN_NUM], *bhesAns[BLUR_KERN_NUM];
  int E;
  unsigned int sx, sy, sz, ki;

  AIR_UNUSED(argc);
  me = argv[0];
  mop = airMopNew();

  nscl = nrrdNew();
  airMopAdd(mop, nscl, (airMopper)nrrdNuke, airMopAlways);
  fullname = testDataPathPrefix("fmob-c4h.nrrd");
  airMopAdd(mop, fullname, airFree, airMopAlways);
  if (nrrdLoad(nscl, fullname, NULL)) {
    char *err;
    airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
    fprintf(stderr, "%s: trouble reading data \"%s\":\n%s",
            me, fullname, err);
    airMopError(mop); return 1;
  }
  /* make sure its a double-type volume (assumed below) */
  if (nrrdTypeDouble != nscl->type) {
    fprintf(stderr, "%s: volume type %s != expected type %s\n", me,
            airEnumStr(nrrdType, nscl->type),
            airEnumStr(nrrdType, nrrdTypeDouble));
    airMopError(mop); return 1;
  }
  dscl = AIR_CAST(double *, nscl->data);
  sx = AIR_CAST(unsigned int, nscl->axis[0].size);
  sy = AIR_CAST(unsigned int, nscl->axis[1].size);
  sz = AIR_CAST(unsigned int, nscl->axis[2].size);

  for (ki=0; ki<INTERP_KERN_NUM; ki++) {
    gagePerVolume *gpvl;
    igctx[ki] = gageContextNew();
    airMopAdd(mop, igctx[ki], (airMopper)gageContextNix, airMopAlways);
    gageParmSet(igctx[ki], gageParmRenormalize, AIR_FALSE);
    gageParmSet(igctx[ki], gageParmCheckIntegrals, AIR_TRUE);
    gageParmSet(igctx[ki], gageParmOrientationFromSpacing, AIR_FALSE);
    E = 0;
    if (!E) E |= !(gpvl = gagePerVolumeNew(igctx[ki], nscl, gageKindScl));
    if (!E) E |= gageKernelSet(igctx[ki], gageKernel00,
                               ikern[ki], ikparm[ki]);
    if (!E) E |= gagePerVolumeAttach(igctx[ki], gpvl);
    if (!E) E |= gageQueryItemOn(igctx[ki], gpvl, gageSclValue);
    if (!E) E |= gageUpdate(igctx[ki]);
    if (E) {
      char *err;
      airMopAdd(mop, err = biffGetDone(GAGE), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble %s set-up:\n%s\n", me,
              ikern[ki]->name, err);
      airMopError(mop); return 1;
    }
    ivalAns[ki] = gageAnswerPointer(igctx[ki], gpvl, gageSclValue);
  }

  /* traverse all samples of volume, probing with the interpolating
     kernels, make sure we recover the original values */
  {
    unsigned int xi, yi, zi;
    double pval[INTERP_KERN_NUM], err, rval;
    int pret;
    for (zi=0; zi<sz; zi++) {
      for (yi=0; yi<sy; yi++) {
        for (xi=0; xi<sx; xi++) {
          rval = dscl[xi + sx*(yi + sy*zi)];
          for (ki=0; ki<INTERP_KERN_NUM; ki++) {
            pret = gageProbeSpace(igctx[ki], xi, yi, zi,
                                  AIR_TRUE /* indexSpace */,
                                  AIR_FALSE /* clamp */);
            if (pret) {
              fprintf(stderr, "%s: %s probe error(%d): %s\n", me,
                      ikern[ki]->name, igctx[ki]->errNum, igctx[ki]->errStr);

              airMopError(mop); return 1;
            }
            pval[ki] = *ivalAns[ki];
            err = AIR_ABS(rval - pval[ki]);
            if (err) {
              fprintf(stderr, "%s: interp's [%u,%u,%u] %s probe %f "
                      "!= true %f (err %f)\n", me, xi, yi, zi,
                      ikern[ki]->name, pval[ki], rval, err);
              airMopError(mop); return 1;
            }
          }
        }
      }
    }
  }

  /* set up contexts for non-interpolating (blurring) kernels,
     and their first and second derivatives */
  for (ki=0; ki<BLUR_KERN_NUM; ki++) {
    gagePerVolume *gpvl;
    bgctx[ki] = gageContextNew();
    airMopAdd(mop, bgctx[ki], (airMopper)gageContextNix, airMopAlways);
    gageParmSet(bgctx[ki], gageParmRenormalize, AIR_TRUE);
    gageParmSet(bgctx[ki], gageParmCheckIntegrals, AIR_TRUE);
    gageParmSet(bgctx[ki], gageParmOrientationFromSpacing, AIR_FALSE);
    E = 0;
    if (!E) E |= !(gpvl = gagePerVolumeNew(bgctx[ki], nscl, gageKindScl));
    if (!E) E |= gageKernelSet(bgctx[ki], gageKernel00,
                               bkern[ki], bkparm[ki]);
    if (!E) E |= gageKernelSet(bgctx[ki], gageKernel11,
                               bkernD[ki], bkparm[ki]);
    if (!E) E |= gageKernelSet(bgctx[ki], gageKernel22,
                               bkernDD[ki], bkparm[ki]);
    if (!E) E |= gagePerVolumeAttach(bgctx[ki], gpvl);
    if (!E) E |= gageQueryItemOn(bgctx[ki], gpvl, gageSclValue);
    if (!E) E |= gageQueryItemOn(bgctx[ki], gpvl, gageSclGradVec);
    if (!E) E |= gageQueryItemOn(bgctx[ki], gpvl, gageSclHessian);
    if (!E) E |= gageUpdate(bgctx[ki]);
    if (E) {
      char *err;
      airMopAdd(mop, err = biffGetDone(GAGE), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble %s set-up:\n%s\n", me,
              bkern[ki]->name, err);
      airMopError(mop); return 1;
    }
    fprintf(stderr, "%s radius = %u\n", bkern[ki]->name, bgctx[ki]->radius);
    bvalAns[ki] = gageAnswerPointer(bgctx[ki], gpvl, gageSclValue);
    bgrdAns[ki] = gageAnswerPointer(bgctx[ki], gpvl, gageSclGradVec);
    bhesAns[ki] = gageAnswerPointer(bgctx[ki], gpvl, gageSclHessian);
  }

  {
#define POS_NUM 12
    double xp[POS_NUM], yp[POS_NUM], zp[POS_NUM],
      pos[POS_NUM*POS_NUM*POS_NUM][3], *prbd,
      offs[POS_NUM/2] = {0, 1.22222, 2.444444, 3.777777, 5.88888, 7.55555};
    Nrrd *nprbd, *ncorr;
    unsigned int ii, jj, kk, qlen = 1 + 3 + 9;
    char *corrfn, explain[AIR_STRLEN_LARGE];
    int pret, differ;

    corrfn = testDataPathPrefix("test/probeSclAns.nrrd");
    airMopAdd(mop, corrfn, airFree, airMopAlways);
    ncorr = nrrdNew();
    airMopAdd(mop, ncorr, (airMopper)nrrdNuke, airMopAlways);
    if (nrrdLoad(ncorr, corrfn, NULL)) {
      char *err;
      airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble reading data \"%s\":\n%s",
              me, corrfn, err);
      airMopError(mop); return 1;
    }
    for (ii=0; ii<POS_NUM/2; ii++) {
      xp[ii] = yp[ii] = zp[ii] = offs[ii];
      xp[POS_NUM-1-ii] = AIR_CAST(double, sx)-1.0-offs[ii];
      yp[POS_NUM-1-ii] = AIR_CAST(double, sy)-1.0-offs[ii];
      zp[POS_NUM-1-ii] = AIR_CAST(double, sz)-1.0-offs[ii];
    }
    for (kk=0; kk<POS_NUM; kk++) {
      for (jj=0; jj<POS_NUM; jj++) {
        for (ii=0; ii<POS_NUM; ii++) {
          ELL_3V_SET(pos[ii + POS_NUM*(jj + POS_NUM*kk)],
                     xp[ii], yp[jj], zp[kk]);
        }
      }
    }
    nprbd = nrrdNew();
    airMopAdd(mop, nprbd, (airMopper)nrrdNuke, airMopAlways);
    if (nrrdMaybeAlloc_va(nprbd, nrrdTypeDouble, 3,
                          AIR_CAST(size_t, qlen),
                          AIR_CAST(size_t, BLUR_KERN_NUM),
                          AIR_CAST(size_t, POS_NUM*POS_NUM*POS_NUM))) {
      char *err;
      airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble setting up prbd:\n%s", me, err);
      airMopError(mop); return 1;
    }
    prbd = AIR_CAST(double *, nprbd->data);
    for (ii=0; ii<POS_NUM*POS_NUM*POS_NUM; ii++) {
      for (ki=0; ki<BLUR_KERN_NUM; ki++) {
        pret = gageProbeSpace(bgctx[ki], pos[ii][0], pos[ii][1], pos[ii][2],
                              AIR_TRUE /* indexSpace */,
                              AIR_FALSE /* clamp */);
        if (pret) {
          fprintf(stderr, "%s: %s probe error(%d): %s\n", me,
                  bkern[ki]->name, bgctx[ki]->errNum, bgctx[ki]->errStr);
          airMopError(mop); return 1;
        }
        prbd[0 + qlen*(ki + BLUR_KERN_NUM*(ii))] = bvalAns[ki][0];
        ELL_3V_COPY(prbd + 1 + qlen*(ki + BLUR_KERN_NUM*(ii)), bgrdAns[ki]);
        ELL_9V_COPY(prbd + 4 + qlen*(ki + BLUR_KERN_NUM*(ii)), bhesAns[ki]);
      }
    }
    /* HEY: weirdly, so far its only on Windows (and more than 10 times worse
       on Cygwin) this epsilon needs to be larger than zero, and only for the
       radius 6 Gaussian? */
    if (nrrdCompare(ncorr, nprbd, AIR_FALSE /* onlyData */,
                    8.0e-14 /* epsilon */, &differ, explain)) {
      char *err;
      airMopAdd(mop, err = biffGetDone(NRRD), airFree, airMopAlways);
      fprintf(stderr, "%s: trouble comparing:\n%s", me, err);
      airMopError(mop); return 1;
    }
    if (differ) {
      fprintf(stderr, "%s: probed values not correct: %s\n", me, explain);
      airMopError(mop); return 1;
    } else {
      fprintf(stderr, "all good\n");
    }
  }

  airMopOkay(mop);
  return 0;
}