void setDimensions(struct dsr hdr, int *nx, int *ny, int *nz, int *nt, float *dx, float *dy, float *dz, short *dataType, int v) { if ( hdr.hk.sizeof_hdr != 348 ) swapByteOrder( (char *) &hdr.dime.datatype, sizeof(short) ); *dataType = hdr.dime.datatype; if ( hdr.hk.sizeof_hdr != 348 ) { swapN( (char *) hdr.dime.dim , 16); for(int i=0; i<8; i++) swapByteOrder( (char *) &hdr.dime.pixdim[i], sizeof(float) ); } *ny=hdr.dime.dim[2]; *nx=hdr.dime.dim[1]; *nz=hdr.dime.dim[3]; *nt=hdr.dime.dim[4]; if(v) printf("\n\tMatrix size = %d x %d x %d x %d (voxels)", *nx, *ny, *nz, *nt); *dx=hdr.dime.pixdim[1]; *dy=hdr.dime.pixdim[2]; *dz=hdr.dime.pixdim[3]; if(v) printf("\n\tVoxel size = %8.6f x %8.6f x %8.6f (mm3)\n", *dx,*dy,*dz); }
void swapByteOrder(unsigned short* input, unsigned int num) { unsigned int c; for (c=0; c<num; c++) { swapByteOrder(input[c]); } }
Hash256 DatabaseHelper::txGetHash(TxId txId) { Hash256 txHash; boost::lock_guard<boost::recursive_mutex> guard(cacheMutex); if (txCache2.exists(txId)) { txHash = txCache2.get(txId); } else { auto buffer = bufferTLS.get(); if (buffer == NULL) { bufferTLS.reset(buffer = new std::string()); } char searchKey[1 + sizeof(TxId)]; searchKey[0] = (uint8_t)DatabaseKeyHeader::Tx; *((TxId*) &searchKey[1]) = swapByteOrder(txId); if (!db->Get(leveldb::ReadOptions(), leveldb::Slice((const char*)searchKey, sizeof(searchKey)), buffer).ok()) { for (int i = 0; i < sizeof(txHash.value); ++i) txHash.value[i] = 0; return txHash; } txHash = *(Hash256*)buffer->c_str(); txCache2.put(txId, txHash); } return txHash; }
// --------------------------------------------------------------------------- // BigEndian write // --------------------------------------------------------------------------- // std::ostream & BigEndian::write( std::ostream & s, long howmany, int size, const char * stuff ) { // swap byte order if nec. if ( ! bigEndianSystem() && size > 1 ) { // use a temporary vector to automate storage: std::vector<char> v( stuff, stuff + (howmany*size) ); for ( long i = 0; i < howmany; ++i ) { swapByteOrder( & v[i*size], size ); } s.write( &v[0], howmany*size ); } else { // read the bytes into data: s.write( stuff, howmany*size ); } // check stream state: if ( ! s.good() ) Throw( FileIOException, "File write failed. " ); return s; }
// --------------------------------------------------------------------------- // BigEndian read // --------------------------------------------------------------------------- // std::istream & BigEndian::read( std::istream & s, long howmany, int size, char * putemHere ) { // read the bytes into data: s.read( putemHere, howmany*size ); // check stream state: if ( s ) { // if the stream is still in a good state, then // the correct number of bytes must have been read: Assert( s.gcount() == howmany*size ); // swap byte order if nec. if ( ! bigEndianSystem() && size > 1 ) { for ( long i = 0; i < howmany; ++i ) { swapByteOrder( putemHere + (i*size), size ); } } } return s; }
bool makeVariablesBigEndian( float* data, int size ) { if( !data || (size<1)) return false; if (data && isLittleEndian()) swapByteOrder(data, size* size* size); return true; }
qint64 K3b::fromLe64( char* data ) { #ifdef WORDS_BIGENDIAN // __BYTE_ORDER == __BIG_ENDIAN return swapByteOrder( *((qint64*)data) ); #else return *((qint64*)data); #endif }
bool DatabaseHelper::blockLoad(uint32_t blockIndex, DbBlock& dbBlock) { uint8_t hash2[1 + sizeof(uint32_t)]; hash2[0] = (uint8_t) DatabaseKeyHeader::Block; *((uint32_t*) &hash2[1]) = swapByteOrder(blockIndex); std::string dbText; if (db->Get(leveldb::ReadOptions(), leveldb::Slice((const char*) hash2, sizeof(hash2)), &dbText).ok()) { Deserialize(dbText, dbBlock); return true; } return false; }
int read_datatype(char *filename) { struct dsr hdr; char hdrfile[1024]; char imgfile[1024]; get_analyze_file_names(filename, hdrfile, imgfile); read_analyze_hdr(&hdr, hdrfile); if ( hdr.hk.sizeof_hdr != 348 ) { swapByteOrder( (char *) &hdr.dime.datatype, sizeof(short) ); } return( (int)(hdr.dime.datatype) ); }
float read_dz(const char *filename) { struct dsr hdr; char hdrfile[1024]; char imgfile[1024]; get_analyze_file_names(filename, hdrfile, imgfile); read_analyze_hdr(&hdr, hdrfile); if ( hdr.hk.sizeof_hdr != 348 ) { for(int i=0; i<8; i++) swapByteOrder( (char *) &hdr.dime.pixdim[i], sizeof(float) ); } return( hdr.dime.pixdim[3] ); }
TxId DatabaseHelper::txSave(leveldb::WriteBatch& batch, const Hash256& txHash, const DbTransaction& dbTx) { auto buffer = bufferTLS.get(); if (buffer == NULL) { bufferTLS.reset(buffer = new std::string()); } auto index = txGetOrCreateId(txHash); Serialize(*buffer, dbTx); char searchKey2[1 + sizeof(TxId)]; searchKey2[0] = (uint8_t)DatabaseKeyHeader::Tx; *(TxId*) &searchKey2[1] = swapByteOrder(index); batch.Put(leveldb::Slice((const char*)searchKey2, sizeof(searchKey2)), *buffer); return index; }
//! Reads double data from the file into the supplied buffer bool MrcFileImpl::readDoubleData(double* buffer, unsigned int numSamples, unsigned int variable) { if (m_OpenMode == Write) return false; if (variable>=m_NumVariables || m_VariableTypes[variable]!=Double) { // no good return false; } prepareToRead(variable); // read in the data if ((int)(numSamples*sizeof(double)) != m_File.readBlock((char*)buffer, numSamples*sizeof(double))) { return false; } if (m_MustSwap) swapByteOrder(buffer, numSamples); incrementPosition(numSamples); return true; }
//! Writes float data to the file from the supplied buffer bool MrcFileImpl::writeFloatData(float* buffer, unsigned int numSamples, unsigned int variable) { if (m_OpenMode == Read) return false; if (variable>=m_NumVariables || m_VariableTypes[variable]!=Float) { // no good return false; } prepareToRead(variable); if (m_MustSwap) swapByteOrder(buffer, numSamples); // write out the data if (((int)numSamples*sizeof(float)) != m_File.writeBlock((char*)buffer, numSamples*sizeof(float))) { return false; } incrementPosition(numSamples); return true; }
short *readNiftiImage(const char *filename, DIM *dim, int flg) { FILE *fp; nifti_1_header hdr; int swapflg=0; int nv; char *imgname; short *im=NULL; // ensure that the specified image has either a .hdr or a .nii extension if( !checkNiftiFileExtension(filename) ) { errorMessage("Error: The image filename must have a `.hdr' or `.nii' extension."); } fp = fopen(filename,"r"); if(fp==NULL) { errorMessage("Error: I have trouble opening the specified image file."); } if( fread(&hdr, sizeof(nifti_1_header), 1, fp) != 1 ) { errorMessage("Error: I have trouble reading the specified image file."); } fclose(fp); // if dim[0] is outside range 1..7, then the header information // needs to be byte swapped appropriately if(hdr.dim[0]<1 || hdr.dim[0]>7) { swapflg=1; } if(swapflg) { swapByteOrder( (char *)&(hdr.sizeof_hdr), sizeof(int)); swapByteOrder( (char *)&(hdr.dim[0]), sizeof(short)); for(int i=1; i<=hdr.dim[0]; i++) { swapByteOrder( (char *)&(hdr.dim[i]), sizeof(short)); } swapByteOrder( (char *)&(hdr.datatype), sizeof(short)); for(int i=0; i<=hdr.dim[0]; i++) { swapByteOrder( (char *)&(hdr.pixdim[i]), sizeof(float)); } swapByteOrder( (char *)&(hdr.vox_offset), sizeof(float)); } dim->nx = hdr.dim[1]; dim->ny = hdr.dim[2]; dim->nz = hdr.dim[3]; dim->dx = hdr.pixdim[1]; dim->dy = hdr.pixdim[2]; dim->dz = hdr.pixdim[3]; nv = hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; im = (short *)calloc(nv, sizeof(short)); if(im==NULL) { errorMessage("Error: Memory allocation problem in readNiftiImage() function."); } { int L; L = strlen(filename); imgname = (char *)calloc(L+1, 1); strcpy(imgname, filename); if(imgname[L-3]=='h' && imgname[L-2]=='d' && imgname[L-1]=='r') { imgname[L-3]='i'; imgname[L-2]='m'; imgname[L-1]='g'; } } if(flg) { printf("Reading %s ...\n", imgname); printf("\tmatrix size = %d x %d x %d\n", dim->nx, dim->ny, dim->nz); printf("\tvoxel size = %5.3f x %5.3f x %5.3f\n", dim->dx, dim->dy, dim->dz); printf("\tdata type = %d\n", hdr.datatype); } // if it is ANALYZE format, we want vox_offset to be zero if( hdr.magic[0]!='n' || (hdr.magic[1]!='+' && hdr.magic[1]!='i') || hdr.magic[2]!='1') { hdr.vox_offset = 0; } fp = fopen(imgname,"r"); if(fp==NULL) { errorMessage("Error: I have trouble opening the specified image file."); } if( fseek(fp, (long)hdr.vox_offset, SEEK_SET) != 0 ) { errorMessage("Error: I have trouble reading the specified image file."); } if( hdr.datatype == DT_SIGNED_SHORT || hdr.datatype == DT_UINT16) { if( fread(im, sizeof(short), nv, fp) != nv ) { errorMessage("Error: I have trouble reading the specified image file."); } if(swapflg) { swapN( (char *)im, nv*2); } } else if( hdr.datatype == DT_UNSIGNED_CHAR || hdr.datatype == DT_INT8 ) { unsigned char *dum; dum = (unsigned char *)calloc( nv, sizeof(unsigned char)); if(dum==NULL) { errorMessage("Error: Memory allocation problem in readNiftiImage() function."); } if (fread(dum, sizeof(unsigned char), nv, fp) != nv ) { errorMessage("Error: I have trouble reading the specified image file."); } for(int i=0; i<nv; i++) im[i]=(short)dum[i]; free(dum); } else { errorMessage("Error: Sorry, but this program can only handle image types `short' and `unsigned char'."); } fclose(fp); return(im); }
// returns 0 on failure, 1 on success int readNKI(char *filename, nki *image) { int nv; FILE *fp; // send error message if the file doesn't exist if(access(filename,F_OK)==-1) { printf("\n\nError: %s does not exist!\n\n",filename); return(0); } // send error message if the file has no read permission if(access(filename,R_OK)==-1) { printf("\n\nError: read permission to %s denied!\n\n",filename); return(0); } if( isNKI(filename)==0 ) { printf("\n\nError: %s does not seem to be in NKI format!\n\n",filename); return(0); } fp=fopen(filename,"r"); if(fp==NULL) { printf("\n\nCannot open %s!\n\n",filename); return(0); } fread(image->id,sizeof(char),3,fp); fread(&image->flg,sizeof(short),1,fp); fread(&image->hs,sizeof(short),1,fp); fread(&image->nx,sizeof(int),1,fp); fread(&image->ny,sizeof(int),1,fp); fread(&image->nz,sizeof(int),1,fp); fread(&image->nt,sizeof(int),1,fp); if(image->flg!=1) { swapByteOrder( (char *)&image->hs, sizeof(short)); swapByteOrder( (char *)&image->nx, sizeof(int)); swapByteOrder( (char *)&image->ny, sizeof(int)); swapByteOrder( (char *)&image->nz, sizeof(int)); swapByteOrder( (char *)&image->nt, sizeof(int)); } fread(&image->dx,sizeof(double),1,fp); fread(&image->dy,sizeof(double),1,fp); fread(&image->dz,sizeof(double),1,fp); fread(&image->dt,sizeof(double),1,fp); if(image->flg!=1) { swapByteOrder( (char *)&image->dt, sizeof(double)); swapByteOrder( (char *)&image->dz, sizeof(double)); swapByteOrder( (char *)&image->dx, sizeof(double)); swapByteOrder( (char *)&image->dy, sizeof(double)); } fread(image->cntrv, sizeof(double), 3, fp); fread(image->nrmlv, sizeof(double), 3, fp); fread(image->rowv, sizeof(double), 3, fp); fread(image->colv, sizeof(double), 3, fp); if(image->flg!=1) { swapByteOrder( (char *)&image->cntrv[0], sizeof(double)); swapByteOrder( (char *)&image->cntrv[1], sizeof(double)); swapByteOrder( (char *)&image->cntrv[2], sizeof(double)); swapByteOrder( (char *)&image->nrmlv[0], sizeof(double)); swapByteOrder( (char *)&image->nrmlv[1], sizeof(double)); swapByteOrder( (char *)&image->nrmlv[2], sizeof(double)); swapByteOrder( (char *)&image->rowv[0], sizeof(double)); swapByteOrder( (char *)&image->rowv[1], sizeof(double)); swapByteOrder( (char *)&image->rowv[2], sizeof(double)); swapByteOrder( (char *)&image->colv[0], sizeof(double)); swapByteOrder( (char *)&image->colv[1], sizeof(double)); swapByteOrder( (char *)&image->colv[2], sizeof(double)); } fread(&image->datatype, sizeof(char), 1, fp); fread(&image->u, sizeof(char), 1, fp); fread(&image->c, sizeof(char), 1, fp); //printf("Center Vector = (%7.5lf %7.5lf %7.5lf)\n", image->cntrv[0],image->cntrv[1], image->cntrv[2]); //printf("Normal Vector = (%7.5lf %7.5lf %7.5lf)\n", image->nrmlv[0],image->nrmlv[1], image->nrmlv[2]); //printf("Row Vector = (%7.5lf %7.5lf %7.5lf)\n", image->rowv[0],image->rowv[1], image->rowv[2]); //printf("Column Vector = (%7.5lf %7.5lf %7.5lf)\n", image->colv[0],image->colv[1], image->colv[2]); if( fseek(fp, image->hs, SEEK_SET) != 0 ) { printf("\n\nError: improper seek operation!\n\n"); return(0); } nv = image->nx*image->ny*image->nz*image->nt; image->cim = NULL; image->sim = NULL; image->iim = NULL; image->fim = NULL; image->dim = NULL; switch (image->datatype) { case 0: image->cim =(char *)calloc(nv,sizeof(char)); if(image->cim == NULL) { printf("\n\nError: memory allocation.\n\n"); return(0);} nv=fread(image->cim, sizeof(char), nv, fp); break; case 1: image->sim =(short *)calloc(nv,sizeof(short)); if(image->sim == NULL) { printf("\n\nError: memory allocation.\n\n"); return(0);} nv=fread(image->sim, sizeof(short), nv, fp); if(image->flg!=1) for(int i=0; i<nv; i++) swapByteOrder( (char *)&image->sim[i], sizeof(short)); break; case 2: image->iim =(int *)calloc(nv,sizeof(int)); if(image->iim == NULL) { printf("\n\nError: memory allocation.\n\n"); return(0);} nv=fread(image->iim, sizeof(int), nv, fp); if(image->flg!=1) for(int i=0; i<nv; i++) swapByteOrder( (char *)&image->iim[i], sizeof(int)); break; case 3: image->fim =(float *)calloc(nv,sizeof(float)); if(image->fim == NULL) { printf("\n\nError: memory allocation.\n\n"); return(0);} nv=fread(image->fim, sizeof(float), nv, fp); if(image->flg!=1) for(int i=0; i<nv; i++) swapByteOrder( (char *)&image->fim[i], sizeof(float)); break; case 4: image->dim =(double *)calloc(nv,sizeof(double)); if(image->dim == NULL) { printf("\n\nError: memory allocation.\n\n"); return(0);} nv=fread(image->dim, sizeof(double), nv, fp); if(image->flg!=1) for(int i=0; i<nv; i++) swapByteOrder( (char *)&image->dim[i], sizeof(double)); break; } fclose(fp); if( nv != image->nx*image->ny*image->nz*image->nt ) { printf("\n\nProblem reading %s!\n\n",filename); return(0); } //printf("Matrix size = %d x %d x %d (voxels)\n",image->nx, image->ny,image->nz); //printf("Voxel size = %8.6f x %8.6f x %8.6f (mm)\n", image->dx,image->dy,image->dz); return(1); }
SimpleVolumeData* RawVFile::loadFile(const string& fileName) { SimpleVolumeData* simpleVolumeData = new SimpleVolumeData(128, 128, 128); FILE *fp=FOPEN(fileName.c_str(), "rb"); unsigned int i, magic, dims[3], numTimeSteps, numVariables; float minExt[4], maxExt[4]; // check to make sure the file exists if (!fp) { printf("Error: could not open file\n"); delete simpleVolumeData; simpleVolumeData = 0; return false; } // read the header // // read the magic number fread(&magic, 1, sizeof(unsigned int), fp); if (isLittleEndian()) swapByteOrder(&magic, 1); if (magic != 0xBAADBEEF) { // doh! this isn't a RawV file printf("Error: file format is not recognized. (expecting RawV)\n"); fclose(fp); return false; } // the dimensions, # of timesteps, # of variables, and min/max extents fread(dims, 3, sizeof(unsigned int), fp); fread(&numTimeSteps, 1, sizeof(unsigned int), fp); fread(&numVariables, 1, sizeof(unsigned int), fp); fread(minExt, 4, sizeof(float), fp); fread(maxExt, 4, sizeof(float), fp); if (isLittleEndian()) { swapByteOrder(dims, 3); swapByteOrder(&numTimeSteps, 1); swapByteOrder(&numVariables, 1); swapByteOrder(minExt, 4); swapByteOrder(maxExt, 4); } // call a bunch of set...() functions // // setNumberOfVariables() has the convenient side effect of cleaning up // any data that this instance might already be holding. (effectively wiping // the slate clean) simpleVolumeData->setNumberOfVariables(numVariables); // the rest ... simpleVolumeData->setDimensions(dims); simpleVolumeData->setMinExtent(minExt); simpleVolumeData->setMaxExtent(maxExt); // finish reading the header (variable names and types) for (i=0; i < numVariables; i++) { char name[64]; unsigned char type; // read the type and the name of a variable fread(&type, 1, sizeof(unsigned char), fp); fread(name, 64, sizeof(char), fp); name[63] = '\0'; // just in case // call set...() functions switch(type) { case 1: simpleVolumeData->setType(i, SimpleVolumeData::UCHAR); break; case 2: simpleVolumeData->setType(i, SimpleVolumeData::USHORT); break; case 3: simpleVolumeData->setType(i, SimpleVolumeData::ULONG); break; case 4: simpleVolumeData->setType(i, SimpleVolumeData::FLOAT); break; case 5: simpleVolumeData->setType(i, SimpleVolumeData::DOUBLE); break; default: break; } simpleVolumeData->setName(i, name); } // finally, read the data for (i=0; i < numVariables; i++) { // now that all the meta-data is filled in, allocate space for the variables unsigned char* data = new unsigned char [simpleVolumeData->getDataSize(i)]; // read the data for this variables first (and only?) timestep fread(data, simpleVolumeData->getDataSize(i), 1, fp); // swap the byte order if needed if (isLittleEndian()) { switch(simpleVolumeData->getTypeSize(i)) { case 1: break; case 2: swapByteOrder((unsigned short *)data, dims[0]*dims[1]*dims[2]); break; case 4: swapByteOrder((float *)data, dims[0]*dims[1]*dims[2]); break; case 8: swapByteOrder((double *)data, dims[0]*dims[1]*dims[2]); break; default: break; } } simpleVolumeData->setData(i, data); // seek past any remaining timesteps if (numTimeSteps > 1) fseek(fp, simpleVolumeData->getDataSize(i)*(numTimeSteps-1), SEEK_CUR); } // close the file fclose(fp); return simpleVolumeData; }
// assumes that the *.img and *.hdr files exist and we have read permission. char *read_analyze_image(const char *filename, int *nx, int *ny, int *nz, int *nt, float *dx, float *dy, float *dz, int *type, int v) { char hdrfile[1024]; char imgfile[1024]; int nv; short dataType; char *im; struct dsr analyzehdr; get_analyze_file_names(filename, hdrfile, imgfile); if( !check_F_R_permission(hdrfile) ) { printf("\nError: cannot read %s\n",hdrfile); return(NULL); } if( !check_F_R_permission(imgfile) ) { printf("\nError: cannot read %s\n",imgfile); return(NULL); } if(v) { printf("\nReading:"); printf("\n\t%s",hdrfile); printf("\n\t%s",imgfile); } read_analyze_hdr(&analyzehdr, hdrfile); setDimensions(analyzehdr, nx, ny, nz, nt, dx, dy, dz, &dataType,v); nv = (*nx)*(*ny)*(*nz)*(*nt); *type = dataType; if(dataType==16) { im = read_image(imgfile,(int)(nv*sizeof(float))); if(im==NULL) return(NULL); if ( analyzehdr.hk.sizeof_hdr != 348 ) for(int i=0; i<nv; i+=sizeof(float) ) swapByteOrder( im+i, sizeof(float)); return(im); } if(dataType==4) { im= read_image(imgfile,nv*2); if(im==NULL) return(NULL); if ( analyzehdr.hk.sizeof_hdr != 348 ) swapN( (char *)im, 2*nv); return(im); } if(dataType==2) { im = read_image(imgfile,nv); return(im); } printf("\n\nSorry, but this program cannot handle this data type! Aborting ...\n\n"); return(NULL); }
void getNiftiImageOrientation(const char *filename, char *orientation) { FILE *fp; nifti_1_header hdr; int swapflg=0; orientation[0]='\0'; // ensure that the specified image has either a .hdr or a .nii extension if( !checkNiftiFileExtension(filename) ) { errorMessage("The image filename must have a `.hdr' or `.nii' extension."); } fp = fopen(filename,"r"); if(fp==NULL) { file_open_error(filename); } if( fread(&hdr, sizeof(nifti_1_header), 1, fp) != 1 ) { errorMessage("I have trouble reading the specified image file."); } fclose(fp); // looks like ANALYZE 7.5, cannot determine orientation if( hdr.magic[0]!='n' || (hdr.magic[1]!='+' && hdr.magic[1]!='i') || hdr.magic[2]!='1') { printf("\nWarning: Could not determine %s image orientation ...\n",filename); return; } // if dim[0] is outside range 1..7, then the header information // needs to be byte swapped appropriately if(hdr.dim[0]<1 || hdr.dim[0]>7) { swapflg=1; } // Here I am only byte swapping the header fields relevant for determining the image orientation if(swapflg) { swapByteOrder( (char *)&(hdr.qform_code), sizeof(short)); swapByteOrder( (char *)&(hdr.sform_code), sizeof(short)); swapByteOrder( (char *)&(hdr.quatern_b), sizeof(float)); swapByteOrder( (char *)&(hdr.quatern_c), sizeof(float)); swapByteOrder( (char *)&(hdr.quatern_d), sizeof(float)); swapByteOrder( (char *)&(hdr.qoffset_x), sizeof(float)); swapByteOrder( (char *)&(hdr.qoffset_y), sizeof(float)); swapByteOrder( (char *)&(hdr.qoffset_z), sizeof(float)); for(int i=0; i<4; i++) { swapByteOrder( (char *)&(hdr.srow_x[i]), sizeof(float)); swapByteOrder( (char *)&(hdr.srow_y[i]), sizeof(float)); swapByteOrder( (char *)&(hdr.srow_z[i]), sizeof(float)); } } if(hdr.qform_code == 0 && hdr.sform_code == 0) { printf("\nWarning: Could not determine %s image orientation ...\n",filename); printf("\nWarning: The header of this \"NIFTI\" file does not contain orientation information.\n"); return; } if(hdr.qform_code > 0 ) { mat44 R; R = nifti_quatern_to_mat44(hdr.quatern_b, hdr.quatern_c, hdr.quatern_d, hdr.qoffset_x, hdr.qoffset_y, hdr.qoffset_z, hdr.pixdim[1], hdr.pixdim[2], hdr.pixdim[3], hdr.pixdim[0]); orientation[0] = directionCode(R.m[0][0],R.m[1][0],R.m[2][0]); orientation[1] = directionCode(R.m[0][1],R.m[1][1],R.m[2][1]); orientation[2] = directionCode(R.m[0][2],R.m[1][2],R.m[2][2]); orientation[3] = '\0'; } else { orientation[0] = directionCode(hdr.srow_x[0],hdr.srow_y[0],hdr.srow_z[0]); orientation[1] = directionCode(hdr.srow_x[1],hdr.srow_y[1],hdr.srow_z[1]); orientation[2] = directionCode(hdr.srow_x[2],hdr.srow_y[2],hdr.srow_z[2]); orientation[3] = '\0'; } return; }
void MrcFileImpl::swapHeader(MrcHeader& header) { //qDebug("swap header"); swapByteOrder(header.nx); swapByteOrder(header.ny); swapByteOrder(header.nz); //qDebug("header.mode = %x", header.mode); swapByteOrder(header.mode); //qDebug("header.mode = %x", header.mode); swapByteOrder(header.nxstart); swapByteOrder(header.nystart); swapByteOrder(header.nzstart); swapByteOrder(header.mx); swapByteOrder(header.my); swapByteOrder(header.mz); swapByteOrder(header.xlength); swapByteOrder(header.ylength); swapByteOrder(header.zlength); swapByteOrder(header.alpha); swapByteOrder(header.beta); swapByteOrder(header.gamma); swapByteOrder(header.mapc); swapByteOrder(header.mapr); swapByteOrder(header.maps); swapByteOrder(header.amin); swapByteOrder(header.amax); swapByteOrder(header.amean); swapByteOrder(header.ispg); swapByteOrder(header.nsymbt); swapByteOrder(header.extra, 25); swapByteOrder(header.xorigin); swapByteOrder(header.yorigin); swapByteOrder(header.zorigin); swapByteOrder(header.rms); swapByteOrder(header.nlabl); }
// assumes that the *.img and *.hdr files exist and we have read permission. char *read_analyze_image(const char *filename, DIM *dim, int *type, int v) { char hdrfile[1024]; char imgfile[1024]; int nv; short dataType; char *im=NULL; struct dsr analyzehdr; get_analyze_file_names(filename, hdrfile, imgfile); if( !check_F_R_permission(hdrfile) ) { printf("\nError: cannot read %s\n\n",hdrfile); return(NULL); } if( !check_F_R_permission(imgfile) ) { printf("\nError: cannot read %s\n\n",imgfile); return(NULL); } if(v) { printf("\nReading:"); printf("\n\t%s",hdrfile); printf("\n\t%s",imgfile); } read_analyze_hdr(&analyzehdr, hdrfile); setDimensions(analyzehdr, &(dim->nx), &(dim->ny), &(dim->nz), &(dim->dx), &(dim->dy), &(dim->dz), &dataType,v); nv = (dim->nx)*(dim->ny)*(dim->nz); *type = dataType; if(dataType==16) { im = read_image(imgfile,(int)(nv*sizeof(float))); if ( im!=NULL && analyzehdr.hk.sizeof_hdr != 348 ) for(int i=0; i<nv; i += sizeof(float)) swapByteOrder( im+i, sizeof(float)); } else if(dataType==4) { im= read_image(imgfile,nv*sizeof(short)); if (im!=NULL && analyzehdr.hk.sizeof_hdr != 348 ) swapN( im, 2*nv); } else if(dataType==2) { im = read_image(imgfile,nv); } else { printf("\nSorry, but this program cannot handle this data type! Aborting ...\n\n"); return(NULL); } return(im); }
void MrcFileImpl::fillHeader(MrcHeader& header) { // fill in the header's fields header.nx = m_DimX; header.ny = m_DimY; header.nz = m_DimZ; switch (m_VariableTypes[0]) { case Char: header.mode = 0; break; case Short: header.mode = 1; break; case Float: header.mode = 2; break; default: // wha??? // we shouldn't get here. (famous last words, I know) break; } // start coord, defaults to (0,0,0) header.nxstart = 0; header.nystart = 0; header.nzstart = 0; // the dimensions again header.mx = m_DimX; header.my = m_DimY; header.mz = m_DimZ; // dimensions of a cell (span) // (supposed to be in angstroms, but no guarantees) header.xlength = m_MaxX - m_MinX; header.ylength = m_MaxY - m_MinY; header.zlength = m_MaxZ - m_MinZ; // cell angles, all 90 deg header.alpha = 90.0; header.beta = 90.0; header.gamma = 90.0; // axis order header.mapc = 1; // number of axis corresponding to columns (X) header.mapr = 2; // number of axis corresponding to rows (Y) header.maps = 3; // number of axis corresponding to sections (Z) // min, max and mean... just put 0.0 header.amin = 0.0; // minimum density value header.amax = 0.0; // maximum density value header.amean = 0.0; // mean density value header.ispg = 0; // space group number (0 for images) header.nsymbt = 0; // # of bytes for symmetry operators memset(header.extra, 0, 25*sizeof(int)); // user defined storage space // mesh origin header.xorigin = m_MinX; // X phase origin header.yorigin = m_MinY; // Y phase origin header.zorigin = m_MinZ; // Z phase origin // character string 'MAP ' header.map[0] = 'M'; header.map[1] = 'A'; header.map[2] = 'P'; header.map[3] = ' '; // machine stamp if (isLittleEndian()) { header.machst = 0x44410000; // swap it to big endian swapByteOrder(header.machst); } else header.machst = 0x11110000; header.rms = 0.0; // rms deviation of map from mean density header.nlabl = 1; // # of labels being used in the MRC header // zero the labels for (int i=0; i < 10; i++) memset(header.label[i], 0, 80); // fill in the first label strcpy(header.label[0], "Created by Volume Rover"); }
TxId DatabaseHelper::txLoad(TxId txIndex, DbTransaction& dbTx, std::vector<DbTransactionOutput>* outputs, std::vector<DbTransactionBlock>* blocks) { auto buffer = bufferTLS.get(); if (buffer == NULL) { bufferTLS.reset(buffer = new std::string()); } bool loadedTransaction = false; char searchKey2[1 + sizeof(TxId)]; searchKey2[0] = (uint8_t)DatabaseKeyHeader::Tx; *((TxId*)&searchKey2[1]) = swapByteOrder(txIndex); auto searchKeySlice = leveldb::Slice((const char*)searchKey2, sizeof(searchKey2)); if (outputs == NULL && blocks == NULL) { if (!db->Get(leveldb::ReadOptions(), searchKeySlice, buffer).ok()) return 0; } else { // Slower path to get outputs and/or blocks using iterators auto it = std::unique_ptr<leveldb::Iterator>(db->NewIterator(leveldb::ReadOptions())); it->Seek(searchKeySlice); if (!it->Valid() || it->key() != searchKeySlice) return false; buffer->assign(it->value().data(), it->value().size()); // Read outputs it->Next(); for (; it->Valid(); it->Next()) { auto key = it->key(); if (key.size() < searchKeySlice.size() || memcmp(key.data(), searchKeySlice.data(), searchKeySlice.size()) != 0) break; auto keyType = key.data()[1 + sizeof(TxId)]; if (keyType == 0x02) { if (outputs != NULL) { auto& transactionOutput = *(DbTransactionOutput*)&key.data()[1 + sizeof(TxId) + 1]; outputs->push_back(transactionOutput); } } else if (keyType == 0x03 && blocks != NULL) { if (blocks != NULL) { auto& transactionBlock = *(DbTransactionBlock*) &key.data()[1 + sizeof(TxId) + 1]; blocks->push_back(transactionBlock); } } else { break; } } } Deserialize(*buffer, dbTx); return txIndex; }
char *read_nifti_image(const char *filename, nifti_1_header *hdr) { FILE *fp; int swapflg=0; int nv; char *imgname; char *im=NULL; // ensure that the specified image has either a .hdr or a .nii extension if( !checkNiftiFileExtension(filename) ) { errorMessage("Error: The image filename must have a `.hdr' or `.nii' extension."); } fp = fopen(filename,"r"); if(fp==NULL) { errorMessage("Error: I have trouble opening the specified image file."); } if( fread(hdr, sizeof(nifti_1_header), 1, fp) != 1 ) { errorMessage("Error: I have trouble reading the specified image file."); } fclose(fp); // if dim[0] is outside range 1..7, then the header information // needs to be byte swapped appropriately if(hdr->dim[0]<1 || hdr->dim[0]>7) { swapflg=1; } if(swapflg) { swapByteOrder( (char *)&(hdr->sizeof_hdr), sizeof(int)); swapByteOrder( (char *)&(hdr->dim[0]), sizeof(short)); for(int i=1; i<=hdr->dim[0]; i++) { swapByteOrder( (char *)&(hdr->dim[i]), sizeof(short)); } swapByteOrder( (char *)&(hdr->datatype), sizeof(short)); for(int i=0; i<=hdr->dim[0]; i++) { swapByteOrder( (char *)&(hdr->pixdim[i]), sizeof(float)); } swapByteOrder( (char *)&(hdr->vox_offset), sizeof(float)); } nv = hdr->dim[1]*hdr->dim[2]*hdr->dim[3]; im = (char *)calloc(nv*hdr->bitpix/8, sizeof(char)); if(im==NULL) { errorMessage("Error: Memory allocation problem in readNiftiImage() function."); } { int L; L = strlen(filename); imgname = (char *)calloc(L+1, 1); strcpy(imgname, filename); if(imgname[L-3]=='h' && imgname[L-2]=='d' && imgname[L-1]=='r') { imgname[L-3]='i'; imgname[L-2]='m'; imgname[L-1]='g'; } } // if it is ANALYZE format, we want vox_offset to be zero if( hdr->magic[0]!='n' || (hdr->magic[1]!='+' && hdr->magic[1]!='i') || hdr->magic[2]!='1') { hdr->vox_offset = 0; } fp = fopen(imgname,"r"); if(fp==NULL) { errorMessage("Error: I have trouble opening the specified image file."); } if( fseek(fp, (long)hdr->vox_offset, SEEK_SET) != 0 ) { errorMessage("Error: I have trouble reading the specified image file."); } if( hdr->datatype == DT_SIGNED_SHORT || hdr->datatype == DT_UINT16) { if( fread(im, sizeof(short), nv, fp) != nv ) { errorMessage("Error: I have trouble reading the specified image file."); } if(swapflg) { swapN( im, nv*2); } } else if( hdr->datatype == DT_UNSIGNED_CHAR || hdr->datatype == DT_INT8 ) { if (fread(im, sizeof(unsigned char), nv, fp) != nv ) { errorMessage("Error: I have trouble reading the specified image file."); } } else { errorMessage("Error: Sorry, but this program can only handle image types `short' and `unsigned char'."); } fclose(fp); return(im); }
SimpleVolumeData* RawIVFile::loadFile(const string& fileName) { SimpleVolumeData* simpleVolumeData = new SimpleVolumeData(128, 128, 128); FILE *fp=FOPEN(fileName.c_str(), "rb"); unsigned int dims[3]; unsigned int temp_numverts, temp_numcells; //for large files, these are meaningless, and anyway not used. float minExt[3], maxExt[3], orig[3], span[3]; // check to make sure the file exists if (!fp) { printf("Error: could not open file\n"); delete simpleVolumeData; simpleVolumeData = 0; return 0; } // read the header // fread(minExt, 3, sizeof(float), fp); fread(maxExt, 3, sizeof(float), fp); fread(&temp_numverts, 1, sizeof(unsigned int), fp); fread(&temp_numcells, 1, sizeof(unsigned int), fp); fread(dims, 3, sizeof(unsigned int), fp); fread(orig, 3, sizeof(float), fp); fread(span, 3, sizeof(float), fp); if (isLittleEndian()) { swapByteOrder(minExt, 3); swapByteOrder(maxExt, 3); swapByteOrder(&temp_numverts, 1); swapByteOrder(&temp_numcells, 1); swapByteOrder(dims, 3); swapByteOrder(orig, 3); swapByteOrder(span, 3); } /* //// only for NMJ project! ////// { minExt[0] *= 150; minExt[1] *= 150; minExt[2] *= 150; } { maxExt[0] *= 150; maxExt[1] *= 150; maxExt[2] *= 150; orig[0] *= 150; orig[1] *= 150; orig[2] *= 150; span[0] = span[1] = span[2] = 150; } */ ///////////////////////////////// // find out how large the data is Q_ULLONG dataStart = ftell(fp), dataSize; fseek(fp, 0, SEEK_END); dataSize = ftell(fp) - dataStart; fseek(fp, dataStart, SEEK_SET); // a small sanity check to make sure this file is valid if ((dataSize % ((Q_ULLONG)dims[0]*dims[1]*dims[2])) != 0) { printf("Error: rawiv file header dimensions don't match file size"); fclose(fp); return false; } // call some set...() functions // simpleVolumeData->setNumberOfVariables(1); simpleVolumeData->setDimensions(dims); simpleVolumeData->setMinExtent(minExt); simpleVolumeData->setMaxExtent(maxExt); // figure out the data type switch (dataSize / ((Q_ULLONG)dims[0]*dims[1]*dims[2])) { case 1: simpleVolumeData->setType(0, SimpleVolumeData::UCHAR); break; case 2: simpleVolumeData->setType(0, SimpleVolumeData::USHORT); break; case 4: simpleVolumeData->setType(0, SimpleVolumeData::FLOAT); break; default: simpleVolumeData->setType(0, SimpleVolumeData::NO_TYPE); break; } // allocate space for the data unsigned char * data = (unsigned char*)malloc((Q_ULLONG)sizeof(unsigned char)*dataSize); // read the data fread(data, dataSize, 1, fp); // swap the byte order if needed if (isLittleEndian()) { switch(simpleVolumeData->getTypeSize(0)) { case 1: break; case 2: swapByteOrder((unsigned short *)data, (Q_ULLONG)dims[0]*dims[1]*dims[2]); break; case 4: swapByteOrder((float *)data, (Q_ULLONG)dims[0]*dims[1]*dims[2]); break; case 8: swapByteOrder((double *)data, (Q_ULLONG)dims[0]*dims[1]*dims[2]); break; default: break; } } simpleVolumeData->setData(0, data); // close the file fclose(fp); return simpleVolumeData; }
bool createRawIVHeader(char *header, float* real_data, float span[3], float orig[3], int size, float min[3], float max[3] ) { if (!real_data) return false; unsigned int numverts, numcells; numverts = size* size* size; numcells = (size-1)*(size-1)*(size-1); // minX memcpy(header, &min[0], sizeof(float)); header += 4; // minY memcpy(header, &min[1], sizeof(float)); header += 4; // minZ memcpy(header, &min[2], sizeof(float)); header += 4; // maxX memcpy(header, &max[0], sizeof(float)); header += 4; // maxY memcpy(header, &max[1], sizeof(float)); header += 4; // maxZ memcpy(header, &max[2], sizeof(float)); header += 4; // numverts memcpy(header, &numverts, sizeof(numverts)); header += 4; // numcells memcpy(header, &numcells, sizeof(numcells)); header += 4; // dimX memcpy(header, &size, sizeof(unsigned int)); header += 4; // dimY memcpy(header, &size, sizeof(unsigned int)); header += 4; // dimZ memcpy(header, &size, sizeof(unsigned int)); header += 4; // originX memcpy(header, &orig[0], sizeof(float)); header += 4; // originY memcpy(header, &orig[1], sizeof(float)); header += 4; // originZ memcpy(header, &orig[2], sizeof(float)); header += 4; // spanX memcpy(header, &span[0], sizeof(float)); header += 4; // spanY memcpy(header, &span[1], sizeof(float)); header += 4; // spanZ memcpy(header, &span[2], sizeof(float)); header -= 64; if (isLittleEndian()) swapByteOrder((unsigned int *)header, 17); return true; }
// returns the orientations vectors xvec, yvec, and zvec in NIFTI's RAS system void readOrientationVectorsFromFile(const char *filename, float *xvec, float *yvec, float *zvec) { FILE *fp; nifti_1_header hdr; int swapflg=0; // ensure that the specified image has either a .hdr or a .nii extension if( !checkNiftiFileExtension(filename) ) { errorMessage("Error: The image filename must have a `.hdr' or `.nii' extension."); } fp = fopen(filename,"r"); if(fp==NULL) { errorMessage("Error: I have trouble opening the specified image file."); } if( fread(&hdr, sizeof(nifti_1_header), 1, fp) != 1 ) { errorMessage("Error: I have trouble reading the specified image file."); } fclose(fp); // looks like ANALYZE 7.5, cannot determine orientation if( hdr.magic[0]!='n' || (hdr.magic[1]!='+' && hdr.magic[1]!='i') || hdr.magic[2]!='1') { return; } // if dim[0] is outside range 1..7, then the header information // needs to be byte swapped appropriately if(hdr.dim[0]<1 || hdr.dim[0]>7) { swapflg=1; } // Here I am only byte swapping the header fields relevant for determining the image orientation if(swapflg) { swapByteOrder( (char *)&(hdr.qform_code), sizeof(short)); swapByteOrder( (char *)&(hdr.sform_code), sizeof(short)); swapByteOrder( (char *)&(hdr.quatern_b), sizeof(float)); swapByteOrder( (char *)&(hdr.quatern_c), sizeof(float)); swapByteOrder( (char *)&(hdr.quatern_d), sizeof(float)); swapByteOrder( (char *)&(hdr.qoffset_x), sizeof(float)); swapByteOrder( (char *)&(hdr.qoffset_y), sizeof(float)); swapByteOrder( (char *)&(hdr.qoffset_z), sizeof(float)); for(int i=0; i<4; i++) { swapByteOrder( (char *)&(hdr.srow_x[i]), sizeof(float)); swapByteOrder( (char *)&(hdr.srow_y[i]), sizeof(float)); swapByteOrder( (char *)&(hdr.srow_z[i]), sizeof(float)); } } if(hdr.qform_code == 0 && hdr.sform_code == 0) { printf("\nThe header of this so called \"NIFTI\" file does not contain orientation information.\n"); return; } if(hdr.qform_code > 0 ) { mat44 R; R = nifti_quatern_to_mat44(hdr.quatern_b, hdr.quatern_c, hdr.quatern_d, hdr.qoffset_x, hdr.qoffset_y, hdr.qoffset_z, hdr.pixdim[1], hdr.pixdim[2], hdr.pixdim[3], hdr.pixdim[0]); xvec[0] = R.m[0][0]; xvec[1] = R.m[1][0]; xvec[2] = R.m[2][0]; yvec[0] = R.m[0][1]; yvec[1] = R.m[1][1]; yvec[2] = R.m[2][1]; zvec[0] = R.m[0][2]; zvec[1] = R.m[1][2]; zvec[2] = R.m[2][2]; } else { xvec[0] = hdr.srow_x[0]; xvec[1] = hdr.srow_y[0]; xvec[2] = hdr.srow_z[0]; yvec[0] = hdr.srow_x[1]; yvec[1] = hdr.srow_y[1]; yvec[2] = hdr.srow_z[1]; zvec[0] = hdr.srow_x[2]; zvec[1] = hdr.srow_y[2]; zvec[2] = hdr.srow_z[2]; } normalizeVector(xvec, 3); normalizeVector(yvec, 3); normalizeVector(zvec, 3); return; }
void swapniftiheader(nifti_1_header *hdr) { swapByteOrder( (char *)&(hdr->sizeof_hdr), sizeof(int)); swapByteOrder( (char *)&(hdr->extents), sizeof(int)); swapByteOrder( (char *)&(hdr->session_error), sizeof(short)); for(int i=0; i<8; i++) { swapByteOrder( (char *)&(hdr->dim[i]), sizeof(short)); } swapByteOrder( (char *)&(hdr->intent_p1), sizeof(float)); swapByteOrder( (char *)&(hdr->intent_p2), sizeof(float)); swapByteOrder( (char *)&(hdr->intent_p3), sizeof(float)); swapByteOrder( (char *)&(hdr->intent_code), sizeof(short)); swapByteOrder( (char *)&(hdr->datatype), sizeof(short)); swapByteOrder( (char *)&(hdr->bitpix), sizeof(short)); swapByteOrder( (char *)&(hdr->slice_start), sizeof(short)); for(int i=0; i<8; i++) { swapByteOrder( (char *)&(hdr->pixdim[i]), sizeof(float)); } swapByteOrder( (char *)&(hdr->vox_offset), sizeof(float)); swapByteOrder( (char *)&(hdr->scl_slope), sizeof(float)); swapByteOrder( (char *)&(hdr->scl_inter), sizeof(float)); swapByteOrder( (char *)&(hdr->slice_end), sizeof(short)); swapByteOrder( (char *)&(hdr->cal_max), sizeof(float)); swapByteOrder( (char *)&(hdr->cal_min), sizeof(float)); swapByteOrder( (char *)&(hdr->slice_duration), sizeof(float)); swapByteOrder( (char *)&(hdr->toffset), sizeof(float)); swapByteOrder( (char *)&(hdr->glmax), sizeof(int)); swapByteOrder( (char *)&(hdr->glmin), sizeof(int)); swapByteOrder( (char *)&(hdr->qform_code), sizeof(short)); swapByteOrder( (char *)&(hdr->sform_code), sizeof(short)); swapByteOrder( (char *)&(hdr->quatern_b), sizeof(float)); swapByteOrder( (char *)&(hdr->quatern_c), sizeof(float)); swapByteOrder( (char *)&(hdr->quatern_d), sizeof(float)); swapByteOrder( (char *)&(hdr->qoffset_x), sizeof(float)); swapByteOrder( (char *)&(hdr->qoffset_y), sizeof(float)); swapByteOrder( (char *)&(hdr->qoffset_z), sizeof(float)); for(int i=0; i<4; i++) { swapByteOrder( (char *)&(hdr->srow_x[i]), sizeof(float)); swapByteOrder( (char *)&(hdr->srow_y[i]), sizeof(float)); swapByteOrder( (char *)&(hdr->srow_z[i]), sizeof(float)); } }