Пример #1
0
int Flow::createVarY()
{
	int nvars = 0;
	double coeff = 0.0;
	double lb = 0.;
	double ub = 1.;
	VariableHash::iterator vit;
	Variable::VARTYPE varType = Variable::V_Y;
	Column::COLTYPE colType = Column::COLTYPE::BINARY;

	for (int sIt = 0; sIt < g->nTerminals; ++sIt)
	{
		Vertex s = g->terminals[sIt];
		for (int tIt = 0; tIt < g->nTerminals; ++tIt)
		{
			Vertex t = g->terminals[tIt];

			if (s.getCode() == t.getCode())
				continue;

			for (int i = 1; i <= g->nVertices; ++i)
			{
				for (int j = 0; j < g->adjList[i].size(); ++j)
				{
					Arc arc = g->adjList[i][j];

					Variable y(colType, coeff, lb, ub);
					y.setType(varType);
					y.setVertex1(s);
					y.setVertex2(t);
					y.setArc(arc);

					vit = vHash[varType].find(y);
					if (vit != vHash[varType].end())
						continue;

					bool isInserted = addCol(&y);
					if (isInserted)
					{
						y.setColIdx(getNCols() - 1);
						vHash[varType][y] = y.getColIdx();
						++nvars;
					}
				}
			}
		}
	}

	return nvars;
}
Пример #2
0
void Image2D<T>::printEntireImage (int Nx90)
{
        cout << "Image2D<T>: Rotation by 90*" << Nx90 << "=" << Nx90*90 << " degree" << endl;

	cout << "   ncols=" << this->getNCols(Nx90)
	     << "   nrows=" << this->getNRows(Nx90)
             << endl;

	for (size_t row = 0; row < getNRows(Nx90); row++) {
	  for (size_t col = 0; col < getNCols(Nx90); col++) {

	    cout << this->rotN90 (row,col,Nx90) << "  ";
	  }
	    cout << endl;
	}
}
Пример #3
0
int FacilityLocation::createVarY()
{
	int nVars = 0;
	double coeff = 0.0;
	double lb = 0.;
	double ub = 1.;
	VariableHash::iterator vit;
	Variable::VARTYPE varType = Variable::V_Y;
	Column::COLTYPE colType = choseColType(pType, lb, ub);
	// @teste
	colType = Column::CONTINUOUS;

	// * Variable y_i:
	// *
	// * Used to indicate whether the vertex i \in I is a core vertex (Steiner
	// * vertex) in the solution.
	for (int i = 1; i <= g->nVertices; ++i)
	{
		Vertex* v = &(g->vertices[i]);

		// @annotation: comment next filter to resolve instances where
		// the vpn terminals may be considered internal nodes
		// 20160125
		if (v->isTerminal())
			continue;

		Variable var(colType, coeff, lb, ub);
		var.setType(varType);
		var.setVertex1(*v);

		vit = vHash[varType].find(var);
		if (vit != vHash[varType].end())
			continue;

		bool isInserted = addCol(&var);
		if (isInserted)
		{
			var.setColIdx(getNCols() - 1);
			vHash[varType][var] = var.getColIdx();
			++nVars;
		}
	}

	return nVars;
}
Пример #4
0
int main(int nargin, char** argv){
  if(nargin != 4){
    printf("Usage: p1 <greylevel img> <threshold> <output file>");
    return -1;
  }
  
  im = (Image*) malloc(sizeof(Image));
  thresh = atoi(argv[2]);
  readImage(im, argv[1]);
  int i, j;
  setColors(im, 1);
  for(i = 0; i < getNRows(im); i++){
    for(j = 0; j < getNCols(im); j++){
      setPixel(im, i, j, getPixel(im, i, j) > thresh);
    }
  }
  writeImage(im, argv[3]);
}
Пример #5
0
/** Calculate the the number of holes in the object o of the image i 
 * The function attempts to reverse the idea of sequential labeling 
 * in order to find black spots on objects
 * It still needs work.
 * TODO Make this work properly
 * */
