⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shapefile.cpp

📁 这是个人脸识别程序
💻 CPP
字号:
// $masm\shapefile.cpp 1.5 milbo$ routines for shape files// Warning: this is raw research code -- expect it to be quite messy.// milbo durban May06//-----------------------------------------------------------------------------// This program is free software; you can redistribute it and/or modify// it under the terms of the GNU General Public License as published by// the Free Software Foundation; either version 2 of the License, or// (at your option) any later version.//// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the// GNU General Public License for more details.//// A copy of the GNU General Public License is available at// http://www.r-project.org/Licenses///-----------------------------------------------------------------------------#include "all.hpp"//-----------------------------------------------------------------------------void CheckShapeFileMagicNumber (FILE *pFile, const char sFile[]){char s[SLEN];										// read magic numberif (NULL == fgets(s, PLEN-1, pFile))	Err("Can't read %s", sFile);if (s[0] != 's' || s[1] != 's')	SysErr("%s is not a shape file (first two chars aren't \"ss\")", sFile);}//-----------------------------------------------------------------------------// On entry: nShapes is the max nbr of shapes you want to read. It is updated to// the number of shapes that were actually read.//// If sTagRegExp is not null, then we ignore fAllShapes and TestSetsMaskvoid ReadShapeFile (MatVec *pMats, StringVec &Strings, char sImageDirs[], 	// out					const char *sTagRegExp,									// in					unsigned Mask1, unsigned Mask2,							// in: only read matrices where Attr&Mask1 == Mask2 (Attr is hex part of tag string)					const char sShapeFile[], bool fVerbose) 				// in{lprintf("Opening %s\n", sShapeFile);FILE *pShapeFile = fopen(sShapeFile, "r");		// Fopen checks internally if file opens ok and issues err msg if need beif (!pShapeFile)	Err("Can't open %s", sShapeFile);CheckShapeFileMagicNumber(pShapeFile, sShapeFile);GetImageDirsFromShapeFile(sImageDirs, sShapeFile, pShapeFile);lprintf("Reading shapes");if (sTagRegExp[0])	lprintf(" matching \"%s\"", sTagRegExp);if (Mask1 || Mask2)	{	lprintf(" Mask1 %x [%s]",  Mask1, sGetAtFaceString(Mask1, false));	lprintf(" Mask2 %x [%s]",  Mask2, sGetAtFaceString(Mask2, false));	}lprintf("\n");ReadMatVec(pMats, &Strings, sShapeFile, pShapeFile, sTagRegExp, Mask1, Mask2, 0, MAT_NO_CHECK_SAME_DIM, fVerbose, fVerbose);fclose(pShapeFile);}//-----------------------------------------------------------------------------// Return a sample of Shapes (without replacement) with sample size nWantedShapes//// If nSeed==0 then it's simply the first nWantedShapes in Shapes//// If nSeed!=0 is TRUE then it's a random sample, with nSeed as the seed for the rand number generator.// There is a twist: we always keep the first shape in Shapes and always keep it first.// This is because some of the ASM routines assume that the first shape is the reference shape.// The shapes in the new Shapes are in the same order as they were in the old Shapes.#define CONF_iGenForSelectNShapes 1static int nMyRand(int n) { return Rand(n, CONF_iGenForSelectNShapes); }	// auxilary function for random_shufflestatic void SelectNShapes (ShapeVec *pShapes, 	// io					StringVec &TagStrings,		// io: also shuffled, in step with Shapes					int nWantedShapes,			// in: 0 means keep all					int nSeed=0)				// in: 0 means no random selection; if any other val select randomly with rand seed=nSeed{int nShapes = TagStrings.size();nWantedShapes = __min(nWantedShapes, nShapes);// generate a shuffled set of indices in iShuffledShapesIntVec iShuffledShapes(nShapes-1);					// -1 because first shape excludedfor (int iShape = 0; iShape < nShapes-1; iShape++)	// start at 1 to exclude first shape from shuffle	iShuffledShapes[iShape] = iShape+1;if (nSeed)	{	SeedRand(nSeed, CONF_iGenForSelectNShapes);	random_shuffle(iShuffledShapes.begin(), iShuffledShapes.end(), pointer_to_unary_function<int,int>(nMyRand));	}iShuffledShapes.resize(nWantedShapes-1);// sort the selected indices so we can do an in-place replacement in pShapessort(iShuffledShapes.begin(), iShuffledShapes.end());// keep the first nWantedShapes in iShuffledShapesfor (iShape = 1; iShape < nWantedShapes; iShape++)	// start at 1 so first shape stays put	{	int iOldShape = iShuffledShapes[iShape-1];	if (pShapes)		(*pShapes)[iShape] = (*pShapes)[iOldShape];	TagStrings[iShape] = TagStrings[iOldShape];	}if (pShapes)	pShapes->resize(nWantedShapes);TagStrings.resize(nWantedShapes);}//-----------------------------------------------------------------------------// If pShapes is null then we just get TagStringsvoid ReadSelectedShapes (ShapeVec *pShapes, StringVec &TagStrings, char sImageDirs[], // out: pShapes is optional						int nWantedShapes, const char sTagRegExp[],					// in						unsigned Mask1, unsigned Mask2,								// in: only read matrices where Attr&Mask1 == Mask2 (Attr is hex part of tag string)						int nSeed,													// in: 0 means no random selection; any other val select randomly with rand seed=nSeed						tSampleSpec *pSampleSpec,									// in						const char sShapeFile[], bool fVerbose)						// in{ReadShapeFile(pShapes, TagStrings, sImageDirs, sTagRegExp, Mask1, Mask2, sShapeFile, fVerbose);DiscardGlobalFaceDetectorShapes(pShapes, TagStrings, AT_DISCARD_UNDERSCORES);int nShapes = TagStrings.size();if (nShapes == 0)	Err("No shapes");if (nWantedShapes > nShapes)	Err("Want %d shapes but there are only %d shapes", nWantedShapes, nShapes);if (nWantedShapes != 0)	SelectNShapes(pShapes, TagStrings, nWantedShapes, nSeed);if (sTagRegExp[0] || Mask1!=0 || Mask2!=0)	if (pSampleSpec && pSampleSpec->sFile[0])		SysErr("ReadSelectedShapes"); 	// you can't specify BOTH ways of choosing shapesif (pSampleSpec)	{	if (pSampleSpec->i > 0)	//TODO this is wrong for ms.exe		Err("SampleSpec I is %d but it should be less than 0 (because for training you EXCLUDE one set)", pSampleSpec->i);	GetShapesSpecifiedBySampleSpec(pShapes, TagStrings, *pSampleSpec, fVerbose);	}if (nWantedShapes)	if (nSeed)		lprintf("Selected a random sample of %d shape%s from %d shape%s (seed=%d)\n",			nWantedShapes, ((nWantedShapes==1)? "":"s"), nShapes, ((nShapes==1)? "":"s"), nSeed);	else		lprintf("Selected the first %d shape%s of %d shape%s\n",			nWantedShapes, ((nWantedShapes==1)? "":"s"), nShapes, ((nShapes==1)? "":"s"));else	lprintf("Got %d shape%s\n", nShapes, ((nShapes==1)? "":"s"));}//-------------------------------------------------------------------------------int iFindString (const char s[], const StringVec &Strings, int iOffset){for (int i = 0; i < Strings.size(); i++)	if (0 == strcmp(Strings[i].c_str()+iOffset, s+iOffset))		break;if (i < Strings.size())	return i;else	return -1;	// not found}//-----------------------------------------------------------------------------// Copy sOldShapeFile to sNewShapeFile but replace shapes that are in Shapesvoid UpdateShapeFile (const char sNewShapeFile[], const char sOldShapeFile[],						const ShapeVec &Shapes, const StringVec &TagStrings, int nNewShapes, int nWantedPoints,						const char sHeader[]){FILE *pIn = Fopen(sOldShapeFile, "r");FILE *pOut = Fopen(sNewShapeFile, "w");time_t ltime; time(&ltime);int nUpdated = 0;bool fPrint = true;char sLine[SLEN];bool fWrittenUpdateComment = false;while (fgets(sLine, SLEN-1, pIn))	{	if (sLine[0] == '"' && (strstr(sLine, ".bmp") || strstr(sLine, ".pgm") || strstr(sLine, ".jpg")))		{		char sStripped[SLEN];		// sLine with first and last quote removed		strcpy(sStripped, &sLine[1]);		int iLen = strlen(sStripped)-2;		DASSERT(iLen > 0);		sStripped[iLen] = 0;		int iNewShape = iFindString(sStripped, TagStrings, 0);		if (iNewShape >= 0)	// found shape in file?			{			fPrint = false;			nUpdated++;			Fprintf(pOut, "\"%s\"\n", TagStrings[iNewShape].c_str());			SHAPE Shape;	// ConvertShapeFromInternalFormat will resize			ConvertShapeFromInternalFormat(Shape, Shapes[iNewShape], TagStrings[iNewShape].c_str(), nWantedPoints);			Shape.write(sNewShapeFile, pOut, QUIET, NULL, "%.2f");			}		}	if (fPrint)		Fprintf(pOut, sLine);	if (sLine[0] == '}')		fPrint = true;	// Write update line after comment line with the word "Edits" or after first non comment line	if (!fWrittenUpdateComment && sLine[0] != '#')		{		Fprintf(pOut, "# %s %s", sHeader, ctime(&ltime));		fWrittenUpdateComment = true;		}	}fclose(pIn);fclose(pOut);lprintf("\n");if (nUpdated != nNewShapes)	Warn("%s has %d shapes but only found %d of them in %s", sNewShapeFile, nNewShapes, nUpdated, sOldShapeFile);}//-----------------------------------------------------------------------------void WriteShapeFile (const char sShapeFile[], const ShapeVec &Shapes, StringVec &TagStrings,					  int nShapes, int nWantedPoints, const char sHeader[], const char sImageDirs[]){FILE *pShapeFile = Fopen(sShapeFile, "w");time_t ltime; time(&ltime);Fprintf(pShapeFile, "ss %s\n", sShapeFile);	// magic number and file nameFprintf(pShapeFile, "# %s %s\n", sHeader, ctime(&ltime));Fprintf(pShapeFile, "Directories %s   # image directories\n\n", sImageDirs);// Fprintf(pShapeFile, "%d   # Total number of shapes\n\n", nShapes);for (int iShape = 0; iShape < nShapes; iShape++)	{	if (TagStrings[iShape][0])		Fprintf(pShapeFile, "\"%s\"\n", TagStrings[iShape].c_str());	SHAPE Shape(1,2);	// ConvertShapeFromInternalFormat will resize	ConvertShapeFromInternalFormat(Shape, Shapes[iShape], TagStrings[iShape].c_str(), nWantedPoints);	Shape.write(sShapeFile, pShapeFile, QUIET, NULL, "%.2f");	}fclose(pShapeFile);lprintf("\n");}//-----------------------------------------------------------------------------// return the first shape in TagStrings that has face attributes which// mask Mask1 and Mask2static int iGetRefShapeIndex1 (const StringVec &TagStrings, unsigned Mask1, unsigned Mask2){for (int iShape = 0; iShape < TagStrings.size(); iShape++)	{	unsigned Tag;	if (1 != sscanf(TagStrings[iShape].c_str(), "%x", &Tag))		SysErr("GetRefShapeIndex: can't read tag");	if ((Tag & Mask1) == Mask2)		return iShape;		// found it	}return -1;	// not found}//-----------------------------------------------------------------------------int iGetRefShapeIndex (const ShapeVec &Shapes, const StringVec &TagStrings, unsigned Mask1, unsigned Mask2){// we OR in FA_Rowley etc because we never use such shapes as a reference shapeint iRefShape = iGetRefShapeIndex1(TagStrings, (Mask1|FA_ViolaJones|FA_Rowley|FA_Test1|FA_Test2), Mask2);if (iRefShape < 0)	SysErr("ReadShapes: can't find reference shape");const char *sRefShape = TagStrings[iRefShape].c_str()+FNAME_OFFSET;if (iRefShape != 0)	Warn("Reference shape %d %s is not the first shape", iRefShape, sRefShape);lprintf("Reference shape %s has %d landmarks, ", sRefShape, Shapes[iRefShape].nrows());return iRefShape;}//-----------------------------------------------------------------------------// On return sImageDirs will be a string holding the image directories in sShapeFile.// We assume pShapeFile points to the string on entry (or to comments preceding it).// We assume sImageDirs is big enough// On return, will *psImageDirs will be something like "c:/dir1;c:/dir2;"void GetImageDirsFromShapeFile (char sImageDirs[],									// out									const char sShapeFile[], FILE *pShapeFile)	// in (but pShapeFile updated){char s[PLEN];Fgets(s, PLEN-1, pShapeFile);char *sWhiteSpace = " \t\n\r";char *sToken = strtok(s, sWhiteSpace);if (!sToken || 0 != strcmp(sToken, "Directories"))	SysErr("Can't find image directory prefix \"Directories\" in %s", sShapeFile);sToken = strtok(NULL, sWhiteSpace);if (!sToken)	SysErr("Can't find image directory in %s", sShapeFile);strcpy(sImageDirs, sToken);}//-----------------------------------------------------------------------------// Find Shape in sShapeFile by matching its tag string against sTagRegExp// sTagRegExp is a regular expression specifying the shape header stringbool fGetNamedShape (SHAPE &Shape, 															// out				 	const char sTagRegExp[], const char sShapeFile[], bool fPlainString,	// in					bool fBrief){bool fSuccess = true;FILE *pShapeFile = Fopen(sShapeFile, "r");							// Fopen will complain if can't open filechar sImageDirs[SLEN];CheckShapeFileMagicNumber(pShapeFile, sShapeFile);GetImageDirsFromShapeFile(sImageDirs, sShapeFile, pShapeFile);		// get image directories string, discard itchar sMatHeader[PLEN];int nShape = iReadSelectedMatGivenRegExp(Shape, sMatHeader, sShapeFile, pShapeFile, sTagRegExp, fPlainString);if (nShape < 0)	{	lprintf("Can't find \"%s\" in %s (or index file)\n", sTagRegExp, sShapeFile);	fSuccess = false;	}else	bprintf(fBrief, "\"%s\"", sMatHeader);fclose(pShapeFile);return fSuccess;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -