Beispiel #1
0
void test() {
	CvCapture *capture = cvCreateFileCapture("D:\\²âÊÔÊÓƵ\\1344.avi");
	int frameWidth = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
	int frameHeight = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
	codeBook *cb = new codeBook[frameWidth * frameHeight];
	memset(cb, 0, frameWidth * frameHeight * sizeof(codeBook));
	unsigned int bound[3] = { 10 ,10,10 };
	int minMod[3] = { 10 ,10,10 };
	int maxMod[3] = { 10 ,10,10 };
	IplImage *frame[1000];

	for (int i = 0; i < 1000; i++) {
		frame[i] = cvCreateImage(cvSize(frameWidth, frameHeight), 8, 3);
		cvCopy(cvQueryFrame(capture), frame[i]);
	}

	for (int i = 0; i < frameWidth * frameHeight; i++) {
		for (int j = 0; j < 1000; j++) {
			UpdateCodeBook((unsigned char*)frame[j]->imageData + i * 3, cb[i], bound, 3);
		}
	}

	IplImage *mask = cvCreateImage(cvSize(frameWidth, frameHeight), 8, 1);

	for (int i = 0; i < 1000; i++) {
		for (int j = 0; j < frameWidth * frameHeight; j++) {
			mask->imageData[j] = BackgroundDiff((unsigned char*)frame[i]->imageData + j * 3, cb[j], 3, minMod, maxMod);
		}
		FindConnectedComponents(mask);
		cvShowImage("1", mask);
		cvShowImage("2", frame[i]);
		cvWaitKey(30);
	}
}
int main(int argc, char **argv) {
    std::string infile = "input";
    std::string outfile = "output";
    uint connectivity = 4;
    if (argc > 1) {
        infile = argv[1];
    }
    if (argc > 2) {
        outfile = argv[2];
    }
    if (argc > 3) { 
        connectivity = atoi(argv[3]);
    }
    uint xLen, yLen;
    std::vector<uint> vec = ReadImgFromFile(infile, xLen, yLen);
    std::vector<uint> res(vec.size());
    FindConnectedComponents(vec, res, xLen, yLen, connectivity);
    RelabelImg(res, xLen, yLen);
    WriteImgToFile(outfile, res, xLen, yLen); 
    return 0;
}
void AveragingMethodTest() {
	CvCapture *capture = cvCreateFileCapture("D:\\²âÊÔÊÓƵ\\daytime.avi");
	int fps = cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
	IplImage *frame;
	IplImage *back = cvLoadImage("back.jpg");
	IplImage *mask = cvCreateImage(cvGetSize(back), 8, 1);
	AllocateImages(back);
	while (frame = cvQueryFrame(capture)) {
		AccumulateBackground(frame);
	}
	CreateModelsfromStats();
	cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, 0);
	while (frame = cvQueryFrame(capture)) {
		BackgroundDiff(frame, mask);
		FindConnectedComponents(mask);
		cvShowImage("Display", mask);
		cvWaitKey(1000 / fps);
	}
	cvReleaseImage(&back);
	cvReleaseImage(&mask);
	cvReleaseCapture(&capture);
}
Beispiel #4
0
static void FindPyramids(int PileIndex)
	{
	const TanPile &Pile = Piles[PileIndex];
	const int HitCount = Pile.HitCount;
	if (HitCount < MIN_HIT_COUNT)
		return;

	EdgeList Edges;
	EdgeData Edge;
	Edge.Rev = false;
	const HitData *Hits = Pile.Hits;
	for (int HitIndex1 = 0; HitIndex1 < HitCount; ++HitIndex1)
		{
		const HitData &Hit1 = Hits[HitIndex1];
		Edge.Node1 = HitIndex1;
		for (int HitIndex2 = 0; HitIndex2 < HitIndex1; ++HitIndex2)
			{
			const HitData &Hit2 = Hits[HitIndex2];
			if (TandemPair(Hit1, Hit2))
				{
				Edge.Node2 = HitIndex2;
				Edges.push_back(Edge);
				}
			}
		}

	FamList Fams;
	FindConnectedComponents(Edges, Fams, MIN_HIT_COUNT);

	if (0 == Fams.size())
		return;

	GFFRecord Rec;
	Rec.Source = "piler";
	Rec.Feature = "hit";
	Rec.Score = 0;
	Rec.Frame = -1;
	Rec.SeqName = Pile.Label;

	for (PtrFamList p = Fams.begin(); p != Fams.end(); ++p)
		{
		FamData *Fam = *p;
		if (0 != fMotif)
			InferMotif(PyramidIndex, Pile, Fam);
		LogPyramid(PyramidIndex, Pile, Fam);

		int PyramidFrom = -1;
		int PyramidTo = -1;

		for (PtrFamData q = Fam->begin(); q != Fam->end(); ++q)
			{
			FamMemberData &FamMember = *q;
			int HitIndex = FamMember.PileIndex;
			if (HitIndex < 0 || HitIndex >= Pile.HitCount)
				Quit("Hit index out of range");
			const HitData &Hit = Pile.Hits[HitIndex];

			char s[1024];
			sprintf(s, "Target %s %d %d ; Pile %d ; Pyramid %d",
			  Pile.Label,
			  Hit.TargetFrom + 1,
			  Hit.TargetTo + 1,
			  PileIndex,
			  PyramidIndex);

			Rec.Strand = (Hit.Rev ? '-' : '+');
			Rec.Start = Hit.QueryFrom + 1;
			Rec.End = Hit.QueryTo + 1;
			Rec.Attrs = s;

			WriteGFFRecord(fOut, Rec);

			if (PyramidFrom == -1)
				PyramidFrom = min(Hit.QueryFrom, Hit.TargetFrom);
			else
				PyramidFrom = min3(PyramidFrom, Hit.QueryFrom, Hit.TargetFrom);

			if (PyramidTo == -1)
				PyramidTo = max(Hit.QueryTo, Hit.TargetTo);
			else
				PyramidTo = max3(PyramidTo, Hit.QueryTo, Hit.TargetTo);
			}
		WritePyramid(PyramidIndex, Pile.Label, PyramidFrom, PyramidTo);
		++PyramidIndex;
		}
	}