void euler(Image *im, Object *o)
{
	int i, j, k, c, neighbors[NNEIGHB], 
		 newObj, left, right;

	LabelMap lm=makeLabelMap(im);

	/* this sets up a dummy class for background darkness */
	addLabel(&lm);
	for (i=0; i < getNRows(im); ++i)
		for (j=0; j < getNCols(im); ++j)
			if (!getPixel(im, i, j)) setLabel(&lm, i, j, 1);

	for (i=o->top; i <= o->bottom; ++i) {
		left=-1;
		for (j=o->left; j <= o->right; ++j) {
			if (getPixel(im, i, j) == o->label) {
				if (left < 0) left=j; /* left edge for this row */
				right=j; /* right-most so far */
			} 
		}
		for (j=left; j <= right; ++j) {
			if (!getPixel(im, i, j)) {
				newObj=getNeighbors(&lm, i, o->top, j, left, neighbors);
				if (newObj) {
					addLabel(&lm);
					c=getNLabels(&lm);
				} else {
					for (k=0; k < NNEIGHB; ++k)
						if (neighbors[k] > 0) {
							c=evalNeighbor(k, &lm, neighbors);
							break; /* break since finding one means checking the rest */
						}
				}
				setLabel(&lm, i, j, c);
			}
		}
	}

	o->holes=getNClasses(&lm)-1; /* number is off by one because of dummy class */
	freeLabelMap(&lm);
}
Пример #6
0
int writeImage(const Image *im, const char *fname) {
  FILE *output; 
  int nRows;
  int nCols;
  int colors;
  int i, j;
    
  /* open the file */
  if (!fname || (output=fopen(fname,"wb"))==0)
    return(-1);

  nRows=getNRows(im);
  nCols=getNCols(im);
  colors=getColors(im);

  /* write the header */
  fprintf(output,"P5\n"); /* magic number */
  fprintf(output,"#\n");  /* empty comment */
  fprintf(output,"%d %d\n%03d\n",nCols,nRows,colors); /* image info */

  /* write pixels row by row */
  for(i=0;i<nRows;i++)
  {
    for(j=0;j<nCols;j++)
    {
      int byte=getPixel(im,i,j);

      if (fputc(byte,output)==EOF) /* couldn't write */
      {
	    fclose(output);
	    return -1;
      }      
    }
  }
  
  /* close the file */
  fclose(output);
  return 0; /* OK */
}
Пример #7
0
void Image2D<T>::saveImageInFile (const std::string &fname, int Nx90)
{
    cout << "Image2D<T>::saveImageInFile: ";

    ofstream file; 
    file.open(fname.c_str(),ios_base::out);

        for (size_t row = 0; row < getNRows(Nx90); row++) {
          for (size_t col = 0; col < getNCols(Nx90); col++) {

            file << this->rotN90 (row,col,Nx90) << "  ";
          }
            file << endl;
        }

    file.close();
    cout << "The 2x1 image (ncols,nrows="
         << this->getNCols(Nx90) << ","
         << this->getNRows(Nx90)
         << " with rotation by 90*" << Nx90 << "=" << Nx90*90 << " degree)" 
         << " is saved in file " << fname << endl; 
}
Пример #8
0
int Flow::createVarX()
{
	int nvars = 0;
	double coeff = 1.0;
	double lb = 0.;
	double ub = 1e20;
	VariableHash::iterator vit;
	Variable::VARTYPE varType = Variable::V_X;
	Column::COLTYPE colType = Column::COLTYPE::CONTINUOUS;

	for (int i = 1; i <= g->nVertices; ++i)
	{
		for (int j = 0; j < g->adjList[i].size(); ++j)
		{
			Arc arc = g->adjList[i][j];

			Variable x(colType, coeff, lb, ub);
			x.setType(varType);
			x.setArc(arc.toEdge());

			vit = vHash[varType].find(x);
			if (vit != vHash[varType].end())
				continue;

			bool isInserted = addCol(&x);
			if (isInserted)
			{
				x.setColIdx(getNCols() - 1);
				vHash[varType][x] = x.getColIdx();
				++nvars;
			}
		}
	}

	return nvars;
}
Пример #9
0
int main(int argc, char *argv[])
{
	int threshold, rh, theta, rows, cols, rScale, tScale, hitImage, i;
	char *inputo, *inputh, *inpute, *outputl;
	float r, t, diag, x, y, c, s;
	Image io, ih, ie;

	if (argc < 5) {
		fprintf(stderr, "usage: %s <input original scene image> <input hough image> <input thresholded image> <hough threshold> <cropped line-detected output image>\n", argv[0]);
		exit(0);
	}

	inputo = argv[1];
	inputh = argv[2];
	inpute = argv[3];
	if (sscanf(argv[4], "%d", &threshold) != 1) {
		fprintf(stderr, "error: threshold not an integer\n");
		exit(1);
	}
	outputl = argv[5];

	if (readImage(&io, inputo) == -1) {
		std::cerr << "Error reading file " << inputo << "\n";
		exit(1);
	} else if (readImage(&ih, inputh) == -1) {
		std::cerr << "Error reading file " << inputh << "\n";
		exit(1);
	} else if (readImage(&ie, inpute) == -1) {
		std::cerr << "Error reading file " << inpute << "\n";
		exit(1);
	}	
	rows = getNRows(&io);
	cols = getNCols(&io);
	diag = sqrt(pow(rows, 2) + pow(cols, 2));
	rScale = getNRows(&ih);
	tScale = getNCols(&ih);

	for (rh = 0; rh < rScale; ++rh) {
		for (theta = 0; theta < tScale; ++theta) {
			if (getPixel(&ih, rh, theta) >= threshold) {
				r = ((2*diag)/rScale)*rh - diag;
				t = (PI/tScale)*theta - PI/2;
				c = cos(t);
				s = sin(t);

				x = -r*s; // cos(t + pi/2) = -sin(t)
				y = r*c; // sin(t + pi/2) = cos(t)
				if (inImage(&io, x, y)) {
       			x -= diag*c;
					y -= diag*s;
				}

				hitImage = 0;
				i = 0;
				while (!hitImage || inImage(&io, x + i*c, y + i*s)) {
					if (!hitImage && inImage(&io, x + i*c, y + i*s))
						hitImage = 1;
					if (hitImage && getPixel(&ie, y + i*s, x + i*c)) {
						setPixel(&io, y + i*s, x + i*c, 255);
					}
					i++;
				}
			}
		}
	}

	setColors(&io, 255);
	if (writeImage(&io, outputl) == -1) {
		std::cerr << "Error writing file " << outputl << "\n";
	}
	free(io.data);
	free(ih.data);
	free(ie.data);
}
Пример #10
0
int FacilityLocation::createVarZ()
{
	int nVars = 0;
	double coeff = 0.0;
	double lb = 0.;
	double ub = 1.;
	VariableHash::iterator vit;
	Variable::VARTYPE varType = Variable::V_Z;
	Column::COLTYPE colType = choseColType(pType, lb, ub);
	// @teste
	//colType = Column::CONTINUOUS;
	
	double bMinus = 0.;
	double bPlus = 0.;
	for (int i = 1; i <= g->nVertices; ++i)
	{
		bMinus += g->vertices[i].getIngree();
		bPlus += g->vertices[i].getEgree();
	}
	
	(bMinus < bPlus) ? coeff = bMinus : coeff = bPlus;

	// * Variable z_e:
	// *
	// * Used to indicate whether the edges e = (i, j) is used to connect the
	// * two core vertex i \in I and j \in I
	for (int i = 1; i <= g->nVertices; ++i)
	{
		Vertex* v = &(g->vertices[i]);

		// @annotation: comment next filter to resolve instances where
		// the vpn terminals may be considered internal nodes
		// 20160125
		if (v->isTerminal())
			continue;

		for (int j = 0; j < g->adjList[i].size(); ++j)
		{
			Vertex* u = &(g->adjList[i][j].getTail());
			Arc* arc = &(g->adjList[i][j]);

			// @annotation: comment next filter to resolve instances where
			// the vpn terminals may be considered internal nodes
			// 20160125
			if (arc->getHead().isTerminal() || arc->getTail().isTerminal())
				continue;

			Variable var(colType, coeff, lb, ub);
			var.setType(varType);
			var.setArc(arc->toEdge());

			vit = vHash[varType].find(var);
			if (vit != vHash[varType].end())
				continue;

			bool isInserted = addCol(&var);
			if (isInserted)
			{
				var.setColIdx(getNCols() - 1);
				vHash[varType][var] = var.getColIdx();
				++nVars;
			}
		}
	}

	return nVars;
}
Пример #11
0
int FacilityLocation::createVarX()
{
	int nVars = 0;
	double coeff = 0.0;
	double lb = 0.;
	double ub = 1.;
	VariableHash::iterator vit;
	Variable::VARTYPE varType = Variable::V_X;
	Column::COLTYPE colType = choseColType(pType, lb, ub);
	// @teste
	//colType = Column::CONTINUOUS;

	std::vector<std::vector<int> > dist((g->nVertices + 1), std::vector<int>((g->nVertices + 1), 0));

	clock_t start, end;

	start = clock();
	bfs(g, dist);
	end = clock();
#ifdef VERBOSE
	std::cout << "\nBFS_time: " << (end - start) / (double)CLOCKS_PER_SEC << "\n";
#endif

#ifdef DEBUG
	for (int i = 0; i <= g->nVertices; ++i)
	{
		for (int j = 0; j <= g->nVertices; ++j)
		{
			std::cout << i << " " << j << ": " << dist[i][j] << std::endl;
		}
	}
#endif

	// * Variable x_ip:
	// *
	// * Used to indicate whether the terminal vertex (client) p \in P is connected
	// * (or assigned) to the core vertex i \in I.

	double totalIngree = 0.;
	double totalEgree = 0.;
	for (int i = 1; i <= g->nVertices; ++i)
	{
		totalIngree += g->vertices[i].getIngree();
		totalEgree += g->vertices[i].getEgree();
	}

	for (int i = 1; i <= g->nVertices; ++i)
	{
		Vertex client = g->vertices[i];

		if (!client.isTerminal())
			continue;

		double tmp1 = std::min(g->vertices[i].getEgree(), totalIngree - g->vertices[i].getIngree());
		double tmp2 = std::min(g->vertices[i].getIngree(), totalEgree- g->vertices[i].getEgree());
		double b = tmp1 + tmp2;

		for (int j = 1; j <= g->nVertices; ++j)
		{
			Vertex router = g->vertices[j];
		
			// @annotation: comment next filter to resolve instances where
			// the vpn terminals may be considered internal nodes
			// 20160125
			if (client == router || router.isTerminal())
				continue;

			coeff = b * dist[client.getCode()][router.getCode()];

			Variable var(colType, coeff, lb, ub);
			var.setType(varType);
			var.setArc(Arc(router, client, 0.));

			vit = vHash[varType].find(var);
			if (vit != vHash[varType].end())
				continue;

			bool isInserted = addCol(&var);
			if (isInserted)
			{
				var.setColIdx(getNCols() - 1);
				vHash[varType][var] = var.getColIdx();
				++nVars;
			}
		}
	}

	return nVars;
}
Пример #12
0
SolverMIP::SOLVERSTAT FacilityLocation::solveLRExtentedFormulations(MulltipleCutSetSeparation _cutSetSepFunc, double _tol)
{
	int pos = 0;
	int nbCuts = 0;
	int sentinel = 0;
	int MAX_ITER = 100;
	int tailOffCounter = 0;
	int tailOffTol = 3;
	int printInterval = 5;
	double currentLp = 0., lastLp = 0.;
	bool noViolatedCutFound = true;
	std::set<long> hashTable;
	TypeVariableHashPtr vHashPtr = &(vHash);
	std::vector<std::set<int>*> cutSets;
	SolverMIP::SOLVERSTAT ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_UNKNOWN;

	if (xSol != NULL)
		delete[] xSol;

	xSol = new double[getNCols()];
	
	clock_t start = clock();
	do
	{
		lastLp = currentLp;
		status = SolverMIP::solve(SolverMIP::METHOD::METHOD_DUAL);

		if (status == SolverMIP::SOLVERSTAT::SOLVERSTAT_MIPOPTIMAL || status == SolverMIP::SOLVERSTAT::SOLVERSTAT_LPOPTIMAL ||
			status == SolverMIP::SOLVERSTAT::SOLVERSTAT_FEASIBLE)
		{
			ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_FEASIBLE;
			currentLp = getObjVal();

			// Getting fractional node solution
			getX();

			if (sentinel % printInterval == 0)
			{
				printf("\n---- iter: %d\n", sentinel + 1);
				printf("OBJ_VAL = %lf\n", currentLp);
			}

#ifndef DEBUG
			//Printing xNode solution
			printf("\n\n---- iter: %d\n", sentinel + 1);
			for (int varType = Variable::V_X; varType != Variable::V_UNKNOWN; varType += 10)
			{
				VariableHash::iterator vit = vHashPtr->at((Variable::VARTYPE)varType).begin();
				for (; vit != vHashPtr->at((Variable::VARTYPE)varType).end(); ++vit)
				{
					int idx = vit->second;

					if (xSol[idx] > SOLVER_EPS)
						std::cout << (vit->first).toString() << "(" << idx << "); " << xSol[idx] << std::endl;
					printf("");
				}
				printf("");
			}
#endif
			// Verifying optimality conditions
			if (fabs(currentLp - lastLp) < _tol)
			{
				++tailOffCounter;
				if (tailOffCounter > tailOffTol)
				{
					ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_LPOPTIMAL;
					break;
				}
			}
			else
				tailOffCounter = 0;

			// Calling the separation routine
			pos = cutSets.size();
			int cutSize = _cutSetSepFunc(g, vHashPtr, xSol, cutSets, true);

			// If a fractional cycle is found...
			if (cutSets.size() - pos > 0)
			{
				noViolatedCutFound = false;

				for (int i = pos; i < cutSets.size(); ++i)
				{
					std::set<int>* sPtr = cutSets[i];
					// Check whether the cut has already been generated
					unsigned long hashVal = hashFunc(*sPtr);
					std::set<long>::iterator it = hashTable.find(hashVal);
					if (it != hashTable.end())
					{
#ifdef DEBUG
						int warnCode = 990;
						std::string aux = convertSetToString(s);
						std::string msg = "The identified cut set was already separated " + convertSetToString(s);
						warningMsg(NULL, __func__, msg.data(), warnCode);
#endif
					}
					else
						hashTable.insert(hashVal);

					// ... we must find the cut set ...
					std::vector<Variable> cutSet;
					for (VariableHash::iterator vit = vHashPtr->at(Variable::V_Z).begin(); vit != vHashPtr->at(Variable::V_Z).end(); ++vit)
					{
						Variable z = vit->first;
						int head = z.getArc().getHead().getCode();
						int tail = z.getArc().getTail().getCode();

						std::set<int>::iterator hIt = sPtr->find(head);
						std::set<int>::iterator tIt = sPtr->find(tail);

						// ... which is composed by those arcs with one endpoint in S
						bool isHeadInS = hIt != sPtr->end();
						bool isTailInS = tIt != sPtr->end();
						if (!(isHeadInS && isTailInS) && (isHeadInS || isTailInS))
						{
							cutSet.push_back(z);
						}
					}

					// Identifying the y-variables involved in cut set constraints
					// And split them into two sets
					std::vector<Variable> sVec;
					std::vector<Variable> sCompVec;
					for (VariableHash::iterator vit = vHashPtr->at(Variable::V_Y).begin(); vit != vHashPtr->at(Variable::V_Y).end(); ++vit)
					{
						Variable v = vit->first;
						int nodeIdx = v.getVertex1().getCode();

						if (sPtr->find(nodeIdx) != sPtr->end())
						{
							sVec.push_back(v);
						}
						else
						{
							sCompVec.push_back(v);
						}
					}

					// Translating valid inequalities found into cplex/matrix representation
					int nzcnt = cutSet.size() + 2;
					std::vector<int> idx(nzcnt);
					std::vector<double> val(nzcnt);
					for (int i = 0; i < sVec.size(); ++i)
					{
						idx[0] = sVec[i].getColIdx();
						val[0] = -1.0;
						for (int j = 0; j < sCompVec.size(); ++j)
						{
							idx[1] = sCompVec[j].getColIdx();
							val[1] = -1.0;

							for (int k = 0; k < cutSet.size(); ++k)
							{
								idx[k + 2] = cutSet[k].getColIdx();
								val[k + 2] = 1.0;
							}

							// Adding user generated cut
							int nRows = 1;
							double rhs = -1;
							char sense = 'G';
							int rmatbeg = 0;
							int newColsAdded = 0;
							status = CPXaddrows(env, lp, newColsAdded, nRows, nzcnt, &rhs, &sense, &rmatbeg, &idx[0], &val[0], NULL, NULL);
							//status = CPXcutcallbackadd(_env, _cbdata, _wherefrom, nzcnt, -1, 'G', &idx[0], &val[0], CPX_USECUT_FORCE);
							if (status)
							{
								int warnCode = 999;
								std::string msg = "Failed to add integer cut.";
								warningMsg(NULL, __func__, msg.data(), warnCode);
							}
							else
								nbCuts++;

							printf("");
						}
					}
				}
#ifdef DEBUG
					// salva um arquivo .lp com o LP atual
					writeProbLP(".\\lpRelax");
#endif
			}
			else
			{
				// No violated cut was found
				noViolatedCutFound = true;
			}
		
			// If no violated cut was found
			if (noViolatedCutFound)
			{
				ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_LPOPTIMAL;
				break;
			}
		}
		else
		{
			int warnCode = 201;
			std::string msg = "Model is infeasible";
			warningMsg(typeid(*this).name(), __func__, msg.data(), warnCode);

			// salva um arquivo .lp com o LP atual
			writeProbLP(".\\infeasible");

			ret = SolverMIP::SOLVERSTAT::SOLVERSTAT_INFEASIBLE;
			break;
		}

	} while (++sentinel < MAX_ITER);

	// Deallocating memory
	for (int i = 0; i < cutSets.size(); ++i)
	{
		if (cutSets[i] != NULL)
		{
			delete cutSets[i];
			cutSets[i] = NULL;
		}
	}

	clock_t end = clock();
	printf("\n-----");
	printf("\n----- iter: %d", sentinel + 1);
	printf("\n----- OBJ_VAL = %lf", currentLp);
	printf("\n----- Exectution time: %.4f", (end - start) / (double)CLOCKS_PER_SEC);

	return ret;
}
Пример #13
0
int main(int nargin, char** argv){
  if(nargin != 5){
    printf("Usage: p5 <input gradient> <seed point> <mask> <output depth>");
    return -1;
  }
  
  int index, i,j;
  mask = (Image*) malloc(sizeof(Image));
  readImage(mask, argv[3]);
  
  FILE* file = fopen(argv[1], "rb");
  FILE* seeds = fopen(argv[2], "r");
  Gradient* grid = (Gradient*) malloc(sizeof(Gradient)*getNRows(mask)*getNCols(mask));
  fread(grid, getNRows(mask)*getNCols(mask), sizeof(Gradient), file);
  double** points = (double**) malloc(sizeof(double)*getNRows(mask));
  for(i = 0; i < getNRows(mask); i++) points[i] = (double*)malloc(sizeof(double)*getNCols(mask));
  double* allpoints = (double*) malloc(sizeof(double)*getNRows(mask)*getNCols(mask));

  char line[1024];
  int r = getNRows(mask), c = getNCols(mask);
  int max = 0;
  while(fgets(line, 1024, seeds) != NULL){
    int x0 = atoi(strtok(line, " "));
    int y0 = atoi(strtok(NULL, " "));
    for(i = 0; i < getNRows(mask); i++)
      for(j = 0; j < getNCols(mask); j++) 
	points[i][j] = 0;
    int x, y;
    for(x = x0-1; x >=0; x--)
      points[x][y0] = (points[x+1][y0] + (grid+x*r+y0)->p);
    for(x = x0+1; x < r; x++)
      points[x][y0] = (points[x-1][y0] - (grid+x*r+y0)->p);
    for(y = y0-1; y >=0; y--)
      points[x0][y] = (points[x0][y+1] + (grid+x0*r+y)->q);
    for(y = y0+1; y < r; y++)
      points[x0][y] = (points[x0][y-1] - (grid+x0*r+y)->q);
    
    for(x = x0-1; x >=0; x--){
      for(y = y0-1; y >=0; y--)
	points[x][y] = (0.5 * points[x][y+1] + (grid+x*r+y)->q +
			0.5 * points[x+1][y] + (grid+x*r+y)->p);
      for(y = y0+1; y < r; y++)
	points[x][y] = (0.5 * points[x][y-1] - (grid+x*r+y)->q +
			0.5 * points[x+1][y] + (grid+x*r+y)->p);
    }
    for(x = x0+1; x < r; x++){
      for(y = y0-1; y >=0; y--)
	points[x][y] = (0.5 * points[x][y+1] + (grid+x*r+y)->q +
			0.5 * points[x-1][y] - (grid+x*r+y)->p);
      for(y = y0+1; y < r; y++)
	points[x][y] = (0.5 * points[x][y-1] - (grid+x*r+y)->q +
			0.5 * points[x-1][y] - (grid+x*r+y)->p);
    }
    for(x = 0; x < r; x++)
      for(y = 0; y < r; y++){
	allpoints[x*r+y] += points[x][y];
	max = (allpoints[x*r+y] > max) ? allpoints[x*r+y] : max;
      }
  }
  Image* im = (Image*) malloc(sizeof(Image));
  setSize(im, r, c);
  setColors(im, 255);
  int x,y;
  for(x = 0; x < r; x++)
    for(y = 0; y < c; y++)
      setPixel(im, x, y, getPixel(mask,x,y) ? allpoints[x*r+y] / (double) max * 255 : 0);
  writeImage(im, argv[4]);
}
Пример #14
0
void getObjects(Image *im, ObjectDB *odb)
{
	int i, j, px, a, b, c, jp, ip,
		 rows=getNRows(im), cols=getNCols(im);
	float theta[2];
	double E[2];
	Object *obj;

	/* get area, calculate bounding boxes, and begin calculating centers */
	for (i=0; i < rows; ++i) {
		for (j=0; j < cols; ++j) {
			px=getPixel(im, i, j);
			if (px > 0) {
				obj=odb->objs+px-1;
				if (i < obj->top) obj->top=i;
				if (i > obj->bottom) obj->bottom=i;
				if (j < obj->left) obj->left=j;
				if (j > obj->right) obj->right=j;
				obj->fm[0]+=i;
				obj->fm[1]+=j;
				obj->area++;
			}
		}
	}

	/* finish centers */
	for (i=0; i < odb->nObjects; ++i)
		if (odb->objs[i].area > 0) {
			obj=odb->objs+i;
			for (j=0; j < DIM; ++j)
				obj->fm[j]/=obj->area;
		}

	/* calculate a, b, c */
	for (i=0; i < rows; ++i) {
		for (j=0; j < cols; ++j) {
			px=getPixel(im, i, j);
			if (px > 0) {
				obj=odb->objs+px-1;
				ip=i - obj->fm[0];
				jp=j - obj->fm[1];
				obj->sm.a+=jp*jp;
				obj->sm.b+=2*jp*ip;
				obj->sm.c+=ip*ip;
			}
		}
	}

	/* calculate theatmin */
	for (i=0; i < odb->nObjects; ++i)
		if (odb->objs[i].area > 0) {
			obj=odb->objs+i;
			a=obj->sm.a;
			b=obj->sm.b;
			c=obj->sm.c;

			theta[0]=0.5f*atan2(b, a-c);
			theta[1]=theta[0] + PI/2.0;

			E[0]=secondMoment(a, b, c, theta[0]);
			E[1]=secondMoment(a, b, c, theta[1]);

			if (E[0] > E[1]) {
				obj->sm.thetaMin=theta[1];
				obj->sm.thetaMax=theta[0];
			} else {
				obj->sm.thetaMin=theta[0];
				obj->sm.thetaMax=theta[1];
			}
		}
}