コード例 #1
0
//------------------------------------------------------------------------------
void LHAnimationNode::nextFrameAndRepeat(){
    
    int curFrame = getCurrentFrame();
    curFrame +=1;
    
    if(curFrame >= getNumberOfFrames()){
        curFrame = 0;
    }
    
    if(curFrame >= 0 && curFrame < getNumberOfFrames()){
        setFrame(curFrame);
    }    
}
コード例 #2
0
//------------------------------------------------------------------------------
void LHAnimationNode::prevFrameAndRepeat(){
    
    int curFrame = getCurrentFrame();
    curFrame -=1;
    
    if(curFrame < 0){
        curFrame = getNumberOfFrames() - 1;        
    }
    
    if(curFrame >= 0 && curFrame < (int)getNumberOfFrames()){
        setFrame(curFrame);
    }        
}
コード例 #3
0
ファイル: floodFill.cpp プロジェクト: ezemiron/bioimagetools
/* -------------------------------------------------------------------------- */
SEXP
fillHull(SEXP x) {
  SEXP res;
  int nprotect = 0;
  int nz;

  // check image validity
  validImage(x,0);
  nz = getNumberOfFrames(x, 0);

  int *dim=INTEGER(GET_DIM(x));
  XYPoint size(dim[0], dim[1]);


  // return itself if nothing to do
  if (size.x <= 0 || size.y <= 0 || nz < 1) return x;
 
  // do fillHull
  PROTECT(res = Rf_duplicate(x));
  nprotect++;
  if (IS_INTEGER(res)) {
    for (int i=0; i < nz; i++) _fillHullT<int>(&(INTEGER(res)[i*size.x*size.y]), size);
  }
  else if (IS_NUMERIC(res)) {
    for (int i=0; i < nz; i++) _fillHullT<double>(&(REAL(res)[i*size.x*size.y]), size);
  }
  
  UNPROTECT (nprotect);
  return res;
}
コード例 #4
0
/*----------------------------------------------------------------------- */
SEXP
lib_erode_dilate (SEXP x, SEXP kernel, SEXP what, SEXP binary) {
    numeric resetTo, * tgt, * src, *kern, min, max;
    int nz, i, j, nprotect;
    int * dim;
    PointXY size, ksize, pt;
    SEXP res;

    validImage(x,0);
    validImage(kernel,0);

    /* value to reset the checked part t */
    if ( INTEGER(what)[0] == DILATE )
        resetTo = 1.0; /* checking background, reseting to 1 */
    else
        resetTo = 0.0; /* checking foreground, reseting to 0 */
    dim = INTEGER ( GET_DIM(x) );
    size.x = dim[0];
    size.y = dim[1];
    nz = getNumberOfFrames(x,0);

    kern = REAL (kernel);
    ksize.x = INTEGER ( GET_DIM(kernel) )[0];
    ksize.y = INTEGER ( GET_DIM(kernel) )[1];
    nprotect = 0;

    PROTECT ( res = Rf_duplicate(x) );
    nprotect++;

    for ( i = 0; i < nz; i++ ) {
        tgt = &( REAL(res)[i * size.x * size.y] );
        src = &( REAL(x)[i * size.x * size.y] );

        if ( ! INTEGER(binary)[0] ) {
            min = max = src[0];
            for ( j = 0; j < size.x * size.y; j++ ) {
                if (src[j] > max)
                    max = src[j];
                if (src[j] < min)
                    min = src[j];
            }
            for ( j = 0; j < size.x * size.y; j++ ) {
                pt = pointFromIndex (j, size.x);
                tgt[j] = _greymatch(kern, &ksize, src, &size, &pt,
                                    INTEGER(what)[0], min , max);
            }
        }
        else {
            for ( j = 0; j < size.x * size.y; j++ ) {
                if ( tgt[j] == resetTo ) continue;
                pt = pointFromIndex (j, size.x);
                if ( !_match(kern, &ksize, src, &size, &pt, resetTo) )
                    tgt[j] = resetTo;
            }
        }
    }
    
    UNPROTECT (nprotect);
    return res;
}
コード例 #5
0
ファイル: MP3Info.cpp プロジェクト: markessien/p2p
int CMP3Info::getBitrate() {

    if (VBitRate) {

        // get average frame size by deviding fileSize by the number of frames
        float medFrameSize = (float)fileSize / (float)getNumberOfFrames();
        
        /* Now using the formula for FrameSizes which looks different,
           depending on which mpeg version we're using, for mpeg v1:
        
           FrameSize = 12 * BitRate / SampleRate + Padding (if there is padding)

           for mpeg v2 the same thing is:

           FrameSize = 144 * BitRate / SampleRate + Padding (if there is padding)

           remember that bitrate is in kbps and sample rate in Hz, so we need to
           multiply our BitRate with 1000.

           For our purpose, just getting the average frame size, will make the
           padding obsolete, so our formula looks like:

           FrameSize = (mpeg1?12:144) * 1000 * BitRate / SampleRate;
        */

        return (int)( 
                     ( medFrameSize * (float)header.getFrequency() ) / 
                     ( 1000.0 * ( (header.getLayerIndex()==3) ? 12.0 : 144.0))
                    );

    }
    else return header.getBitrate();

}
コード例 #6
0
ファイル: floodFill.cpp プロジェクト: 000Nelson000/EBImage
/* -------------------------------------------------------------------------- */
SEXP
floodFill(SEXP x, SEXP point, SEXP col, SEXP tol) {
  int i, nz, *dim;
  int nprotect=0;
  XYPoint pt;
  SEXP res;

  // check image validity
  validImage(x,0);
  nz = getNumberOfFrames(x, 0);
  dim = INTEGER(GET_DIM(x));
  XYPoint size(dim[0], dim[1]);
  if (size.x <= 0 || size.y <= 0) error("image must have positive dimensions");
  if (LENGTH(point) != 2*nz) error("point must have a size of two times the number of frames");
  if (LENGTH(col) != nz) error("color must have the same size as the number of frames");
  
  // initialize result
  PROTECT(res = Rf_duplicate(x));
  nprotect++;
  
  // do the job over images
 for (i=0; i<nz; i++) {
    pt.x = INTEGER(point)[i]-1;
    pt.y = INTEGER(point)[nz+i]-1;
    
    if (IS_NUMERIC(res)) _floodFill<double>(&(REAL(res)[i*size.x*size.y]), size, pt, REAL(col)[i], REAL(tol)[0]);
    if (IS_INTEGER(res)) _floodFill<int>(&(INTEGER(res)[i*size.x*size.y]), size, pt, INTEGER(col)[i], REAL(tol)[0]);
  }

  UNPROTECT (nprotect);
  return res;
}
コード例 #7
0
ファイル: distmap.cpp プロジェクト: aoles/EBImage
// Compute Euclidean (L2)/Manhattan (L1) distance map of matrix _a 
// Input: numeric matrix _a, of size width*height, where 0 is background and everything else is foreground. _a shouldn't contain any NAs
// Input: integer _metric. If 0, will compute Euclidean distance and Manhattan distance otherwise
// Output: distance matrix of same size as _a
SEXP distmap(SEXP _a, SEXP _metric) {
  SEXP res;
  int i,nprotect=0,nz;
  
  // check validity
  validImage(_a,0);
  
  // initialize width, height, dim
  width=INTEGER(GET_DIM(_a))[0];
  height=INTEGER(GET_DIM(_a))[1];
  nz=getNumberOfFrames(_a,0);
  
  // initialize vj, where (i,vj[i]) are the coordinates of the closest background pixel to a(i,j) with vj[i]>=j
  vj=(int *)R_Calloc(height,int);
  
  // initialize d, the output distance matrix
  PROTECT(res = allocVector(REALSXP, XLENGTH(_a)) );
  nprotect++;
  DUPLICATE_ATTRIB(res, _a);
  
  d=REAL(res);
  for (i=0;i<height*width*nz;i++) d[i]=R_PosInf;
  
  // initialize dist, the distance type
  metric=INTEGER(_metric)[0];
  
  // do the job
  int sizexy = height*width;
  int offset = 0;
  
  for (i=0; i<nz; i++, offset+=sizexy) {
    d = &(REAL(res)[offset]);
    
    switch (TYPEOF(_a)) {
    case LGLSXP:
    case INTSXP:
      _distmap<int>( &(INTEGER(_a)[offset]) );
      break;
    case REALSXP:
      _distmap<double>( &(REAL(_a)[offset]) );
      break;
    }
  }
  
  // final square root for Euclidean distance
  d=REAL(res);
  if (metric==0) for (i=0;i<height*width*nz;i++) d[i]=sqrt(d[i]);
  
  R_Free(vj);
  
  UNPROTECT (nprotect);
  return res;
}
コード例 #8
0
ファイル: spatial.c プロジェクト: pmarais/EBImage
SEXP affine(SEXP _a, SEXP _b, SEXP _m, SEXP _filter) {
  int width, height, nz;
  int owidth, oheight;
  int filter;
  double *a, *m, *b;

  // check image validity
  validImage(_a, 0); 

  // initialize width, height, nz
  width = INTEGER(GET_DIM(_a))[0];
  height = INTEGER(GET_DIM(_a))[1];
  nz = getNumberOfFrames(_a, 0);
 
  // initialize a, m, filter
  a = REAL(_a);
  m = REAL(_m);
  filter = INTEGER(_filter)[0];

  // get output image b data
  owidth = INTEGER(GET_DIM(_b))[0];
  oheight = INTEGER(GET_DIM(_b))[1];
  b = REAL(_b);

  // apply transform
  for (int z=0; z<nz; z++) {
    for (int y=0; y<oheight; y++) { 
      for (int x=0; x<owidth; x++) {
        int idx = x + y*owidth + z*owidth*oheight;
        double bg = b[idx];
      	double tx = m[0]*x + m[1]*y + m[2];
      	double ty = m[3]*x + m[4]*y + m[5];
      	int ftx = floor(tx);
      	int fty = floor(ty);
      	double dx = tx-ftx;
      	double dy = ty-fty;
      	double pa = peekpixel(ftx, fty, z, width, height, a, bg);
      	// bilinear filter?
      	if (filter==1) {
      	  double pb = peekpixel(ftx+1, fty, z, width, height, a, bg);
      	  double pc = peekpixel(ftx, fty+1, z, width, height, a, bg);
      	  double pd = peekpixel(ftx+1, fty+1, z, width, height, a, bg);
      	  pa = (1-dy)*(pa*(1-dx) + pb*dx) + dy*(pc*(1-dx) + pd*dx);
      	}
      	b[idx] = pa;
      }
    }
  }

  return _b;
} 
コード例 #9
0
int
Md3Utils::getNumberOfFrames( std::string const& fileName )
{
	fileHandle_t file;
	
	if( FS_FOpenFileByMode( fileName.c_str(), &file, FS_READ ) >= 0 ) 
	{
		int frames = getNumberOfFrames( file );
		FS_FCloseFile( file );
		return frames;
	}

	Com_Printf( "Unable to open file %s\n", fileName.c_str() );

	return 0;
}
コード例 #10
0
/* -------------------------------------------------------------------------- */
SEXP
bwlabel(SEXP x) {
  int i, kx, ky, nz, *dim;
  int nprotect=0;
  double index;
  XYPoint pt;
  SEXP res;

  // check image validity
  validImage(x,0);
  nz = getNumberOfFrames(x, 0);
  dim = INTEGER(GET_DIM(x));
  XYPoint size(dim[0], dim[1]);
  if (size.x <= 0 || size.y <= 0) error("image must have positive dimensions");
  
  // initialize result
  PROTECT(res = Rf_duplicate(x));
  nprotect++;  

  // assuming binary images: 0 is background and everything else foreground
  // foreground is converted here to -1.0
  // NO NO NO: I've splitted some labelled objects, I want to relabel the parts,
  // so I put them to -REAL(res)[i] instead of -1, otherwise they will be merged
  // as they are connected
  for (i=0; i<nz*size.x*size.y; i++) {
    if (REAL(res)[i]!=0.0) REAL(res)[i]=-REAL(res)[i];
  }
  
  // do the job over images
  // every pixel equals with R_PosInf is filled with an increasing index, starting from 1
  for (i=0; i<nz; i++) {
    index = 1.0;
    for (ky=0; ky<size.y ; ky++) {
      for (kx=0; kx<size.x ; kx++) {
          if ( REAL(res)[kx + ky*size.x + i*size.x*size.y] < 0 ) {
	  pt.x = kx;
	  pt.y = ky;
	  _floodFill<double>(&(REAL(res)[i*size.x*size.y]), size, pt, index, 0.0);
	  index = index + 1.0;
	}
      }
    }
  }

  UNPROTECT (nprotect);
  return res;
}
コード例 #11
0
ファイル: distmap.c プロジェクト: 000Nelson000/EBImage
// Compute Euclidean (L2)/Manhattan (L1) distance map of matrix _a 
// Input: numeric matrix _a, of size width*height, where 0 is background and everything else is foreground. _a shouldn't contain any NAs
// Input: integer _metric. If 0, will compute Euclidean distance and Manhattan distance otherwise
// Output: distance matrix of same size as _a
SEXP distmap(SEXP _a, SEXP _metric) {
  SEXP res;
  int i,nprotect=0,nz;

  // check validity
  validImage(_a,0);

  // initialize width, height, dim
  width=INTEGER(GET_DIM(_a))[0];
  height=INTEGER(GET_DIM(_a))[1];
  nz=getNumberOfFrames(_a,0);

 // initialize vj, where (i,vj[i]) are the coordinates of the closest background pixel to a(i,j) with vj[i]>=j
  vj=(int *)R_Calloc(height,int);

  // initialize a
  a=REAL(_a);

  // initialize d, the output distance matrix
  PROTECT(res=Rf_duplicate(_a));
  nprotect++;
  d=REAL(res);
  for (i=0;i<height*width*nz;i++) d[i]=R_PosInf;
  
  // initialize dist, the distance type
  metric=INTEGER(_metric)[0];
   
  // do the job
  for (i=0;i<nz;i++) {
    distmap_onesided(1);
    distmap_onesided(0);
    a=a+height*width;
    d=d+height*width;
  }

  // final square root for Euclidean distance
  d=REAL(res);
  if (metric==0) for (i=0;i<height*width*nz;i++) d[i]=sqrt(d[i]);

  // free vj
  R_Free(vj);

  UNPROTECT (nprotect);
  return res;
}
コード例 #12
0
ファイル: openni2_grabber.cpp プロジェクト: taketwo/radical
  void open(const char* uri) {
    if (device.open(uri) != openni::STATUS_OK)
      BOOST_THROW_EXCEPTION(GrabberException("Failed to open device")
                            << GrabberException::ErrorInfo(openni::OpenNI::getExtendedError()));

    if (color_stream.create(device, openni::SENSOR_COLOR) != openni::STATUS_OK)
      BOOST_THROW_EXCEPTION(GrabberException("Failed to create color stream")
                            << GrabberException::ErrorInfo(openni::OpenNI::getExtendedError()));

    openni::VideoMode color_mode;
    color_mode.setFps(30);
    color_mode.setResolution(color_image_resolution.width, color_image_resolution.height);
    color_mode.setPixelFormat(openni::PIXEL_FORMAT_RGB888);
    color_stream.setVideoMode(color_mode);
    color_image_size = color_image_resolution.width * color_image_resolution.height * 3;
    color_stream.setMirroringEnabled(false);

    if (color_stream.start() != openni::STATUS_OK) {
      color_stream.destroy();
      BOOST_THROW_EXCEPTION(GrabberException("Failed to start color stream")
                            << GrabberException::ErrorInfo(openni::OpenNI::getExtendedError()));
    }

    streams.push_back(&color_stream);

    auto control = device.getPlaybackControl();
    if (control != nullptr) {
      // This is a file, make sure we get every frame
      control->setSpeed(-1.0f);
      control->setRepeatEnabled(false);
      num_frames = control->getNumberOfFrames(color_stream);
      is_file = true;
      if (num_frames == -1)
        BOOST_THROW_EXCEPTION(GrabberException("Unable to determine number of frames in ONI file"));
    }
  }