int main(int argc, char *argv[]){
	clock_t start, end;
	if (argc != 4){
		printf("Not enough arguments, exiting.\n");
		return 1;
	}
    double diftotal;
    start = clock();
    // Read params file.
    char *ParamFN;
    FILE *fileParam;
    ParamFN = argv[1];
    char aline[1000];
    fflush(stdout);
    fileParam = fopen(ParamFN,"r");
    if (fileParam == NULL){
		printf("Parameter file could not be read. Exiting\n");
		return 1;
	}
    check (fileParam == NULL,"%s file not found: %s", ParamFN, strerror(errno));
    char *str, dummy[1000], Folder[1024], FileStem[1024], *TmpFolder, darkcurrentfilename[1024], floodfilename[1024], Ext[1024],RawFolder[1024];
    TmpFolder = "Temp";
    int LowNr,FileNr,RingNr;
    FileNr = atoi(argv[2]);
    RingNr = atoi(argv[3]);
    double Thresh, bc=1, Ycen, Zcen, IntSat, OmegaStep, OmegaFirstFile, Lsd, px, Width, Wavelength, LatticeConstant,MaxRingRad;
    int CellStruct,NrPixels,Padding = 6, StartNr;
    char fs[1024];
    int LayerNr;
    int NrTransOpt=0;
    int TransOpt[10];
    int StartFileNr, NrFilesPerSweep;
    int DoFullImage = 0;
    int FrameNrOmeChange = 1, NrDarkFramesDataFile = 0;
    double OmegaMissing = 0, MisDir;
    double FileOmegaOmeStep[360][2];
    int fnr = 0;
    double RhoD, tx, ty, tz, p0, p1, p2;
    while (fgets(aline,1000,fileParam)!=NULL){
		printf("%s\n",aline);
		fflush(stdout);
		str = "tx ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &tx);
            continue;
        }
		str = "ty ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &ty);
            continue;
        }
        str = "tz ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &tz);
            continue;
        }
        str = "p0 ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &p0);
            continue;
        }
        str = "p1 ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &p1);
            continue;
        }
        str = "p2 ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &p2);
            continue;
        }
        str = "StartFileNr ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &StartFileNr);
            continue;
        }
        str = "DoFullImage ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &DoFullImage);
            continue;
        }
        str = "NrFilesPerSweep ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &NrFilesPerSweep);
            continue;
        }
        str = "Ext ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %s", dummy, Ext);
            continue;
        }
        str = "RawFolder ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %s", dummy, RawFolder);
            continue;
        }
        str = "Folder ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %s", dummy, Folder);
            continue;
        }
        str = "FileStem ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %s", dummy, fs);
            continue;
        }
        str = "Dark ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %s", dummy, darkcurrentfilename);
            continue;
        }
        str = "Flood ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %s", dummy, floodfilename);
            continue;
        }
        str = "LowerBoundThreshold ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &Thresh);
            continue;
        }
        str = "BeamCurrent ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &bc);
            continue;
        }
        str = "BC ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf %lf", dummy, &Ycen, &Zcen);
            continue;
        }
        str = "UpperBoundThreshold ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &IntSat);
            continue;
        }
        str = "OmegaStep ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &OmegaStep);
            continue;
        }
        str = "OmegaFirstFile ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &OmegaFirstFile);
            continue;
        }
        str = "px ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &px);
            continue;
        }
        str = "Width ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &Width);
            continue;
        }
        str = "LayerNr ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &LayerNr);
            continue;
        }
        str = "CellStruct ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &CellStruct);
            continue;
        }
        str = "NrPixels ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &NrPixels);
            continue;
        }
        str = "Padding ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &Padding);
            continue;
        }
        str = "Wavelength ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &Wavelength);
            continue;
        }
        str = "Lsd ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &Lsd);
            continue;
        }
        str = "StartNr ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &StartNr);
            continue;
        }
        str = "NrDarkFramesDataFile ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &NrDarkFramesDataFile);
            continue;
        }
        str = "MaxRingRad ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &MaxRingRad);
            continue;
        }
        str = "RhoD ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf", dummy, &RhoD);
            continue;
        }
        str = "ImTransOpt ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d", dummy, &TransOpt[NrTransOpt]);
            NrTransOpt++;
            continue;
        }
        str = "FrameOmeChange ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %d %lf %lf", dummy, &FrameNrOmeChange, &OmegaMissing, &MisDir);
            continue;
        }
        str = "FileOmegaOmeStep ";
        LowNr = strncmp(aline,str,strlen(str));
        if (LowNr==0){
            sscanf(aline,"%s %lf %lf", dummy, &FileOmegaOmeStep[fnr][0], &FileOmegaOmeStep[fnr][1]);
            fnr++;
            continue;
        }
	}
	printf("%f\n",Thresh);
	Width = Width/px;
	int i,j,k;
    for (i=0;i<NrTransOpt;i++){
        if (TransOpt[i] < 0 || TransOpt[i] > 3){printf("TransformationOptions can only be 0, 1, 2 or 3.\nExiting.\n");return 0;}
        printf("TransformationOptions: %d ",TransOpt[i]);
        if (TransOpt[i] == 0) printf("No change.\n");
        else if (TransOpt[i] == 1) printf("Flip Left Right.\n");
        else if (TransOpt[i] == 2) printf("Flip Top Bottom.\n");
        else printf("Transpose.\n");
    }
	sprintf(FileStem,"%s_%d",fs,LayerNr);
	fclose(fileParam);
	double MaxTtheta = rad2deg*atan(MaxRingRad/Lsd);
	double RingRad;
	char hklfn[2040];
	sprintf(hklfn,"%s/hkls.csv",Folder);
	FILE *hklf = fopen(hklfn,"r");
    if (hklf == NULL){
		printf("HKL file could not be read. Exiting\n");
		return 1;
	}
	fgets(aline,1000,hklf);
	int Rnr;
	double RRd;
	while (fgets(aline,1000,hklf)!=NULL){
		sscanf(aline, "%s %s %s %s %d %s %s %s %s %s %lf",dummy,dummy,dummy,dummy,&Rnr,dummy,dummy,dummy,dummy,dummy,&RRd);
		if (Rnr == RingNr){
			RingRad = RRd;
			break;
		}
	}
	RingRad = RingRad/px;
	printf("RingNr = %d RingRad = %f\n",RingNr, RingRad);
	double Rmin=RingRad-Width, Rmax=RingRad+Width;
	double Omega;
	int Nadditions;
	if (fnr == 0){
		if (FileNr - StartNr + 1 < FrameNrOmeChange){
			Omega = OmegaFirstFile + ((FileNr-StartNr)*OmegaStep);
		} else {
			Nadditions = (int) ((FileNr - StartNr + 1) / FrameNrOmeChange)  ;
			Omega = OmegaFirstFile + ((FileNr-StartNr)*OmegaStep) + MisDir*OmegaMissing*Nadditions;
		}
    }
    // Dark file reading from here.
	double *dark, *flood, *darkTemp;;
	//printf("%f %f\n",Rmin,Rmax);
	dark = malloc(NrPixels*NrPixels*sizeof(*dark));
	darkTemp = malloc(NrPixels*NrPixels*sizeof(*darkTemp));
	flood = malloc(NrPixels*NrPixels*sizeof(*flood));
	FILE *darkfile=fopen(darkcurrentfilename,"rb");
	size_t sz;
	int nFrames;
	int SizeFile = sizeof(pixelvalue) * NrPixels * NrPixels;
	long int Skip;
	for (i=0;i<(NrPixels*NrPixels);i++){dark[i]=0;darkTemp[i]=0;}
	pixelvalue *darkcontents;
	darkcontents = malloc(NrPixels*NrPixels*sizeof(*darkcontents));
	if (darkfile==NULL){printf("Could not read the dark file. Using no dark subtraction.");}
	else{
		fseek(darkfile,0L,SEEK_END);
		sz = ftell(darkfile);
		rewind(darkfile);
		nFrames = sz/(8*1024*1024);
		Skip = sz - (nFrames*8*1024*1024);
		fseek(darkfile,Skip,SEEK_SET);
		printf("Reading dark file: %s, nFrames: %d, skipping first %ld bytes.\n",darkcurrentfilename,nFrames,Skip);
		for (i=0;i<nFrames;i++){
			fread(darkcontents,SizeFile,1,darkfile);
			DoImageTransformations(NrTransOpt,TransOpt,darkcontents,NrPixels);
			for (j=0;j<(NrPixels*NrPixels);j++){
				darkTemp[j] += darkcontents[j];
			}
		}
		fclose(darkfile);
		for (i=0;i<(NrPixels*NrPixels);i++){
			darkTemp[i] /= nFrames;
		}
	}
	Transposer(darkTemp,NrPixels,dark);
	free(darkcontents);
	//Finished reading dark file.
	
	FILE *floodfile=fopen(floodfilename,"rb");
	if (floodfile==NULL){
		printf("Could not read the flood file. Using no flood correction.\n");
		for(i=0;i<(NrPixels*NrPixels);i++){
			flood[i]=1;
		}
	}
	else{
		fread(flood,sizeof(double)*NrPixels*NrPixels, 1, floodfile);
		fclose(floodfile);
	}
	double Rt;
	int *GoodCoords;
	GoodCoords = malloc(NrPixels*NrPixels*sizeof(*GoodCoords));
	memset(GoodCoords,0,NrPixels*NrPixels*sizeof(*GoodCoords));
	double txr, tyr, tzr;
	txr = deg2rad*tx;
	tyr = deg2rad*ty;
	tzr = deg2rad*tz;
	double Rx[3][3] = {{1,0,0},{0,cos(txr),-sin(txr)},{0,sin(txr),cos(txr)}};
	double Ry[3][3] = {{cos(tyr),0,sin(tyr)},{0,1,0},{-sin(tyr),0,cos(tyr)}};
	double Rz[3][3] = {{cos(tzr),-sin(tzr),0},{sin(tzr),cos(tzr),0},{0,0,1}};
	double TRint[3][3], TRs[3][3];
	MatrixMultF33(Ry,Rz,TRint);
	MatrixMultF33(Rx,TRint,TRs);
	double Yc, Zc, n0=2, n1=4, n2=2;
	double ABC[3], ABCPr[3], XYZ[3];
	double Rad, Eta, RNorm, DistortFunc, EtaT;
	for (i=1;i<NrPixels;i++){
		for (j=1;j<NrPixels;j++){
			//Rt = sqrt((i-Ycen)*(i-Ycen)+(j-Zcen)*(j-Zcen)); 
			// Correct for tilts and Distortion here
			Yc = (-i + Ycen)*px;
			Zc =  (j - Zcen)*px;
			ABC[0] = 0;
			ABC[1] = Yc;
			ABC[2] = Zc;
			MatrixMult(TRs,ABC,ABCPr);
			XYZ[0] = Lsd+ABCPr[0];
			XYZ[1] = ABCPr[1];
			XYZ[2] = ABCPr[2];
			Rad = (Lsd/(XYZ[0]))*(sqrt(XYZ[1]*XYZ[1] + XYZ[2]*XYZ[2]));
			Eta = CalcEtaAngle(XYZ[1],XYZ[2]);
			RNorm = Rad/RhoD;
			EtaT = 90 - Eta;
			DistortFunc = (p0*(pow(RNorm,n0))*(cos(deg2rad*(2*EtaT)))) + (p1*(pow(RNorm,n1))*(cos(deg2rad*(4*EtaT)))) + (p2*(pow(RNorm,n2))) + 1;
			Rt = Rad * DistortFunc / px;
			if (Rt > Rmin && Rt < Rmax){GoodCoords[((i-1)*NrPixels)+(j-1)] = 1;}
			else {GoodCoords[((i-1)*NrPixels)+(j-1)] = 0;}
		}
	}
	if (DoFullImage == 1){
		for (i=0;i<NrPixels*NrPixels;i++) GoodCoords[i] = 1;
	}
	
	// Get nFrames:
	FILE *dummyFile;
	char dummyFN[2048];
	if (Padding == 2){sprintf(dummyFN,"%s/%s_%02d%s",RawFolder,fs,StartFileNr,Ext);}
	else if (Padding == 3){sprintf(dummyFN,"%s/%s_%03d%s",RawFolder,fs,StartFileNr,Ext);}
	else if (Padding == 4){sprintf(dummyFN,"%s/%s_%04d%s",RawFolder,fs,StartFileNr,Ext);}
	else if (Padding == 5){sprintf(dummyFN,"%s/%s_%05d%s",RawFolder,fs,StartFileNr,Ext);}
	else if (Padding == 6){sprintf(dummyFN,"%s/%s_%06d%s",RawFolder,fs,StartFileNr,Ext);}
	else if (Padding == 7){sprintf(dummyFN,"%s/%s_%07d%s",RawFolder,fs,StartFileNr,Ext);}
	else if (Padding == 8){sprintf(dummyFN,"%s/%s_%08d%s",RawFolder,fs,StartFileNr,Ext);}
	else if (Padding == 9){sprintf(dummyFN,"%s/%s_%09d%s",RawFolder,fs,StartFileNr,Ext);}
	dummyFile = fopen(dummyFN,"rb");
	if (dummyFile == NULL){
		printf("Could not read the input file %s. Exiting.\n",dummyFN);
		return 1;
	}
	fseek(dummyFile,0L,SEEK_END);
	sz = ftell(dummyFile);
	fclose(dummyFile);
	nFrames = sz/(8*1024*1024);

	char FN[2048];
	int ReadFileNr;
	ReadFileNr = StartFileNr + ((FileNr-1) / nFrames);
	int FramesToSkip = ((FileNr-1) % nFrames);
	
	if (fnr != 0){
		OmegaStep = FileOmegaOmeStep[ReadFileNr-StartFileNr][1];
		Omega = FileOmegaOmeStep[ReadFileNr-StartFileNr][0] + FramesToSkip*OmegaStep;
	}
	
	if (Padding == 2){sprintf(FN,"%s/%s_%02d%s",RawFolder,fs,ReadFileNr,Ext);}
	else if (Padding == 3){sprintf(FN,"%s/%s_%03d%s",RawFolder,fs,ReadFileNr,Ext);}
	else if (Padding == 4){sprintf(FN,"%s/%s_%04d%s",RawFolder,fs,ReadFileNr,Ext);}
	else if (Padding == 5){sprintf(FN,"%s/%s_%05d%s",RawFolder,fs,ReadFileNr,Ext);}
	else if (Padding == 6){sprintf(FN,"%s/%s_%06d%s",RawFolder,fs,ReadFileNr,Ext);}
	else if (Padding == 7){sprintf(FN,"%s/%s_%07d%s",RawFolder,fs,ReadFileNr,Ext);}
	else if (Padding == 8){sprintf(FN,"%s/%s_%08d%s",RawFolder,fs,ReadFileNr,Ext);}
	else if (Padding == 9){sprintf(FN,"%s/%s_%09d%s",RawFolder,fs,ReadFileNr,Ext);}

	printf("Reading file: %s\n",FN);
	FILE *ImageFile = fopen(FN,"rb");
	if (ImageFile == NULL){
		printf("Could not read the input file. Exiting.\n");
		return 1;
	}
	pixelvalue *Image;
	Image = malloc(NrPixels*NrPixels*sizeof(*Image));
	fseek(ImageFile,0L,SEEK_END);
	sz = ftell(ImageFile);
	rewind(ImageFile);
	Skip = sz - ((nFrames-FramesToSkip) * 8*1024*1024);
	printf("Now processing file: %s\n",FN);
	double beamcurr=1;
	fseek(ImageFile,Skip,SEEK_SET);
	fread(Image,SizeFile,1,ImageFile);
	fclose(ImageFile);
	DoImageTransformations(NrTransOpt,TransOpt,Image,NrPixels);
	printf("Beam current this file: %f, Beam current scaling value: %f\n",beamcurr,bc);
	double *ImgCorrBCTemp, *ImgCorrBC;
	ImgCorrBC = malloc(NrPixels*NrPixels*sizeof(*ImgCorrBC));
	ImgCorrBCTemp = malloc(NrPixels*NrPixels*sizeof(*ImgCorrBCTemp));
	for (i=0;i<(NrPixels*NrPixels);i++)ImgCorrBCTemp[i]=Image[i];
	free(Image);
	Transposer(ImgCorrBCTemp,NrPixels,ImgCorrBC);
	for (i=0;i<(NrPixels*NrPixels);i++){
		ImgCorrBC[i] = (ImgCorrBC[i] - dark[i])/flood[i];
		ImgCorrBC[i] = ImgCorrBC[i]*bc/beamcurr;
		if (ImgCorrBC[i] < Thresh){
			ImgCorrBC[i] = 0;
		}
		if (GoodCoords[i] == 0){
			ImgCorrBC[i] = 0;
		}
	}
	free(GoodCoords);
	free(ImgCorrBCTemp);
	free(dark);
	free(flood);
	char OutFolderName[1024];
	sprintf(OutFolderName,"%s/%s",Folder,TmpFolder);
	int e = CheckDirectoryCreation(OutFolderName);
	if (e == 0){ return 1;}
	int nOverlapsMaxPerImage = 10000;
	// Do Connected components
	int **BoolImage, **ConnectedComponents;
	BoolImage = allocMatrixInt(NrPixels,NrPixels);
	ConnectedComponents = allocMatrixInt(NrPixels,NrPixels);
	int **Positions;
	Positions = allocMatrixInt(nOverlapsMaxPerImage,NrPixels*4);
	int *PositionTrackers;
	PositionTrackers = malloc(nOverlapsMaxPerImage*sizeof(*PositionTrackers));
	for (i=0;i<nOverlapsMaxPerImage;i++)PositionTrackers[i] = 0;
	int NrOfReg;
	for (i=0;i<NrPixels;i++){
		for (j=0;j<NrPixels;j++){
			if (ImgCorrBC[(i*NrPixels)+j] != 0){
				BoolImage[i][j] = 1;
			}else{
				BoolImage[i][j] = 0;
			}
		}
	}
	NrOfReg = FindConnectedComponents(BoolImage,NrPixels,ConnectedComponents,Positions,PositionTrackers);
	FreeMemMatrixInt(BoolImage,NrPixels);
	/*FILE *connectedcomps;
	char conncomp[1024];
	pixelvalue *CCP;
	CCP = malloc(NrPixels*NrPixels*sizeof(*CCP));
	memset(CCP,0,NrPixels*NrPixels*sizeof(*CCP));
	for (i=0;i<NrPixels;i++){
		for (j=0;j<NrPixels;j++){
			if (ConnectedComponents[i][j] != 0){
				CCP[(i*NrPixels)+j] = ConnectedComponents[i][j];
			}
		}
	}
	sprintf(conncomp,"%sccp",FN);
	connectedcomps = fopen(conncomp,"w");
	fwrite(CCP,NrPixels*NrPixels*sizeof(pixelvalue),1,connectedcomps);
	fclose(connectedcomps);
	free(CCP);*/
	FreeMemMatrixInt(ConnectedComponents,NrPixels);
	int RegNr,NrPixelsThisRegion;
	int **MaximaPositions;
	double *MaximaValues;
	int **UsefulPixels;
	double *z;
	MaximaPositions = allocMatrixInt(NrPixels*10,2);
	MaximaValues = malloc(NrPixels*10*sizeof(*MaximaValues));
	UsefulPixels = allocMatrixInt(NrPixels*10,2);
	z = malloc(NrPixels*10*sizeof(*z));
	int IsSaturated;
	int SpotIDStart = 1;
	char OutFile[1024];
	if (Padding == 2) {sprintf(OutFile,"%s/%s_%02d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	else if (Padding == 3) {sprintf(OutFile,"%s/%s_%03d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	else if (Padding == 4) {sprintf(OutFile,"%s/%s_%04d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	else if (Padding == 5) {sprintf(OutFile,"%s/%s_%05d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	else if (Padding == 6) {sprintf(OutFile,"%s/%s_%06d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	else if (Padding == 7) {sprintf(OutFile,"%s/%s_%07d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	else if (Padding == 8) {sprintf(OutFile,"%s/%s_%08d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	else if (Padding == 9) {sprintf(OutFile,"%s/%s_%09d_%d_PS.csv",OutFolderName,FileStem,FileNr,RingNr);}
	FILE *outfilewrite;
	outfilewrite = fopen(OutFile,"w");
	fprintf(outfilewrite,"SpotID IntegratedIntensity Omega(degrees) YCen(px) ZCen(px) IMax Radius(px) Eta(degrees) SigmaR SigmaEta\n");
	int TotNrRegions = NrOfReg;
	for (RegNr=1;RegNr<=NrOfReg;RegNr++){
		NrPixelsThisRegion = PositionTrackers[RegNr];
		if (NrPixelsThisRegion == 1){
			TotNrRegions--;
			continue;
		}
		for (i=0;i<NrPixelsThisRegion;i++){
			UsefulPixels[i][0] = (int)(Positions[RegNr][i]/NrPixels);
			UsefulPixels[i][1] = (int)(Positions[RegNr][i]%NrPixels);
			z[i] = ImgCorrBC[((UsefulPixels[i][0])*NrPixels) + (UsefulPixels[i][1])];
		}
		unsigned nPeaks;
		nPeaks = FindRegionalMaxima(z,UsefulPixels,NrPixelsThisRegion,MaximaPositions,MaximaValues,&IsSaturated,IntSat);
		if (IsSaturated == 1){ //Saturated peaks removed
			TotNrRegions--;
			continue;
		}
		double *IntegratedIntensity, *IMAX, *YCEN, *ZCEN, *Rads, *Etass, *OtherInfo;
		IntegratedIntensity = malloc(nPeaks*2*sizeof(*IntegratedIntensity));
		memset(IntegratedIntensity,0,nPeaks*2*sizeof(*IntegratedIntensity));
		IMAX = malloc(nPeaks*2*sizeof(*IMAX));
		YCEN = malloc(nPeaks*2*sizeof(*YCEN));
		ZCEN = malloc(nPeaks*2*sizeof(*ZCEN));
		Rads = malloc(nPeaks*2*sizeof(*Rads));
		Etass = malloc(nPeaks*2*sizeof(*Etass));
		OtherInfo = malloc(nPeaks*10*sizeof(*OtherInfo));
		int *NrPx;
		NrPx = malloc(nPeaks*2*sizeof(*NrPx));
		printf("%d %d %d %d\n",RegNr,NrOfReg,NrPixelsThisRegion,nPeaks);
		Fit2DPeaks(nPeaks,NrPixelsThisRegion,z,UsefulPixels,MaximaValues,MaximaPositions,IntegratedIntensity,IMAX,YCEN,ZCEN,Rads,Etass,Ycen,Zcen,Thresh,NrPx,OtherInfo);
		for (i=0;i<nPeaks;i++){
			fprintf(outfilewrite,"%d %f %f %f %f %f %f %f ",(SpotIDStart+i),IntegratedIntensity[i],Omega,YCEN[i]+Ycen,ZCEN[i]+Zcen,IMAX[i],Rads[i],Etass[i]);
			for (j=0;j<2;j++) fprintf(outfilewrite, "%f ",OtherInfo[2*i+j]);
			fprintf(outfilewrite,"\n");
		}
		SpotIDStart += nPeaks;
		free(IntegratedIntensity);
		free(IMAX);
		free(YCEN);
		free(ZCEN);
		free(Rads);
		free(Etass);
		free(NrPx);
	}
	printf("Number of regions = %d\n",TotNrRegions);
	printf("Number of peaks = %d\n",SpotIDStart-1);
	fclose(outfilewrite);
	free(ImgCorrBC);
	free(PositionTrackers);
	free(z);
	free(MaximaValues);
    //FreeMemMatrixInt(Positions,nOverlapsMaxPerImage);
	FreeMemMatrixInt(MaximaPositions,NrPixels*10);
	FreeMemMatrixInt(UsefulPixels,NrPixels*10);
	end = clock();
	diftotal = ((double)(end-start))/CLOCKS_PER_SEC;
    printf("Time elapsed: %f s.\n",diftotal);
    return 0;
}
Beispiel #6
0
void TR()
{
#if defined(DEBUG) && defined(_MSC_VER)
    _CrtSetDbgFlag(0);	// too expensive
#endif

    const char *HitFileName = RequiredValueOpt("tr");
    const char *OutFileName = RequiredValueOpt("out");
    const char *CandFileName = ValueOpt("cand");

    const char *strMinTrSpacing = ValueOpt("mintrspacing");
    const char *strMaxTrSpacing = ValueOpt("maxtrspacing");
    const char *strMinTrLength = ValueOpt("mintrlength");
    const char *strMaxTrLength = ValueOpt("minspacingratio");
    const char *strMinFam = ValueOpt("minfam");
    const char *strMinHitRatio = ValueOpt("minhitratio");
    const char *strMinDistPairs = ValueOpt("mindistpairs");

    if (0 != strMinTrSpacing)
        MIN_LENGTH_LINE = atoi(strMinTrSpacing);
    if (0 != strMaxTrSpacing)
        MAX_LENGTH_LINE = atoi(strMaxTrSpacing);
    if (0 != strMinTrLength)
        MIN_LENGTH_LTR = atoi(strMinTrLength);
    if (0 != strMaxTrLength)
        MAX_LENGTH_LTR = atoi(strMaxTrLength);
    if (0 != strMinFam)
        MIN_FAM_SIZE = atoi(strMinFam);
    if (0 != strMinHitRatio)
        MIN_HIT_LENGTH_RATIO = atoi(strMinHitRatio);
    if (0 != strMinDistPairs)
        MIN_DIST_EDGE = atoi(strMinDistPairs);

    FILE *fHit = OpenStdioFile(HitFileName, FILEIO_MODE_ReadOnly);

    ProgressStart("Index hits");
    GLIX HitGlix;
    HitGlix.Init();
    HitGlix.FromGFFFile(fHit);
    HitGlix.MakeGlobalToLocalIndex();
    ProgressDone();

    const int GlobalLength = HitGlix.GetGlobalLength();
    IIX IntervalIndex;
    IntervalIndex.Init(GlobalLength);

    ProgressStart("Find candidate TRs");
    Rewind(fHit);
    GFFRecord Rec;
    while (GetNextGFFRecord(fHit, Rec))
    {
        HitData Hit;
        GFFRecordToHit(HitGlix, Rec, Hit);
        if (IsCandLTR(Hit))
            AddCand(Hit, IntervalIndex);
    }
    ProgressDone();

    Progress("%d candidates", CandCount);

    if (0 != CandFileName)
    {
        ProgressStart("Write candidates");
        FILE *fCand = OpenStdioFile(CandFileName, FILEIO_MODE_WriteOnly);
        WriteCands(fCand, HitGlix);
        ProgressDone();
    }

    ProgressStart("Make graph");
    Rewind(fHit);
    while (GetNextGFFRecord(fHit, Rec))
    {
        HitData Hit;
        GFFRecordToHit(HitGlix, Rec, Hit);
        FindEdges(Hit, HitGlix, IntervalIndex);
    }
    fclose(fHit);
    fHit = 0;

    ProgressDone();

    Progress("%d edges", (int) Edges.size());

    ProgressStart("Find families");
    FamList Fams;
    FindConnectedComponents(Edges, Fams, MIN_FAM_SIZE);
    ProgressDone();

    Progress("%d families", (int) Fams.size());

    FILE *fOut = OpenStdioFile(OutFileName, FILEIO_MODE_WriteOnly);
    WriteOutputFile(fOut, HitGlix, Fams);
}
Beispiel #7
0
void TRS()
	{
	const char *InputFileName = RequiredValueOpt("trs");

	const char *OutputFileName = ValueOpt("out");
	const char *PilesFileName = ValueOpt("piles");
	const char *ImagesFileName = ValueOpt("images");

	const char *strMinFamSize = ValueOpt("famsize");
	const char *strMaxLengthDiffPct = ValueOpt("maxlengthdiffpct");
	g_paramSingleHitCoverage = !FlagOpt("multihit");

	if (0 == OutputFileName && 0 == PilesFileName && 0 == ImagesFileName)
		Quit("No output file specified, must be at least one of -out, -piles, -images");

	if (0 != strMinFamSize)
		g_paramMinFamSize = atoi(strMinFamSize);
	if (0 != strMaxLengthDiffPct)
		g_paramMaxLengthDiffPct = atoi(strMaxLengthDiffPct);

	Log("singlehit=%s famsize=%d maxlengthdiffpct=%d\n",
	  g_paramSingleHitCoverage ? "True" : "False",
	  g_paramMinFamSize,
	  g_paramMaxLengthDiffPct);

	ProgressStart("Read hit file");
	int HitCount;
	int SeqLength;
	HitData *Hits = ReadHits(InputFileName, &HitCount, &SeqLength);
	ProgressDone();

	Progress("%d hits", HitCount);

	SeqLengthChunks = (SeqLength + CHUNK_LENGTH - 1)/CHUNK_LENGTH;

	const int BitVectorLength = (SeqLengthChunks + BITS_PER_INT - 1)/BITS_PER_INT;
	int *CopyCount = all(int, BitVectorLength);
	zero(CopyCount, int, BitVectorLength);

	ProgressStart("Compute copy counts");
	for (int i = 0; i < HitCount; ++i)
		IncCopyCount(CopyCount, Hits[i]);
	ProgressDone();

	ProgressStart("Identify piles");
	PILE_INDEX_TYPE *PileIndexes = IdentifyPiles(CopyCount);
	ProgressDone();

	Progress("%d stacks", PileCount);

	freemem(CopyCount);
	CopyCount = 0;

	CreatePiles(Hits, HitCount, PileIndexes);

	if (0 != ImagesFileName)
		{
		ProgressStart("Writing images file");
		WriteImages(ImagesFileName, Hits, HitCount, PileIndexes);
		ProgressDone();
		}

	freemem(Hits);
	Hits = 0;

	if (0 != PilesFileName)
		{
		ProgressStart("Writing piles file");
		WritePiles(PilesFileName, Piles, PileCount);
		ProgressDone();
		}

	freemem(PileIndexes);
	PileIndexes = 0;

	if (0 == OutputFileName)
		return;

	ProgressStart("Find edges");
	EdgeList Edges;
	FindGlobalEdges(Edges, MaxImageCount);
	ProgressDone();

	Progress("%d edges", (int) Edges.size());

	ProgressStart("Find families");
	FamList Fams;
	FindConnectedComponents(Edges, Fams, g_paramMinFamSize);
	AssignFamsToPiles(Fams);
	ProgressDone();

	Progress("%d families", (int) Fams.size());

	ProgressStart("Find superfamilies");
	EdgeList SuperEdges;
	FindSuperFamEdges(Fams, SuperEdges);

	FamList SuperFams;
	FindConnectedComponents(SuperEdges, SuperFams, 1);
	FindSingletonSuperFams(Fams, SuperFams);

	AssignSuperFamsToPiles(Fams, SuperFams);
	ProgressDone();

	Progress("%d superfamilies", (int) SuperFams.size());

	ProgressStart("Write TRS output file");
	WriteTRSFile(OutputFileName, Piles, PileCount);
	ProgressDone();
	}