コード例 #13
0
ファイル: clahe.c プロジェクト: aoles/EBImage
SEXP clahe (SEXP x, SEXP _uiNrX, SEXP _uiNrY, SEXP _uiNrBins, SEXP _fCliplimit, SEXP _keepRange) {
  int nx, ny, nz, i, j;
  unsigned int uiNrX, uiNrY, uiNrBins;
  float fCliplimit;
  int keepRange;
  double *src, *tgt;
  SEXP res;
  
  kz_pixel_t min = 0, max = uiNR_OF_GREY-1;
  kz_pixel_t *img;
  
  double maxPixelValue = uiNR_OF_GREY-1;
  
  PROTECT( res = allocVector(REALSXP, XLENGTH(x)) );
  DUPLICATE_ATTRIB(res, x);
  
  nx = INTEGER(GET_DIM(x))[0];
  ny = INTEGER(GET_DIM(x))[1];
  nz = getNumberOfFrames(x, 0);
  
  uiNrX = INTEGER(_uiNrX)[0];
  uiNrY = INTEGER(_uiNrY)[0];
  uiNrBins = INTEGER(_uiNrBins)[0];
  fCliplimit = REAL(_fCliplimit)[0];
  keepRange = LOGICAL(_keepRange)[0];
  
  img = R_Calloc(nx*ny, kz_pixel_t);
  
  // process channels separately
  for(j = 0; j < nz; j++) {
    src = &(REAL(x)[j*nx*ny]);
    tgt = &(REAL(res)[j*nx*ny]);
    
    if (keepRange) {
      min = uiNR_OF_GREY-1;
      max = 0;
    }
    
    // convert frame to CLAHE-compatible format
    for (i = 0; i < nx*ny; i++) {
      double el = src[i];
      
      // clip
      if (el < 0.0) el = 0;
      else if (el > 1.0) el = 1.0;
      // convert to int
      kz_pixel_t nel = (kz_pixel_t) round(el * maxPixelValue);
      
      if (keepRange) {
        if (nel < min) min = nel;
        if (nel > max) max = nel;
      }
      
      img[i] = nel;
    }
    
    int val = CLAHE (img, (unsigned int) nx, (unsigned int) ny,
                     min, max, uiNrX, uiNrY, uiNrBins, fCliplimit);
    
    // translate internal error codes
    switch (val) {
    case -1:
      error("# of regions x-direction too large");
      break;
    case -2:
      error("# of regions y-direction too large");
      break;
    case -3:
      error("x-resolution no multiple of 'nx'");
      break;
    case -4:
      error("y-resolution no multiple of 'ny'");
      break;
    case -5:
      error("maximum too large");
      break;
    case -6:
      error("minimum equal or larger than maximum");
      break;
    case -7:
      error("at least 4 contextual regions required");
      break;
    case -8:
      error("not enough memory! (try reducing 'bins')");
      break;
    }
    
    // convert back to [0:1] range
    for (i = 0; i < nx*ny; i++) {
      tgt[i] = (double) img[i] / maxPixelValue;
    }
  }
  
  R_Free(img);
  
  UNPROTECT(1);
  
  return res;
}
コード例 #14
0
ファイル: watershed.cpp プロジェクト: pmarais/EBImage
/*----------------------------------------------------------------------- */
SEXP
watershed (SEXP x, SEXP _tolerance, SEXP _ext) {
    SEXP res;
    int im, i, j, nx, ny, nz, ext, nprotect = 0;
    double tolerance;

    nx = INTEGER ( GET_DIM(x) )[0];
    ny = INTEGER ( GET_DIM(x) )[1];
    nz = getNumberOfFrames(x,0);
    tolerance = REAL( _tolerance )[0];
    ext = INTEGER( _ext )[0];

    PROTECT ( res = Rf_duplicate(x) );
    nprotect++;
  
    int * index = new int[ nx * ny ];

    for ( im = 0; im < nz; im++ ) {

        double * src = &( REAL(x)[ im * nx * ny ] );
        double * tgt = &( REAL(res)[ im * nx * ny ] );

        /* generate pixel index and negate the image -- filling wells */
        for ( i = 0; i < nx * ny; i++ ) {
	  tgt[ i ] = -src[ i ];
	  index[ i ] = i;
        }
        /* from R includes R_ext/Utils.h */
        /* will resort tgt as well */
        rsort_with_index( tgt, index, nx * ny );
        /* reassign tgt as it was reset above but keep new index */
        for ( i = 0; i < nx * ny; i++ )
            tgt[ i ] = -src[ i ];

        SeedList seeds;  /* indexes of all seed starting points, i.e. lowest values */

        IntList  equals; /* queue of all pixels on the same gray level */
        IntList  nb;     /* seed values of assigned neighbours */
        int ind, indxy, nbseed, x, y, topseed = 0;
        IntList::iterator it;
        TheSeed newseed;
        PointXY pt;
        bool isin;
        /* loop through the sorted index */
        for ( i = 0; i < nx * ny && src[ index[i] ] > BG; ) {
            /* pool a queue of equally lowest values */
            ind = index[ i ];
            equals.push_back( ind );
            for ( i = i + 1; i < nx * ny; ) {
                if ( src[ index[i] ] != src[ ind ] ) break;
                equals.push_back( index[i] );
                i++;
            }
            while ( !equals.empty() ) {
                /* first check through all the pixels if we can assign them to
                 * existing objects, count checked and reset counter on each assigned
                 * -- exit when counter equals queue length */
                for ( j = 0; j < (int) equals.size(); ) {
		  if ((j%1000)==0) R_CheckUserInterrupt();
                    ind = equals.front();
                    equals.pop_front();
                    /* check neighbours:
                     * - if exists one, assign
                     * - if two or more check what should be combined and assign to the steepest
                     * - if none, push back */
                    /* reset j to 0 every time we assign another pixel to restart the loop */
                    nb.clear();
                    pt = pointFromIndex( ind, nx );
                    /* determine which neighbour we have, push them to nb */
                    for ( x = pt.x - ext; x <= pt.x + ext; x++ )
                        for ( y = pt.y - ext; y <= pt.y + ext; y++ ) {
                            if ( x < 0 || y < 0 || x >= nx || y >= ny || (x == pt.x && y == pt.y) ) continue;
                            indxy = x + y * nx;
                            nbseed = (int) tgt[ indxy ];
                            if ( nbseed < 1 ) continue;
                            isin = false;
                            for ( it = nb.begin(); it != nb.end() && !isin; it++ )
                                if ( nbseed == *it ) isin = true;
                            if ( !isin ) nb.push_back( nbseed );
                        }
                    if ( nb.size() == 0 ) {
                        /* push the pixel back and continue with the next one */
                        equals.push_back( ind );
                        j++;
                        continue;
                    }
                    tgt[ ind ] = check_multiple(tgt, src, ind, nb, seeds, tolerance, nx, ny );
                    /* we assigned the pixel, reset j to restart neighbours detection */
                    j = 0;
                }
                /* now we have assigned all that we could */
                if ( !equals.empty() ) {
                    /* create a new seed for one pixel only and go back to assigning neighbours */
                    topseed++;
                    newseed.index = equals.front();
                    newseed.seed = topseed;
                    equals.pop_front();
                    tgt[ newseed.index ] = topseed;
                    seeds.push_back( newseed );
                }
            } // assigning equals
        } // sorted index

        /* now we need to reassign indexes while some seeds could be removed */
        double * finseed = new double[ topseed ];
        for ( i = 0; i < topseed; i++ )
            finseed[ i ] = 0;
        i = 0;
        while ( !seeds.empty() ) {
            newseed = seeds.front();
            seeds.pop_front();
            finseed[ newseed.seed - 1 ] = i + 1;
            i++;
        }
        for ( i = 0; i < nx * ny; i++ ) {
            j = (int) tgt[ i ];
            if ( 0 < j && j <= topseed )
                tgt[ i ] = finseed[ j - 1 ];
        }
        delete[] finseed;

    } // loop through images

    delete[] index;

    UNPROTECT (nprotect);
    return res;
}
コード例 #15
0
TEST(NexusFileReaderTest, nexus_read_number_frames) {
  extern std::string testDataPath;
  auto fileReader = NexusFileReader(testDataPath + "SANS_test.nxs");
  EXPECT_EQ(18132, fileReader.getNumberOfFrames());
}
コード例 #16
0
//------------------------------------------------------------------------------
bool LHAnimationNode::isAtLastFrame(){
    return (getNumberOfFrames()-1 == getCurrentFrame());
}
コード例 #17
0
/*----------------------------------------------------------------------- */
SEXP
thresh (SEXP x, SEXP param) {
    int dx, dy, nx, ny, nz, nprotect, * dim, xi, yi, u, v, i;
    int sx, ex, sy, ey;
    double offset, * tgt, * src, sum, mean, nFramePix;
    SEXP res;
    
    validImage(x,0);

    dim = INTEGER ( GET_DIM(x) );
    nx = dim[0];
    ny = dim[1];
    nz = getNumberOfFrames(x,0);

    dx = (int)( REAL(param)[0] );
    dy = (int)( REAL(param)[1] );
    offset = REAL(param)[2];
    nprotect = 0;
    nFramePix = (2 * dx + 1) * (2 * dy + 1);

    PROTECT ( res = Rf_duplicate(x) );
    nprotect++;

    for ( i = 0; i < nz; i++ ) {
        tgt = &( REAL(res)[ i * nx * ny ] );
        src = &( REAL(x)[ i * nx * ny ] );
        for ( yi = dy; yi < ny - dy; yi++ ) {
            sum = 0.0;
            for ( xi = dx; xi < nx - dx; xi++ ) {
                if ( xi == dx) {
                /* first position in a row -- collect new sum */
                    for ( u = xi - dx; u <= xi + dx; u++ )
                        for ( v = yi - dy; v <= yi + dy; v++ )
                            sum += src [u + v * nx];
                }
                else {
                /* frame moved in the row, modify sum */
                    for ( v = yi - dy; v <= yi + dy; v++ )
                        sum += src [xi + dx + v * nx] - src [ xi - dx - 1 + v * nx];
                }
                /* calculate threshold and update tgt data */
                mean = sum / nFramePix + offset;
                sx = xi;
                ex = xi;
                sy = yi;
                ey = yi;
                if ( xi == dx ) {
                    /* left */
                    sx = 0;
                    ex = dx;
                }
                else
                if ( xi == nx - dx - 1 ) {
                    /* right */
                    sx = nx - dx - 1;
                    ex = nx - 1;
                }
                if ( yi == dy ) {
                    /* top */
                    sy = 0;
                    ey = dy;
                }
                else
                if ( yi == ny - dy - 1 ) {
                    /* bottom */
                    sy = ny - dy - 1;
                    ey = ny - 1;
                }
                if ( ex - sx > 0 || ey - sy > 0 ) {
                    for ( u = sx; u <= ex; u++ )
                        for ( v = sy; v <= ey; v++ )
                            tgt [u + v * nx] = ( src [u + v * nx] < mean ) ? BG : FG;
                }
                else /* thresh current pixel only */
                    tgt [xi + yi * nx] = ( src [xi + yi * nx] < mean ) ? BG : FG;
            }
        }
    }

    UNPROTECT (nprotect);
    return res;
}
コード例 #18
0
void
_showInGtkWindow (SEXP xx, SEXP caption) {
    int nx, ny, nz, width, height;
    udata *dat;
    SEXP dim;
    GdkPixbuf * pxbuf;
    GtkWidget *evBox, *winWG, *vboxWG, *tbarWG, *scrollWG,
      *btnZoomInWG, *btnZoomOutWG, *btnZoomOneWG,
      *btnNextWG, *btnPrevWG;
    GtkObject *hAdjustment;
    GtkIconSize iSize;
    if ( !GTK_OK )
        error ( "failed to initialize GTK+, use 'read.image' instead" );

    dim = GET_DIM (xx);
    nx = INTEGER (dim)[0];
    ny = INTEGER (dim)[1];
    nz = getNumberOfFrames(xx,1);

    dat=g_new(udata,1);
    dat->nx=nx;
    dat->ny=ny;
    dat->nz=nz;
    dat->x=0;
    dat->y=0;
    dat->zoom=1.0;
    dat->index=0;
    dat->hSlider=NULL;
    dat->xx=xx;
   
    // xx is preserved from garbage collection til the windows is closed
    R_PreserveObject(xx);

    /* create pixbuf from image data */
    pxbuf=newPixbufFromSEXP(xx,0);

    if ( pxbuf == NULL )
        error ( "cannot copy image data to display window" );

    /* create imae display */
    dat->imgWG = gtk_image_new_from_pixbuf (pxbuf);
    g_object_unref (pxbuf);

    /* create main window */
    winWG =  gtk_window_new (GTK_WINDOW_TOPLEVEL);
    if ( caption != R_NilValue )
      gtk_window_set_title ( GTK_WINDOW(winWG), CHAR( asChar(caption) ) );
    else
      gtk_window_set_title ( GTK_WINDOW(winWG), "R image display" );
    /* set destroy event handler for the window */
    g_signal_connect ( G_OBJECT(winWG), "delete-event", G_CALLBACK(onWinDestroy), dat);

    /* create controls and set event handlers */
    /* create general horizontal lyout with a toolbar and add it to the window */
    vboxWG = gtk_vbox_new (FALSE, 0);
    gtk_container_add ( GTK_CONTAINER(winWG), vboxWG);

    /* create toolbar and push it to layout */
    tbarWG = gtk_toolbar_new ();
    gtk_box_pack_start ( GTK_BOX(vboxWG), tbarWG, FALSE, FALSE, 0);

    // add a horizontal slider
    if (nz>1) {
      hAdjustment=gtk_adjustment_new(1,1,nz,1,1,0);
      dat->hSlider=gtk_hscale_new(GTK_ADJUSTMENT(hAdjustment));
      gtk_scale_set_digits(GTK_SCALE(dat->hSlider),0);
      gtk_box_pack_start(GTK_BOX(vboxWG), dat->hSlider, FALSE,FALSE, 0);
      gtk_signal_connect(GTK_OBJECT(dat->hSlider),"value-changed", GTK_SIGNAL_FUNC(onSlide), dat);
    }

    /* create scrollbox that occupies and extends and push it to layout */
    scrollWG = gtk_scrolled_window_new (NULL, NULL);
    gtk_box_pack_start ( GTK_BOX(vboxWG), scrollWG, TRUE, TRUE, 5);
    gtk_scrolled_window_set_policy ( GTK_SCROLLED_WINDOW(scrollWG), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
    /* add image to event box */
    evBox = gtk_event_box_new();
    gtk_container_add(GTK_CONTAINER(evBox), dat->imgWG);
    /* add image to scroll */
    gtk_scrolled_window_add_with_viewport ( GTK_SCROLLED_WINDOW(scrollWG), evBox);
    gtk_signal_connect(GTK_OBJECT(gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(scrollWG))),"value-changed", GTK_SIGNAL_FUNC(onScroll), dat);
    gtk_signal_connect(GTK_OBJECT(gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(scrollWG))),"value-changed", GTK_SIGNAL_FUNC(onScroll), dat);
    
    /* create status bar and push it to layout */
    dat->stbarWG = gtk_statusbar_new ();
    gtk_box_pack_start ( GTK_BOX(vboxWG), dat->stbarWG, FALSE, FALSE, 0);

    /* add zoom buttons */
    iSize = gtk_toolbar_get_icon_size ( GTK_TOOLBAR(tbarWG) );
    btnZoomInWG = (GtkWidget *) gtk_tool_button_new ( gtk_image_new_from_stock("gtk-zoom-in", iSize), "Zoom in" );
    gtk_container_add ( GTK_CONTAINER(tbarWG), btnZoomInWG);
    g_signal_connect ( G_OBJECT(btnZoomInWG), "clicked", G_CALLBACK(onZoomInPress), dat);
    btnZoomOutWG = (GtkWidget *) gtk_tool_button_new ( gtk_image_new_from_stock("gtk-zoom-out", iSize), "Zoom out" );
    gtk_container_add ( GTK_CONTAINER(tbarWG), btnZoomOutWG);
    g_signal_connect ( G_OBJECT(btnZoomOutWG), "clicked", G_CALLBACK(onZoomOutPress), dat);
    btnZoomOneWG = (GtkWidget *) gtk_tool_button_new ( gtk_image_new_from_stock("gtk-yes", iSize), "1:1");
    gtk_container_add ( GTK_CONTAINER(tbarWG), btnZoomOneWG);
    g_signal_connect ( G_OBJECT(btnZoomOneWG), "clicked", G_CALLBACK(onZoomOnePress), dat);

    /* add browsing buttons */
    if ( nz > 1 ) {
        btnPrevWG = (GtkWidget *) gtk_tool_button_new ( gtk_image_new_from_stock("gtk-go-back", iSize), "Previous" );
        gtk_container_add ( GTK_CONTAINER(tbarWG), btnPrevWG);
        g_signal_connect ( G_OBJECT(btnPrevWG), "clicked", G_CALLBACK(onPrevImPress), dat);
        btnNextWG = (GtkWidget *) gtk_tool_button_new ( gtk_image_new_from_stock("gtk-go-forward", iSize), "Next" );
        gtk_container_add ( GTK_CONTAINER(tbarWG), btnNextWG);
        g_signal_connect ( G_OBJECT(btnNextWG), "clicked", G_CALLBACK(onNextImPress), dat);
    }
    
    gtk_signal_connect( GTK_OBJECT(evBox), "motion-notify-event", GTK_SIGNAL_FUNC(onMouseMove), dat);
    gtk_widget_set_events(evBox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK );
    
    /* resize to fit image */
    width = gdk_screen_get_width ( gdk_screen_get_default() );
    height = gdk_screen_get_height ( gdk_screen_get_default () );
    width = ( nx + 20 < width - 20 ) ? ( nx + 20 ) : ( width - 20 );
    height = ( ny + 80 < height - 20 ) ? ( ny + 80 ) : ( height - 20 );
    if ( width < 150 ) width = 150;
    if ( height < 100 ) height = 100;
    gtk_window_resize ( GTK_WINDOW(winWG), width, height);

    /* show window */
    gtk_widget_show_all (winWG);
    updateStatusBar(dat);
    gdk_flush();
}
コード例 #19
0
ファイル: main.cpp プロジェクト: vrai-group/re-identification
int main(int argc, char* argv[])
{
    try {
        openni::OpenNI::initialize();
        openni::Device device;

        const char* deviceURI = openni::ANY_DEVICE;
        if (argc > 1) {
            deviceURI = argv[1];
        }

        auto ret = device.open(deviceURI);


        if (ret != openni::STATUS_OK) {
            throw std::runtime_error("can't open device");
        }

        auto playbackControl = device.getPlaybackControl();
        playbackControl->setRepeatEnabled(false);

        openni::VideoStream colorStream;
        colorStream.create(device, openni::SensorType::SENSOR_COLOR);
        colorStream.start();

        openni::VideoStream depthStream;
        depthStream.create(device, openni::SensorType::SENSOR_DEPTH);
        depthStream.start();

        openni::VideoFrameRef depthFrame;
        openni::VideoFrameRef colorFrame;

        cv::Mat colorImage;
        cv::Mat depthImage;
        cv::Mat depthImageBack;
        cv::Mat depthImageFore;
        cv::Mat depthoutputImage;
        cv::Mat maskImage;
        cv::Mat zeroMaskBack;

        std::string videoID(device.getDeviceInfo().getUri());

        videoID.erase(videoID.begin(), videoID.end() - 7);
        videoID.erase(videoID.begin() + 3, videoID.end());

        std::string pathBase(device.getDeviceInfo().getUri());
        pathBase.erase(pathBase.end() - 11, pathBase.end());

        auto idPerson = std::atoi(videoID.c_str());

        auto oldNoFrame = 0;
        auto NoFrame = 1;

        do {
            // depth frame
            depthStream.readFrame(&depthFrame);
            if (depthFrame.isValid()) {
                depthImage = cv::Mat(depthFrame.getVideoMode().getResolutionY(),
                                     depthFrame.getVideoMode().getResolutionX(),
                                     CV_16UC1, (unsigned short*)depthFrame.getData());

                depthImage.convertTo(depthoutputImage, CV_8UC1, 255.0/10000);
                cv::cvtColor(depthoutputImage, depthoutputImage, CV_GRAY2BGR);
            }

            // color frame
            colorStream.readFrame(&colorFrame);
            if (colorFrame.isValid()) {
                colorImage = cv::Mat(colorStream.getVideoMode().getResolutionY(),
                                     colorStream.getVideoMode().getResolutionX(),
                                     CV_8UC3, (char*)colorFrame.getData());
                cv::cvtColor(colorImage, colorImage, CV_RGB2BGR);
            }

            // process
            if (NoFrame == 1) {
                depthImageBack = depthImage.clone();
                depthImageFore = cv::Mat::zeros(depthImage.rows,depthImage.cols, CV_16UC1);
                zeroMaskBack = depthImageBack == 0;
                std::cout << videoID <<";NULL;NULL;NULL;NULL;"
                          << depthFrame.getTimestamp() << ";" << depthFrame.getFrameIndex() << ";"
                          << colorFrame.getTimestamp() << ";" << colorFrame.getFrameIndex() << std::endl;

                std::string pathImgBack;
                pathImgBack = pathBase + "img/background.png";
                cv::imwrite(pathImgBack, colorImage);
                pathImgBack = pathBase + "depth/background.png";
                cv::imwrite(pathImgBack, depthImage);

            } else {
                depthImageFore = depthImageBack - depthImage;
                maskImage = depthImageFore > MIN_HIGH & depthImageFore < MAX_HIGH;

                // morfology
                maskImage = morphology(maskImage);

                // find contours
                std::vector<std::vector<cv::Point> > contours;
                cv::findContours(maskImage.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

                auto noPerson = 0;

                for (auto c_iter = contours.begin(); c_iter != contours.end(); ++c_iter) {
                    auto area = cv::contourArea(*c_iter);
                    // filtering by area
                    if (area > (MIN_AREA)) {
                        noPerson++;
                    } else {
                        // clean vector of contours
                        contours.erase(c_iter--);
                    }
                }

                if (contours.size()) {
                    oldNoFrame = NoFrame;
                    // Draw contours
                    cv::Mat drawing = cv::Mat::zeros(maskImage.size(), CV_8UC1);
                    for(auto i = 0; i < contours.size(); ++i)
                    {
                        cv::drawContours(drawing, contours, i, 255, -1);
                    }

                    cv::Mat zeroMask = depthImage == 0;
                    cv::Mat zeroMaskTot;
                    cv::bitwise_or(zeroMask, zeroMaskBack, zeroMaskTot);
                    drawing = drawing - zeroMaskTot;

                    cv::Mat depthImageFilter;
                    depthImageFore.copyTo(depthImageFilter, drawing);

                    // cv::imshow("depthImageFilter", depthImageFilter);
                    // cv::imshow("drawing", drawing);

                    if (NoFrame % 10 == 0) {
                        std::string pathImgColor;
                        pathImgColor = pathBase + "img/" + std::to_string(depthFrame.getFrameIndex()) + ".png";
                        cv::imwrite(pathImgColor, colorImage);

                        std::string pathImgDepth;
                        pathImgDepth = pathBase + "depth/" + std::to_string(depthFrame.getFrameIndex()) + ".png";
                        cv::imwrite(pathImgDepth, depthImage);

                        std::string pathImgMask;
                        pathImgMask = pathBase + "mask/" + std::to_string(depthFrame.getFrameIndex()) + ".png";
                        cv::imwrite(pathImgMask, drawing);
                    }

                    double maxValue;
                    cv::Point maxPoint;

                    cv::minMaxLoc(depthImageFilter, NULL, &maxValue, NULL, &maxPoint);

                    maxValue += int(depthImageBack.at<unsigned short>(cv::Point(depthImageBack.cols/2-1, depthImageBack.rows/2-1))) - depthImageBack.at<unsigned short>(maxPoint);

                    std::cout << videoID  << ";" << std::setfill('0') << std::setw(3) << idPerson << ";"
                              << maxValue << ";"
                              << maxPoint.x << ";"
                              << maxPoint.y << ";"
                              << depthFrame.getTimestamp() << ";" << depthFrame.getFrameIndex() << ";"
                              << colorFrame.getTimestamp() << ";" << colorFrame.getFrameIndex() << std::endl;
                    // cv::circle(colorImage, maxPoint, 5, cv::Scalar(255, 50, 0), -1, 8, 0);
                } else {
                    if (!(oldNoFrame - NoFrame + 1)) {
                        ++idPerson;
                    }
                    std::cout << videoID <<";NULL;NULL;NULL;NULL;"
                              << depthFrame.getTimestamp() << ";" << depthFrame.getFrameIndex() << ";"
                              << colorFrame.getTimestamp() << ";" << colorFrame.getFrameIndex() << std::endl;
                }
            }
            // cv::imshow("Color Camera", colorImage);
            // cv::imshow("Depth CameraFore", depthImageFore);

            int key = cv::waitKey(10);
            if (key == 'q') {
                break;
            }

            ++NoFrame;
        } while (depthFrame.getFrameIndex() < playbackControl->getNumberOfFrames(depthStream) && colorFrame.getFrameIndex() < playbackControl->getNumberOfFrames(colorStream));

        depthStream.destroy();
        colorStream.destroy();
        device.close();

        openni::OpenNI::shutdown();
        return 0;
    }
    catch ( std::exception& ) {
        std::cout << openni::OpenNI::getExtendedError() << std::endl;
    }
}
コード例 #20
0
void ossimRpfToc::writeFrameFileIndexSection(ossimRpfFrameFileIndexSubsection* frameFileSubSection,
                                             std::ifstream& dotRpfStr,
                                             std::ofstream& dotTocStr)
{
   static const char MODULE[] = "ossimRpfToc::writeFrameFileIndexSection";

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n";
   }

   const ossim_uint16 FRAME_FILE_INDEX_RECORD_LENGTH = 33;
   ossim_uint32 frames = getNumberOfFrames(dotRpfStr);
   ossim_uint32 pathnameRecordOffset = FRAME_FILE_INDEX_RECORD_LENGTH * frames;

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "frames: " << frames << "\n";
   }
   
   if ( !dotRpfStr.good() )
   {
      // see if we can clear it.  Someone might have hit end of file(eof).
      dotRpfStr.clear();
   }

   dotRpfStr.seekg(0, ios_base::beg);

   std::string line;
   ossimFilename file;
   ossimRpfFrameFileIndexRecord record;
   ossim_uint32 framesWritten = 0;

   // Eat the first line which is the bounding rect line
   std::getline(dotRpfStr, line);

   while( dotRpfStr.good() )
   {
      std::getline(dotRpfStr, line);

      if ( dotRpfStr.good() )
      {
         if ( getFile(line, file) )
         {
            if ( frameFileSubSection->getFrameFileIndexRecordFromFile(file.file(), record) )
            {
               // Always single entry.
               record.setBoundaryRecNumber(0);
               
               record.setPathnameRecordOffset(pathnameRecordOffset);
               record.writeStream(dotTocStr);
               ++framesWritten;

               if ( traceDebug() )
               {
                  ossimNotify(ossimNotifyLevel_DEBUG) << "wrote record:\n" << record << "\n";
               }
            }
         }
      }
   }

   // Now set the path record.
   ossimFilename d = file.path();
   ossimString s = "./";
   s += d.file();
   s += "/";
   ossimRpfPathnameRecord pathRecord;
   pathRecord.setPathName(s);
   pathRecord.writeStream(dotTocStr);

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "frames written: " << framesWritten
         << "\nwrote record:\n" << pathRecord
         << "\n";
   }

   dotRpfStr.clear();
   dotRpfStr.seekg(0, ios_base::beg);

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl;
   }
}
コード例 #21
0
void ossimRpfToc::createTocAndCopyFrames( const ossimFilename& dotRpfFile,
                                          const ossimFilename& outputDir )
{
   static const char MODULE[] = "ossimRpfToc::createTocAndCopyFrames";

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered..."
         << "\ndot rpf file:      " << dotRpfFile
         << "\noutput directory:  " << outputDir
         << "\n";
   }

   if ( outputDir.expand().exists() == false )
   {
      if ( !outputDir.createDirectory(true, 0775) )
      {
         std::string e = MODULE;
         e += " ERROR:\nCould not create directory: ";
         e+= outputDir.c_str();
         throw ossimException(e);
      }
   }

   // Open the dot rpf file.
   std::ifstream* dotRpfStr = new std::ifstream;
   dotRpfStr->open(dotRpfFile, ios_base::in);
   if ( !dotRpfStr->good() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += dotRpfFile.c_str();
      throw ossimException(e);
   }

   ossimFilename sourceADotTocFile = getSourceTocFile(*dotRpfStr);
   if ( sourceADotTocFile.empty() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not deduce source a.toc file!";
      throw ossimException(e);
   }
   
   // Open the source a.toc file. Note the true flag is to keep the file header.
   ossimRefPtr<ossimRpfToc> sourceADotToc = new ossimRpfToc;
   if ( sourceADotToc->parseFile(sourceADotTocFile, true) != ossimErrorCodes::OSSIM_OK )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
 
      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   ossimRefPtr<const ossimNitfFileHeader> sourceNitfFileHdr = sourceADotToc->getNitfFileHeader();
   if ( !sourceNitfFileHdr.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;        

      std::string e = MODULE;
      e += " ERROR:\nCould not get nitf file header from: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }
   
   ossimRefPtr<const ossimRpfHeader> sourceRpfHdr = sourceADotToc->getRpfHeader();
   if ( !sourceRpfHdr.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      
      std::string e = MODULE;
      e += " ERROR:\nCould not get rpf header from: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   // Get the boundary rect sub header from the source a.toc.
   ossimRefPtr<ossimRpfBoundaryRectSectionSubheader> boundaryRectSectionSubheader =
      sourceRpfHdr->getNewBoundaryRectSectSubheader(sourceADotTocFile);
   if ( !boundaryRectSectionSubheader.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull boundary rect sub header from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }   

   // Get the boundary rect table from the source a.toc.
   ossimRefPtr<ossimRpfBoundaryRectTable> boundaryRectTable =
      sourceRpfHdr->getNewBoundaryRectTable(sourceADotTocFile);
   if ( !boundaryRectTable.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      
      std::string e = MODULE;
      e += " ERROR:\nCould not pull boundary rect table from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }
   
   // Get the frame file subheader from the source a.toc.
   ossimRefPtr<ossimRpfFrameFileIndexSectionSubheader> frameFileSubHeader =
      sourceRpfHdr->getNewFrameFileIndexSectionSubheader(sourceADotTocFile);
   if ( !frameFileSubHeader.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull frame file sub header from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   // Get the frame file subsection from the source a.toc.
   ossimRefPtr<ossimRpfFrameFileIndexSubsection> frameFileSubSection =
      sourceRpfHdr->getNewFileIndexSubsection(sourceADotTocFile);
   if ( !frameFileSubSection.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull frame file sub section from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e); 
   }
   
   // Open the output file to write to.
   const ossimFilename A_DOT_TOC_FILE = "a.toc";
   ossimFilename dotTocFile = outputDir.dirCat(A_DOT_TOC_FILE);
   std::ofstream* dotTocStr = new std::ofstream;
   dotTocStr->open( dotTocFile.c_str(), ios::out|ios::binary );
   if ( !dotTocStr->good() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      delete dotTocStr;
      dotTocStr =0;

      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += dotTocFile.c_str();
      throw ossimException(e);
   }
   
   // Variables used throughout:
   ossimRefPtr<ossimProperty> prop = new ossimStringProperty();
   ossimString field;
   ossimString s;
   std::streampos fileHeaderLength = 0;
   std::streampos fileLength = 0;
      
   ossimRefPtr<ossimNitfFileHeaderV2_0> fileHdr = new ossimNitfFileHeaderV2_0();
   
   // Set the CLEVEL:
   s = "01";
   fileHdr->setComplexityLevel(s);
   
   // Set the OSTAID:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OSTAID_KW);
   fileHdr->setProperty(prop);
   
   // Set the FDT (date):
   fileHdr->setDate();
   
   // Set the FTITLE:
   s = "a.toc";
   fileHdr->setTitle(s);
   
   // Set the FSCLAS:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCLAS_KW);
   fileHdr->setProperty(prop);
   
   // Set the FSCODE:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCODE_KW);
   fileHdr->setProperty(prop);
   
   // Set the FSCTLH:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCTLH_KW);
   fileHdr->setProperty(prop);
   
   // Set the ONAME:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::ONAME_KW);
   fileHdr->setProperty(prop);
   
   // Set the OPHONE:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OPHONE_KW);
   fileHdr->setProperty(prop);
   
   // Add the rpf header.
   ossimRpfHeader* rpfHdr = new ossimRpfHeader( *(sourceRpfHdr.get()) );
   
   ossimRefPtr<ossimNitfRegisteredTag> rpfHdrRp = rpfHdr;
   ossimNitfTagInformation rpfHdrInfo(rpfHdrRp);
   fileHdr->addTag(rpfHdrInfo);
   
   //---
   // Write it out...
   // The first write will be with an rpfheader with no location sections just
   // to see where the end of the file header is.
   //---
   fileHdr->writeStream(*dotTocStr);
   
   //---
   // End of file header. Get the header length. This will also be the
   // start of the location section.
   //---
   std::streampos pos = dotTocStr->tellp();
   std::streamoff locationSectionOffset = pos;
   
   // Set the header length:
   fileHdr->setHeaderLength( static_cast<ossim_uint64>(locationSectionOffset) );
   
   // Set the location of the location section.
   rpfHdr->setLocationSectionPos(locationSectionOffset);

   // Set the file name.
   rpfHdr->setFilename(A_DOT_TOC_FILE);
   
   // Add the component location records to the header.
   ossimRpfLocationSection* locSec = rpfHdr->getLocationSection();
   
   // Clear the records copied from the source a.toc.
   locSec->clearFields();
   
   //---
   // Set the length of the locSec to 74.  The record itself is 14 bytes plus
   // an additional 60 bytes for six location records ten bytes each.
   //---
   const ossim_uint16 LOCATION_SECTION_SIZE = 74;
   locSec->setLocationSectionLength(LOCATION_SECTION_SIZE);
   
   // Set the offset which 14 bytes to get to the first record.
   locSec->setLocationTableOffset(14);
   
   // Six records:
   locSec->setNumberOfComponentLocationRecords(6);
   
   // Each record 10 bytes:
   locSec->setLocationRecordLength(10);
   
   // Don't know the aggregate length yet.
   
   ossimRpfComponentLocationRecord locRec;
   
   // Note: See ossimRpfConstants for enum ossimRpfComponentId
   
   const ossim_uint32 RPFHDR_SIZE = 48;
   const ossim_uint32 LOCATION_SECTION_OFFSET = static_cast<ossim_uint32>(locationSectionOffset);
   const ossim_uint32 BOUNDARY_SUBHEADER_SIZE = 8;
   const ossim_uint32 BOUNDARY_RECORD_SIZE = 132;
   const ossim_uint32 FILE_SUBHEADER_SIZE = 13;
   // const ossim_uint32 = ;
   
   // Record 1 RPFHDR location:
   ossim_uint32 rpfHdrOffset = 0;
   if ( fileHdr->getTag(rpfHdrInfo, "RPFHDR") )
   {
      rpfHdrOffset = rpfHdrInfo.getTagDataOffset();
   }

   locRec.m_componentId = OSSIM_RPF_HEADER_COMPONENT; // 128
   locRec.m_componentLength = RPFHDR_SIZE;
   locRec.m_componentLocation = static_cast<ossim_uint32>(rpfHdrInfo.getTagDataOffset());
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)<< "rpf hdr offset: " << rpfHdrOffset << "\n";
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 2 location section:
   locRec.m_componentId = OSSIM_RPF_LOCATION_COMPONENT; // 129
   locRec.m_componentLength = LOCATION_SECTION_SIZE;
   locRec.m_componentLocation = LOCATION_SECTION_OFFSET;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 3 boundary rect sub header section:
   locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_SECTION_SUBHEADER; // 148
   locRec.m_componentLength = BOUNDARY_SUBHEADER_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + LOCATION_SECTION_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Capture the location.
   std::streamoff boundaryRectPosition = locRec.m_componentLocation;
   
   // Record 4 boundary rect table:
   locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_TABLE; // 149
   locRec.m_componentLength = BOUNDARY_RECORD_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_SUBHEADER_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 5 file index sub header:
   locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER; // 150
   locRec.m_componentLength = FILE_SUBHEADER_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_RECORD_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
    
   // Record 6 file index sub header:
   locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SUBSECTION; // 151
   locRec.m_componentLength = 0;  // need to calculate.
   locRec.m_componentLocation = locRec.m_componentLocation + FILE_SUBHEADER_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Seek back and re-write...
   dotTocStr->seekp(0, ios::beg);
   fileHdr->writeStream(*dotTocStr);
   
   dotTocStr->seekp(boundaryRectPosition, ios::beg);

   // Only writing one entry:
   boundaryRectSectionSubheader->setNumberOfEntries(1);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "writing boundaryRectSectionSubheader:\n" << *(boundaryRectSectionSubheader.get())
         << "\n";
   }

   //---
   // Write the boundary rectangle section.  This includes the subheader and subsection.
   // These coorespond to location records 3 and 4 above.
   //---
   boundaryRectSectionSubheader->writeStream(*dotTocStr);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) 
         << "Original boundaryRectTable:\n" << *(boundaryRectTable.get()) << "\n";
   }

   ossim_uint32 entry;
   if ( getCorespondingEntry( frameFileSubSection.get(), *dotRpfStr, entry ) )
   {
      ossimRpfBoundaryRectRecord boundaryRectRecord;
      if ( boundaryRectTable->getEntry( entry, boundaryRectRecord) )
      {
         if ( traceDebug() )
         {
            ossimNotify(ossimNotifyLevel_DEBUG) 
               << "writing boundaryRectTable:\n" << boundaryRectRecord << "\n";
         }
         
         boundaryRectRecord.writeStream(*dotTocStr);
      }
      else
      {
         std::string e = MODULE;
         e += " ERROR:\nCould not get bounding rect record for entry: ";
         e += ossimString::toString(entry).c_str();
         throw ossimException(e);
      }
   }
   else
   {
      std::string e = MODULE;
      e += " ERROR:\nCould not deduce entry from frame list!";
      throw ossimException(e);
   }

   frameFileSubHeader->setNumberOfIndexRecords( getNumberOfFrames(*dotRpfStr) );
   frameFileSubHeader->setNumberOfPathnameRecords(1);
   const ossim_uint16 FRAME_FILE_INDEX_RECORD_LENGTH = 33;
   frameFileSubHeader->setIndexRecordLength( FRAME_FILE_INDEX_RECORD_LENGTH );

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "writing frameFileSubHeader:\n" << *(frameFileSubHeader.get()) << "\n";
   }
   frameFileSubHeader->writeStream( *dotTocStr );

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "writing frameFileSubSection:\n";
   }

   std::streamoff frameFileIndexSectionStartPos = dotTocStr->tellp();
   
   writeFrameFileIndexSection(frameFileSubSection.get(), *dotRpfStr, *dotTocStr);
   
   std::streamoff endOfFilePos = dotTocStr->tellp();

   // Update the location section length for the frame file index section.
   locSec->getLocationRecordList()[5].m_componentLength =
      static_cast<ossim_uint32>(endOfFilePos - frameFileIndexSectionStartPos);

   // Update the length of all location sections.
   locSec->setComponentAggregateLength(
      static_cast<ossim_uint32>(endOfFilePos) - rpfHdr->getLocationSectionLocation() );
   

   fileHdr->setFileLength(static_cast<ossim_uint64>(endOfFilePos));
   dotTocStr->seekp(0, ios::beg);
   fileHdr->writeStream(*dotTocStr);

   ossimNotify(ossimNotifyLevel_DEBUG) << "Wrote file: " << dotTocFile << "\n";

   // Copy the frames to the output directory.
   copyFrames(*dotRpfStr, outputDir);

   // Cleanup:
   delete dotRpfStr;
   dotRpfStr = 0;
   delete dotTocStr;
   dotTocStr =0;
}
コード例 #22
0
void ossimRpfToc::copyFrames(std::ifstream& dotRpfStr, const ossimFilename& outputDir)
{
   static const char MODULE[] = "ossimRpfToc::copyFrames";

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n";
   }

   ossim_uint32 frames = getNumberOfFrames(dotRpfStr);

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "frames to copy: " << frames << "\n";
   }
   
   if ( !dotRpfStr.good() )
   {
      // see if we can clear it.  Someone might have hit end of file(eof).
      dotRpfStr.clear();
   }

   dotRpfStr.seekg(0, ios_base::beg);

   std::string line;
   ossimFilename file;
   ossimFilename destinationFile;
   ossimFilename subDir;
   ossim_uint32 framesCopied = 0;
            
   // Eat the first line which is the bounding rect line
   std::getline(dotRpfStr, line);

   // Get the second line which is first file. 
   std::getline(dotRpfStr, line);

   // Get the file name and make the sub directory if needed.
   if ( getFile(line, file) )
   {
      destinationFile = outputDir;
      subDir = file.path();
      subDir = subDir.file();
      destinationFile = destinationFile.dirCat( subDir );
      
      // This is output_dir/subdir.  See if subdir exist:
      if ( !destinationFile.exists() )
      {
         destinationFile.createDirectory();
      }
   }

   // Start over:
   if ( !dotRpfStr.good() )
   {
      // see if we can clear it.  Someone might have hit end of file(eof).
      dotRpfStr.clear();
   }
   dotRpfStr.seekg(0, ios_base::beg);
   
   // Eat the first line which is the bounding rect line
   std::getline(dotRpfStr, line);
   
   while( dotRpfStr.good() )
   {
      std::getline(dotRpfStr, line);

      if ( dotRpfStr.good() )
      {
         if ( getFile(line, file) )
         {
            destinationFile = outputDir;
            subDir = file.path();
            subDir = subDir.file();
            destinationFile = destinationFile.dirCat( subDir );
            destinationFile = destinationFile.dirCat( file.file() );

            if ( file.copyFileTo(destinationFile) )
            {
               ++framesCopied;
            }
            if ( traceDebug() )
            {
               ossimNotify(ossimNotifyLevel_DEBUG) << "Copied frame: " << destinationFile << "\n";
            }
         }
      }
   }

   ossimNotify(ossimNotifyLevel_NOTICE) << "Frames copied: " << framesCopied << std::endl;

   dotRpfStr.clear();
   dotRpfStr.seekg(0, ios_base::beg);

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl;
   }
}