bool TrackerMedianFlowImpl::medianFlowImpl(Mat oldImage,Mat newImage,Rect2d& oldBox){
    std::vector<Point2f> pointsToTrackOld,pointsToTrackNew;

    Mat oldImage_gray,newImage_gray;
    cvtColor( oldImage, oldImage_gray, COLOR_BGR2GRAY );
    cvtColor( newImage, newImage_gray, COLOR_BGR2GRAY );

    //"open ended" grid
    for(int i=0;i<params.pointsInGrid;i++){
        for(int j=0;j<params.pointsInGrid;j++){
                pointsToTrackOld.push_back(
                        Point2f((float)(oldBox.x+((1.0*oldBox.width)/params.pointsInGrid)*j+.5*oldBox.width/params.pointsInGrid),
                        (float)(oldBox.y+((1.0*oldBox.height)/params.pointsInGrid)*i+.5*oldBox.height/params.pointsInGrid)));
        }
    }

    std::vector<uchar> status(pointsToTrackOld.size());
    std::vector<float> errors(pointsToTrackOld.size());
    calcOpticalFlowPyrLK(oldImage_gray, newImage_gray,pointsToTrackOld,pointsToTrackNew,status,errors,Size(3,3),5,termcrit,0);
    dprintf(("\t%d after LK forward\n",(int)pointsToTrackOld.size()));

    std::vector<Point2f> di;
    for(int i=0;i<(int)pointsToTrackOld.size();i++){
        if(status[i]==1){
            di.push_back(pointsToTrackNew[i]-pointsToTrackOld[i]);
        }
    }

    std::vector<bool> filter_status;
    check_FB(oldImage_gray,newImage_gray,pointsToTrackOld,pointsToTrackNew,filter_status);
    check_NCC(oldImage_gray,newImage_gray,pointsToTrackOld,pointsToTrackNew,filter_status);

    // filter
    for(int i=0;i<(int)pointsToTrackOld.size();i++){
        if(!filter_status[i]){
            pointsToTrackOld.erase(pointsToTrackOld.begin()+i);
            pointsToTrackNew.erase(pointsToTrackNew.begin()+i);
            filter_status.erase(filter_status.begin()+i);
            i--;
        }
    }
    dprintf(("\t%d after LK backward\n",(int)pointsToTrackOld.size()));

    if(pointsToTrackOld.size()==0 || di.size()==0){
        return false;
    }
    Point2f mDisplacement;
    oldBox=vote(pointsToTrackOld,pointsToTrackNew,oldBox,mDisplacement);

    std::vector<double> displacements;
    for(int i=0;i<(int)di.size();i++){
        di[i]-=mDisplacement;
        displacements.push_back(sqrt(di[i].ddot(di[i])));
    }
    if(getMedian(displacements,(int)displacements.size())>10){
        return false;
    }

    return true;
}
Exemple #2
0
    void ElectCmdRunner::Algorithm::processResponse(
            const RemoteCommandRequest& request,
            const ResponseStatus& response) {

        ++_actualResponses;

        if (response.isOK()) {
            BSONObj res = response.getValue().data;
            log() << "received " << res["vote"] << " votes from " << request.target;
            LOG(1) << "full elect res: " << res.toString();
            BSONElement vote(res["vote"]); 
            if (vote.type() != mongo::NumberInt) {
                error() << "wrong type for vote argument in replSetElect command: " << 
                    typeName(vote.type());
                _sufficientResponsesReceived = true;
                return;
            }

            _receivedVotes += vote._numberInt();
        }
        else {
            warning() << "elect command to " << request.target << " failed: " <<
                response.getStatus();
        }
    }
Exemple #3
0
int main()
{
	clock_t beginTime = clock();// clock_t taken as long
    double **trainingData, **testData;
	int trainingPicNum = 42000;
    readInMiniData(&trainingData, trainingPicNum);
//	readInData(&trainingData, &testData);	
	//printData(trainingData, trainingPicNum);
//	printf("Well, boy, look at this %d\n", (int)1 == 1.0);

	printf("Succefully read in data\n\n");
	
	// Hard coded
	double occurrance[10] = {0};
	double voting[10][784] = {0};
	vote(occurrance, voting, trainingData, trainingPicNum);

	double weight[10][784] = {0};
	weighting(occurrance, voting, weight);

	validate(trainingData, weight, trainingPicNum);	
	
	clock_t endTime = clock();

	printf("Total time elapsed %lf seconds\n\n", (double)(endTime - beginTime)/(double)CLOCKS_PER_SEC);
    return 0;
}
Exemple #4
0
void PostedItem::makeDownVote()
{
    RsGxsGrpMsgIdPair msgId;
    msgId.first = mPost.mMeta.mGroupId;
    msgId.second = mPost.mMeta.mMsgId;
    emit vote(msgId, false);
}
void mexFunction(int nout, mxArray *pout[], int nin, const mxArray *pin[]) {
  if (nin < 2) { mexErrMsgTxt("votemex called with < 2 input arguments"); }
  const mxArray *B = pin[0], *Ann = pin[1], *Bnn = NULL;

  BITMAP *b = convert_bitmap(B);

  Params *p = new Params();
  // [bnn=[]], [algo='cpu'], [patch_w=7], [bmask=[]], [bweight=[]], [coherence_weight=1], [complete_weight=1], [amask=[]], [aweight=[]]
  BITMAP *bmask = NULL, *bweight = NULL, *amask = NULL, *aweight = NULL, *ainit = NULL;
  double coherence_weight = 1, complete_weight = 1;
  int i = 2;
  if (nin > i && !mxIsEmpty(pin[i])) { Bnn = pin[i]; } i++;
  if (nin > i && !mxIsEmpty(pin[i])) {
    if			(mxStringEquals(pin[i], "cpu")) { p->algo = ALGO_CPU; }
    else if (mxStringEquals(pin[i], "gpucpu")) { p->algo = ALGO_GPUCPU; }
    else if (mxStringEquals(pin[i], "cputiled")) { p->algo = ALGO_CPUTILED; }
    else { mexErrMsgTxt("Unknown algorithm"); }
  } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { p->patch_w = int(mxGetScalar(pin[i])); } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { bmask = convert_bitmap(pin[i]); } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { bweight = convert_bitmapf(pin[i]); } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { coherence_weight = mxGetScalar(pin[i]); } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { complete_weight = mxGetScalar(pin[i]); } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { amask = convert_bitmap(pin[i]); } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { aweight = convert_bitmapf(pin[i]); } i++;
  if (nin > i && !mxIsEmpty(pin[i])) { ainit = convert_bitmap(pin[i]); } i++;

  int aclip = 0, bclip = 0;
  BITMAP *ann = convert_field(p, Ann, b->w, b->h, aclip);
  BITMAP *bnn = Bnn ? convert_field(p, Bnn, ann->w, ann->h, bclip): NULL;

  int nclip = aclip + bclip;
  //if (nclip) printf("Warning: clipped %d votes (%d a -> b, %d b -> a)\n", nclip, aclip, bclip);

  RegionMasks *amaskm = amask ? new RegionMasks(p, amask): NULL;
  //BITMAP *a = vote(p, b, ann, bnn, bmask, bweight, coherence_weight, complete_weight, amaskm, aweight, ainit);
  // David Jacobs -- Added mask_self_only as true for multiple.
  BITMAP *a = vote(p, b, ann, bnn, bmask, bweight, coherence_weight, complete_weight, amaskm, aweight, ainit, NULL, NULL, 1);
	
  destroy_region_masks(amaskm);

	if(nout >= 1) {
		mxArray *ans = bitmap_to_array(a);
		pout[0] = ans;
  } 

  delete p;
  destroy_bitmap(a);
  destroy_bitmap(ainit);
  destroy_bitmap(b);
  destroy_bitmap(ann);
  destroy_bitmap(bnn);
  destroy_bitmap(bmask);
  destroy_bitmap(bweight);
//  destroy_bitmap(amask);
  destroy_bitmap(aweight);
}
Exemple #6
0
vector<PlaintextArray> encodeVotes(vector<vector <long> > votes, EncryptedArray ea) {
  vector<PlaintextArray> ret;
  for(int i = 0; i < votes.size(); i++) {
    PlaintextArray vote(ea);
    vote.encode(votes[i]);
    ret.push_back(vote);
  }

  return ret;
}
void GxsChannelPostItem::makeDownVote()
{
	RsGxsGrpMsgIdPair msgId;
	msgId.first = mPost.mMeta.mGroupId;
	msgId.second = mPost.mMeta.mMsgId;

	ui->voteUpButton->setEnabled(false);
	ui->voteDownButton->setEnabled(false);

	emit vote(msgId, false);
}
Exemple #8
0
void PostedItem::makeUpVote()
{
	RsGxsGrpMsgIdPair msgId;
	msgId.first = mPost.mMeta.mGroupId;
	msgId.second = mPost.mMeta.mMsgId;

	ui->voteUpButton->setEnabled(false);
	ui->voteDownButton->setEnabled(false);

	emit vote(msgId, true);
}
Exemple #9
0
/* 
 * Read and process poll commands
 * Return:  -1 for quit command
 *          0 otherwise
 */
char * process_args(int cmd_argc, char **cmd_argv, Poll **poll_list_ptr) {

    // some commands need the poll_list head and others
    // require the address of that head
    Poll *poll_list = *poll_list_ptr; 

    if (strcmp(cmd_argv[0], "list_polls") == 0 && cmd_argc == 1) {
        char *buf;
        buf = print_polls(poll_list);
        printf("%s", buf);
        free(buf);
    } else if (strcmp(cmd_argv[0], "create_poll") == 0 && cmd_argc >= 3) {
        int label_count = cmd_argc - 2;
        int result = create_poll(cmd_argv[1], &cmd_argv[2], label_count,
                     poll_list_ptr);
        if (result == 1) {
            char *ans = malloc(13);
            strcpy(ans, "Poll exists");
            return ans;
        }

   } else if (strcmp(cmd_argv[0], "vote") == 0 && cmd_argc == 3) {

        char *poll_name = cmd_argv[1];        // better name for clarity of code below

        // try to add participant to this poll  
        vote(poll_name, poll_list, cmd_argv[2]);
        

    } else if (strcmp(cmd_argv[0], "delete_poll") == 0 && cmd_argc == 2) {
        if (delete_poll(cmd_argv[1], poll_list_ptr) == 1) {
            char *ans2 = malloc(15);
            strcpy(ans2, "No poll exists");
            return ans2;
        }

    } else if (strcmp(cmd_argv[0], "poll_info") == 0 && cmd_argc == 2) {
        char *buffer;
        buffer = print_poll_info(cmd_argv[1], poll_list);
        return buffer;
    } else if(strcmp(cmd_argv[0], "comment") == 0 && cmd_argc == 3){
        
        comment(cmd_argv[1], poll_list, cmd_argv[2]);
        
    }else{
        char *ans1 = malloc(17);
        strcpy(ans1, "Incorrect syntax");
        return ans1;
    }
    char *ans4 = malloc(5);
    strcpy(ans4, "NULL");
    return ans4;
}
Exemple #10
0
int main()
{
	int n = 0, nop = 0, cd = 0, idp = 0;
	int ID[50], code[50];
	double mv[50], income[50];
	char name[50][10], family[50][20];

	printf("\nلطفا یک عدد از 1 تا 6 وارد کنید\n");
	printf("\nعدد 1 برای وارد کردن تعداد پزشکان و اطلاعات آنها\n");
	printf("\nعدد 2 برای مرتب کردن پزشکان بر اساس نام خانوادگی آنها\n");
	printf("\nعدد 3 برای وارد کردن کد تخصص و درخواست ملاقات با پزشک انتخاب شده\n");
	printf("\nعدد 4 برای نظرسنجی در مورد یک پزشک\n");
	printf("\nعدد 5 برای پرینت کردن اطلاعات پزشکان\n");
	printf("\nعدد 6 برای اتمام برنامه\n");

	while (scanf("%d", &n) != EOF)
	{
		switch (n)
		{
		case 1:
			printf("\nلطفا تعداد پزشکان را وارد کنید\n");
			scanf("%d", &nop);
			enter_info(nop, ID, name, family, code, mv, income);
			break;
		case 2:
			sort(nop, ID, name, family, code, mv, income);
			break;
		case 3:
			printf("\nلطفا کد پزشک را وارد کنید\n");
			scanf("%d", &cd);
			visit(cd, nop, ID, name, family, code, mv, income);
			break;
		case 4:
			printf("\nلطفا شماره پرسنلی پزشک را وارد کنید\n");
			scanf("%d", &idp);
			if (vote(idp, nop, ID, mv, income) == -1)
				printf("\nاین پزشک جزو پزشکان ضعیف این مرکز درمانی است\n");
			break;
		case 5:
			print_info(nop, ID, name, family, code, mv, income);
			break;
		case 6:
			return 0;
		default:
			printf("\nخطا: عدد ورودی باید یکی از اعداد 1 تا 6 باشد\n");
			break;
		}
		printf("\nلطفا یک عدد از 1 تا 6 وارد کنید\n");
	}

	return 0;
}
int main()
{
    int i;
    const int votes = 1 << 10; /* Using bitwise operation to get the 1024 votes. */
    i = 0;

    while(i < votes) {
        vote();
        printf("Vote numer: %d\n", i + 1);
        i++;
    }

    return 0;
}
BITMAP *vecwrap_vote(int vec_mode, Params *p, BITMAP *b,
         BITMAP *ann, BITMAP *ann_sim, BITMAP *bnn,
         BITMAP *bmask, BITMAP *bweight,
         double coherence_weight, double complete_weight,
         RegionMasks *amask, BITMAP *aweight, BITMAP *ainit, RegionMasks *region_masks, BITMAP *aconstraint, int mask_self_only) 
{
  if (vec_mode == VEC_MODE_PATCH || vec_mode == VEC_MODE_DESC) {
    return vote(p, b, ann, bnn, bmask, bweight, coherence_weight, complete_weight, amask, aweight, ainit, region_masks, aconstraint, mask_self_only);
  }
	else if (vec_mode == VEC_MODE_SIM) {
    if (!ann_sim) { fprintf(stderr, "vecwrap_vote: expected argument ann_sim\n"); exit(1); }
    return sim_vote(p, b, ann, ann_sim, bnn, NULL, bmask, bweight, coherence_weight, complete_weight, amask, aweight, ainit, region_masks, aconstraint, mask_self_only);
  } 
	else {
    fprintf(stderr, "vecwrap_vote: unknown mode %d\n", vec_mode); exit(1);
  }
}
Position MotionDetector::majorityVote(std::vector<Position> votes) {
  int gridWidthLen = gridWidth_.size();
  std::vector<int> vote(gridWidthLen, 0);
  for (int i = 0; i < votes.size(); ++i) {
    Position v = votes[i];
    assert(v < gridWidthLen);
    if (v >= 0) {
      vote[v]++;
    }
  }
  int maxVote = 0, maxVotePosition = -1;
  for (int i = 0; i < gridWidthLen; ++i) {
    if (vote[i] > maxVote) {
      maxVote = vote[i];
      maxVotePosition = i;
    }
  }

  return maxVote < (votes.size() + 1) / 2 ? -1 : maxVotePosition;
}
Exemple #14
0
// update w weights
void GraphHandler::updateWeights(vector<vector<unsigned int>> &clustering, vector<unsigned int> &medians){
    if (clustering.size() != medians.size()){
        cout << "error\n";
    }
    
    vector<unsigned int> votes(w.size(), 0);
    unsigned int votes_sum = 0;
    for (unsigned int i=0; i<w.size(); i++){
        for (unsigned int j=0; j<clustering.size(); j++){
            for (unsigned int k=0; k<clustering[j].size(); k++){
                votes[i] += vote(i, clustering[j][k], medians[j]);
            }
        }
        votes_sum += votes[i];
    }
    
    w_sum = 0;
    for (unsigned int i=0; i<w.size(); i++){
        w[i] = 0.5 * (w[i] + (double (votes[i] * w.size())) / double (votes_sum));
        w_sum += w[i];
    }
    
};
int main(int argc, char **argv)
{
    if (argc < 3) {
        std::cout << "USAGE: " << argv[0] << " <filename> <threshold>"
                  << std::endl;
        return -1;
    }
    const char *filename = argv[1];
    cv::Mat src = cv::imread(filename, 0);
    assert(!src.empty());
    cv::Mat dst, cdst;
    cv::Canny(src, dst, 50, 200, 3);
    cv::cvtColor(dst, cdst, CV_GRAY2BGR);

    std::vector< std::pair<int, int> > coords; // List of x, y coords
    for (int i=0; i<cdst.rows; ++i) {
        for (int j=0; j<cdst.cols; ++j) {
            if (cdst.at<cv::Vec3b>(i,j)[0] == 255) {
                coords.push_back(std::make_pair(j, cdst.rows - i));
            }
        }
    }
    // Now to create a hough table of rho and theta, we need to know
    // the maxVals of both.
    // Our table will be of dimensions max(rho) x max(theta)
    std::vector<float> maxVal(2), res(2);
    maxVal[RHO] = (float) (sqrt(pow(cdst.rows, 2) + pow(cdst.cols, 2)));
    maxVal[THETA] = (float) 2 * M_PI;

    //PPRINT(maxVal[RHO]); 
    //PPRINT(maxVal[THETA]); 
    res[RHO] = 1;
    res[THETA] = M_PI / 180; 

    houghSpace hs (res, maxVal);

    std::vector<float> vote(2), voteLoc(2);
    float m; // slope
    for (auto &p: coords) {
        /* The theta here is the slope of the line with +X axis
         * We'll convert the line from slope-point form to hesse-normal
         * form for the hough table
         */
        for (float theta = 0; theta < M_PI; theta += M_PI / 180) {
            m = tanf(theta);
            voteLoc[0] = p.first;
            voteLoc[1] = p.second;
            vote[RHO] = std::abs(p.second - m * p.first) / (sqrt(1 + m*m));
            /* Case I: y-intercept is > 0 */
            if ((p.second - m * p.first) > 0) {
                if (theta < M_PI / 2.0) {
                    vote[THETA] = theta + M_PI / 2.0;
                } else {
                    vote[THETA] = theta - M_PI / 2.0;
                }
            }
            /* Case II: y-intercept is < 0 */
            else {
                if (theta < M_PI / 2.0) {
                    vote[THETA] = theta + M_PI + M_PI / 2.0;
                } else {
                    vote[THETA] = theta + M_PI - M_PI / 2.0;
                }
            }
            assert(vote[RHO] <= maxVal[RHO]);
            assert(vote[THETA] <= maxVal[THETA]);
            hs.addVote(vote, voteLoc);
        }
    }
    auto vec (hs.getMaxima(atoi(argv[2])));
//    for (auto &p: vec) {
//        std::cout << p.first[0] << " "
//                  << p.first[1] << std::endl;
//    }

    auto lineSeg = getLineSegments(vec);
    for (auto &ls : lineSeg) {
        std::cout   << ls.first.first   << ' ' //X1
                    << ls.first.second  << ' ' //Y1
                    << ls.second.first  << ' ' //X2
                    << ls.second.second << ' ' //Y2
                    << std::endl;
    }
    return 0;
}
Exemple #16
0
// server side processing of updates: does very little and most state is tracked
// client only could be extended to move more gameplay to server (at expense of
// lag)
void process(ENetPacket * packet, int sender) { // sender may be -1
  const u16 len = *(u16*) packet->data;
  if (ENET_NET_TO_HOST_16(len)!=packet->dataLength) {
    disconnect_client(sender, "packet length");
    return;
  }

  u8 *end = packet->data+packet->dataLength;
  u8 *p = packet->data+2;
  char text[MAXTRANS];
  int cn = -1, type;

  while (p<end) switch (type = getint(p)) {
    case SV_TEXT:
      sgetstr();
    break;
    case SV_INITC2S:
      sgetstr();
      strcpy_s(clients[cn].name, text);
      sgetstr();
      getint(p);
    break;
    case SV_MAPCHANGE: {
      sgetstr();
      int reqmode = getint(p);
      if (reqmode<0) reqmode = 0;
      if (smapname[0] && !mapreload && !vote(text, reqmode, sender)) return;
      mapreload = false;
      mode = reqmode;
      minremain = mode&1 ? 15 : 10;
      mapend = lastsec+minremain*60;
      interm = 0;
      strcpy_s(smapname, text);
      resetitems();
      sender = -1;
    }
    break;
    case SV_ITEMLIST: {
      int n;
      while ((n = getint(p))!=-1) if (notgotitems) {
        server_entity se = { false, 0 };
        while (sents.size()<=n) sents.push_back(se);
        sents[n].spawned = true;
      }
      notgotitems = false;
    }
    break;
    case SV_ITEMPICKUP: {
      const int n = getint(p);
      pickup(n, getint(p), sender);
    }
    break;
    case SV_PING:
      send2(false, cn, SV_PONG, getint(p));
    break;
    case SV_POS: {
      cn = getint(p);
      if (cn<0 || cn>=clients.size() || clients[cn].type==ST_EMPTY) {
        disconnect_client(sender, "client num");
        return;
      }
      int size = msgsizelookup(type);
      assert(size!=-1);
      loopi(size-2) getint(p);
    }
    break;
    case SV_SENDMAP: {
      sgetstr();
      const auto mapsize = getint(p);
      sendmaps(sender, text, mapsize, p);
    }
    return;
    case SV_RECVMAP:
      send(sender, recvmap(sender));
    return;
    case SV_EXT:   // allows for new features that require no server updates 
      for (int n = getint(p); n; n--) getint(p);
    break;
    default: {
      const int size = msgsizelookup(type);
      if (size==-1) { disconnect_client(sender, "tag type"); return; };
      loopi(size-1) getint(p);
    }
  }

  if (p>end) { disconnect_client(sender, "end of packet"); return; };
  multicast(packet, sender);
}
void doHough(std::vector<payload> readings, int lineThresh, int pointThresh)
{
    std::vector<float> maxVal(2), res(2);
    std::vector<float> minVal(2);
    std::vector<float> vote(2);

    /**
     * LINE SPACE
     * RHO: The perpendicular distance of the line from origin
     * THETA: Angle the perpendicular from the origin to the line
     *        makes with +X axis
     *
     * beta: Angular error of ultrasonic sensor, -15deg < beta < 15deg
     */
    maxVal[RHO] = 15000.0F; // in millimetres
    maxVal[THETA] = (float) 2 * M_PI; // in radians
    res[RHO] = 100;
    res[THETA] = M_PI / 180 * 5;

    houghSpace linespace (res, maxVal);

    for (auto &p: readings) {
        for (float beta = -M_PI/12; beta <= M_PI/12; beta += M_PI/180) {
            // Refer to the paper for the derivation
            vote[THETA] = p.loc.theta + beta;
            vote[THETA] = fmod(vote[THETA], 2 * M_PI);
            if (vote[THETA] < 0) {
                vote[THETA] += 2 * M_PI;
            }
            vote[RHO] = std::abs(p.reading + (p.loc.x * cosf(vote[THETA]))
                                  + (p.loc.y * sinf(vote[THETA])));
            assert(vote[RHO] <= maxVal[RHO]);
            assert(vote[THETA] <= maxVal[THETA]);
            PPRINT(vote[RHO]);
            PPRINT(vote[THETA]);
            linespace.addVote(vote);
        }
    }
    std::vector< std::vector<float> > lineF (linespace.getMaxima(lineThresh));
    std::ofstream lout ("lines.txt");
    for (auto &p: lineF) {
        for (auto &q: p) {
            lout << q << " ";
        }
        lout << std::endl;
    }
    //std::cout << linespace;
    /**
     * POINT SPACE
     * X: X-coordinate of point
     * Y: Y-coordinate of point
     *
     * beta: Angular error of ultrasonic sensor, -15deg < beta < 15deg
     */
    maxVal[X] = 15000.0F; // in millimetres
    maxVal[Y] = 15000.0F; // in millimetres
    minVal[X] = -15000.0F;
    minVal[Y] = -15000.0F;
    res[X] = 10;
    res[Y] = 10;

    houghSpace pointspace (res, maxVal, minVal);

    for (auto &p: readings) {
        for (float beta = -M_PI/12; beta <= M_PI/12; beta += M_PI/180) {
            vote[X] = p.loc.x + (p.reading * cosf(p.loc.theta + beta));
            vote[Y] = p.loc.y + (p.reading * sinf(p.loc.theta + beta));
            assert(vote[X] <= maxVal[X]);
            assert(vote[Y] <= maxVal[Y]);
            PPRINT(vote[X]);
            PPRINT(vote[Y]);
            pointspace.addVote(vote);
        }
    }
    std::vector< std::vector<float> > pointF (pointspace.getMaxima(pointThresh));
    std::ofstream pout ("points.txt");
    for (auto &p: pointF) {
        for (auto &q: p) {
            pout << q << " ";
        }
        pout << std::endl;
    }
  //std::cout << pointspace;
}
void doHough(std::vector<payload> readings, int lineThresh, int pointThresh)
{
    std::vector<float> maxVal(2), res(2);
    std::vector<float> minVal(2);
    std::vector<float> vote(2);
    std::vector<float> voteLoc(2);

    /**
     * LINE SPACE
     * RHO: The perpendicular distance of the line from origin
     * THETA: Angle the perpendicular from the origin to the line
     *        makes with +X axis
     *
     * beta: Angular error of ultrasonic sensor, -15deg < beta < 15deg
     */
    maxVal[RHO] = 15000.0F; // in millimetres
    maxVal[THETA] = (float) 2 * M_PI; // in radians
    res[RHO] = 100;
    res[THETA] = M_PI / 180 * 5;

    houghSpace linespace (res, maxVal);

    for (auto &p: readings) {
        for (float beta = -M_PI/12; beta <= M_PI/12; beta += M_PI/180) {
            // Refer to the paper for the derivation
            vote[THETA] = p.loc.theta + beta;
            vote[THETA] = fmod(vote[THETA], 2 * M_PI);
            if (vote[THETA] < 0) {
                vote[THETA] += 2 * M_PI;
            }
            vote[RHO] = std::abs(p.reading + (p.loc.x * cosf(vote[THETA]))
                    + (p.loc.y * sinf(vote[THETA])));
            voteLoc[X] = p.loc.x + p.reading * cosf(vote[THETA]);
            voteLoc[Y] = p.loc.y + p.reading * sinf(vote[THETA]);
            assert(vote[RHO] <= maxVal[RHO]);
            assert(vote[THETA] <= maxVal[THETA]);
            PPRINT(vote[RHO]);
            PPRINT(vote[THETA]);
            PPRINT(voteLoc[X]);
            PPRINT(voteLoc[Y]);
            linespace.addVote(vote, voteLoc);
        }
    }
    auto lineF (linespace.getMaxima(lineThresh));
    std::ofstream lout ("lines.txt");
    for (auto &p: lineF) {
        for (auto &q: p.first) {
            lout << q << " ";
        }
        lout << std::endl;
    }
    std::ofstream lsout("line_segments.txt");
    auto lineSegments = getLineSegments(lineF);
    for (auto &ls : lineSegments) {
        lsout   << ls.first.first   << ' ' //X1
                << ls.first.second  << ' ' //Y1
                << ls.second.first  << ' ' //X2
                << ls.second.second << ' ' //Y2
                << std::endl;
    }
}
// Performs the proposed Hough transform voting scheme.
void
voting(accumulator_t &accumulator, section_list_t &sections, const clusters_list_t &clusters, const double kernel_min_height, const double n_sigmas)
{
	/* Leandro A. F. Fernandes, Manuel M. Oliveira
	 * Real-time line detection through an improved Hough transform voting scheme
	 * Pattern Recognition (PR), Elsevier, 41:1, 2008, 299-314.
	 *
	 * Algorithm 2
	 */
	static kernels_list_t kernels;
	static pkernels_list_t used_kernels;

	kernels.resize( clusters.size() );
	used_kernels.resize( clusters.size() );

	matrix_t M, V, S;
	point_t mean, u, v;
	double x, y, Sxx, Syy, Sxy, aux;

	static const double rad_to_deg = 180.0 / pi;
	const double delta = accumulator.delta();
	const double one_div_delta = 1.0 / delta;
	const double n_sigmas2 = n_sigmas * n_sigmas;
	const double rho_max = accumulator.rho_bounds().upper;

	for (size_t k=0, end=clusters.size(); k!=end; ++k)
	{
		const cluster_t &cluster = clusters[k];
		kernel_t &kernel = kernels[k];

		kernel.pcluster = &cluster;
		
		// Alternative reference system definition.
		mean.x = mean.y = 0.0;
		for (size_t i=0; i!=cluster.size; ++i)
		{
			mean.x += cluster.pixels[i].x;
			mean.y += cluster.pixels[i].y;
		}
		mean.x /= cluster.size;
		mean.y /= cluster.size;
		
		Sxx = Syy = Sxy = 0.0;
		for (size_t i=0; i!=cluster.size; ++i)
		{
			x = cluster.pixels[i].x - mean.x;
			y = cluster.pixels[i].y - mean.y;
		
			Sxx += (x * x);
			Syy += (y * y);
			Sxy += (x * y);
		}
		
		M[0] = Sxx;
		M[3] = Syy;
		M[1] = M[2] = Sxy;
		eigen( V, S, M );

		u.x = V[0];
		u.y = V[2];
		
		v.x = V[1];
		v.y = V[3];
		
		// y_v >= 0 condition verification.
		if (v.y < 0.0)
		{
			v.x *= -1.0;
			v.y *= -1.0;
		}

		// Normal equation parameters computation (Eq. 3).
		kernel.rho = (v.x * mean.x) + (v.y * mean.y);
		kernel.theta = acos( v.x ) * rad_to_deg;

		kernel.rho_index = static_cast<size_t>( std::abs( (kernel.rho + rho_max) * one_div_delta ) ) + 1;
		kernel.theta_index = static_cast<size_t>( std::abs( kernel.theta * one_div_delta ) ) + 1;

		// sigma^2_m' and sigma^2_b' computation, substituting Eq. 5 in Eq. 10.
		aux = sqrt( 1.0 - (v.x * v.x) );
		matrix_t nabla = {
				             -((u.x * mean.x) + (u.y * mean.y)), 1.0,
				(aux != 0.0) ? ((u.x / aux) * rad_to_deg) : 0.0, 0.0
			};

		aux = 0.0;
		for (size_t i=0; i!=cluster.size; ++i)
		{
			x = (u.x * (cluster.pixels[i].x - mean.x)) + (u.y * (cluster.pixels[i].y - mean.y));
			aux += (x * x);
		}

		matrix_t lambda = {
				1.0 / aux,                0.0,
					  0.0, 1.0 / cluster.size
			};

		// Uncertainty from sigma^2_m' and sigma^2_b' to sigma^2_rho,  sigma^2_theta and sigma_rho_theta.
		solve( kernel.lambda, nabla, lambda );

		if (kernel.lambda[3] == 0.0)
		{
			kernel.lambda[3] = 0.1;
		}

		kernel.lambda[0] *= n_sigmas2;
		kernel.lambda[3] *= n_sigmas2;

		// Compute the height of the kernel.
		kernel.height = gauss( 0.0, 0.0, kernel.lambda[0], kernel.lambda[3], kernel.lambda[1] );
	}

	/* Leandro A. F. Fernandes, Manuel M. Oliveira
	 * Real-time line detection through an improved Hough transform voting scheme
	 * Pattern Recognition (PR), Elsevier, 41:1, 2008, 299-314.
	 *
	 * Algorithm 3
	 */

	// Discard groups with very short kernels.
	double norm = std::numeric_limits<double>::min();

	for (size_t k=0, end=kernels.size(); k!=end; ++k)
	{
		kernel_t &kernel = kernels[k];

		if (norm < kernel.height)
		{
			norm = kernel.height;
		}
		used_kernels[k] = &kernel;
	}
	norm = 1.0 / norm;

	size_t i = 0;
	for (size_t k=0, end=used_kernels.size(); k!=end; ++k)
	{
		if ((used_kernels[k]->height * norm) >= kernel_min_height)
		{
			if (i != k)
			{
				kernel_t *temp = used_kernels[i];
				used_kernels[i] = used_kernels[k];
				used_kernels[k] = temp;
			}
			i++;
		}
	}
	used_kernels.resize( i );

	// Find the g_min threshold and compute the scale factor for integer votes.
	double radius, scale;
	double kernels_scale = std::numeric_limits<double>::min();

	for (size_t k=0, end=used_kernels.size(); k!=end; ++k)
	{
		kernel_t &kernel = *used_kernels[k];

		eigen( V, S, kernel.lambda );
		radius = sqrt( S[3] );

		scale = gauss( V[1] * radius, V[3] * radius, kernel.lambda[0], kernel.lambda[3], kernel.lambda[1] );
		scale = (scale < 1.0) ? (1.0 / scale) : 1.0;

		if (kernels_scale < scale)
		{
			kernels_scale = scale;
		}
	}

	// Vote for each selected kernel.
	for (size_t k=0, end=used_kernels.size(); k!=end; ++k)
	{
		kernel_t &kernel = *used_kernels[k];

		vote( accumulator, kernel.rho_index,     kernel.theta_index,        0.0,    0.0,  1,  1, kernel.lambda[0], kernel.lambda[3], kernel.lambda[1], kernels_scale );
		vote( accumulator, kernel.rho_index,     kernel.theta_index - 1,    0.0, -delta,  1, -1, kernel.lambda[0], kernel.lambda[3], kernel.lambda[1], kernels_scale );
		vote( accumulator, kernel.rho_index - 1, kernel.theta_index,     -delta,    0.0, -1,  1, kernel.lambda[0], kernel.lambda[3], kernel.lambda[1], kernels_scale );
		vote( accumulator, kernel.rho_index - 1, kernel.theta_index - 1, -delta, -delta, -1, -1, kernel.lambda[0], kernel.lambda[3], kernel.lambda[1], kernels_scale );
	}

	sections.resize( used_kernels.size() );
	for (int i=0; i< used_kernels.size(); i++) {
		section_t &section = sections[i];
		kernel_t &kernel = *used_kernels[i];

		section.rho = kernel.rho;
		section.theta = kernel.theta;
		section.size = kernel.pcluster->size;
		section.pixels = kernel.pcluster->pixels;
	}
}
Exemple #20
0
void CInstantSend::Vote(CTxLockCandidate& txLockCandidate, CConnman& connman)
{
    if(!fMasternodeMode) return;
    if(!sporkManager.IsSporkActive(SPORK_2_INSTANTSEND_ENABLED)) return;

    LOCK2(cs_main, cs_instantsend);

    uint256 txHash = txLockCandidate.GetHash();
    // We should never vote on a Transaction Lock Request that was not (yet) accepted by the mempool
    if(mapLockRequestAccepted.find(txHash) == mapLockRequestAccepted.end()) return;
    // check if we need to vote on this candidate's outpoints,
    // it's possible that we need to vote for several of them
    std::map<COutPoint, COutPointLock>::iterator itOutpointLock = txLockCandidate.mapOutPointLocks.begin();
    while(itOutpointLock != txLockCandidate.mapOutPointLocks.end()) {

        int nPrevoutHeight = GetUTXOHeight(itOutpointLock->first);
        if(nPrevoutHeight == -1) {
            LogPrint("instantsend", "CInstantSend::Vote -- Failed to find UTXO %s\n", itOutpointLock->first.ToStringShort());
            return;
        }

        int nLockInputHeight = nPrevoutHeight + Params().GetConsensus().nInstantSendConfirmationsRequired - 2;

        int nRank;
        if(!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nLockInputHeight, MIN_INSTANTSEND_PROTO_VERSION)) {
            LogPrint("instantsend", "CInstantSend::Vote -- Can't calculate rank for masternode %s\n", activeMasternode.outpoint.ToStringShort());
            ++itOutpointLock;
            continue;
        }

        int nSignaturesTotal = COutPointLock::SIGNATURES_TOTAL;
        if(nRank > nSignaturesTotal) {
            LogPrint("instantsend", "CInstantSend::Vote -- Masternode not in the top %d (%d)\n", nSignaturesTotal, nRank);
            ++itOutpointLock;
            continue;
        }

        LogPrint("instantsend", "CInstantSend::Vote -- In the top %d (%d)\n", nSignaturesTotal, nRank);

        std::map<COutPoint, std::set<uint256> >::iterator itVoted = mapVotedOutpoints.find(itOutpointLock->first);

        // Check to see if we already voted for this outpoint,
        // refuse to vote twice or to include the same outpoint in another tx
        bool fAlreadyVoted = false;
        if(itVoted != mapVotedOutpoints.end()) {
            for (const auto& hash : itVoted->second) {
                std::map<uint256, CTxLockCandidate>::iterator it2 = mapTxLockCandidates.find(hash);
                if(it2->second.HasMasternodeVoted(itOutpointLock->first, activeMasternode.outpoint)) {
                    // we already voted for this outpoint to be included either in the same tx or in a competing one,
                    // skip it anyway
                    fAlreadyVoted = true;
                    LogPrintf("CInstantSend::Vote -- WARNING: We already voted for this outpoint, skipping: txHash=%s, outpoint=%s\n",
                            txHash.ToString(), itOutpointLock->first.ToStringShort());
                    break;
                }
            }
        }
        if(fAlreadyVoted) {
            ++itOutpointLock;
            continue; // skip to the next outpoint
        }

        // we haven't voted for this outpoint yet, let's try to do this now
        CTxLockVote vote(txHash, itOutpointLock->first, activeMasternode.outpoint);

        if(!vote.Sign()) {
            LogPrintf("CInstantSend::Vote -- Failed to sign consensus vote\n");
            return;
        }
        if(!vote.CheckSignature()) {
            LogPrintf("CInstantSend::Vote -- Signature invalid\n");
            return;
        }

        // vote constructed sucessfully, let's store and relay it
        uint256 nVoteHash = vote.GetHash();
        mapTxLockVotes.insert(std::make_pair(nVoteHash, vote));
        if(itOutpointLock->second.AddVote(vote)) {
            LogPrintf("CInstantSend::Vote -- Vote created successfully, relaying: txHash=%s, outpoint=%s, vote=%s\n",
                    txHash.ToString(), itOutpointLock->first.ToStringShort(), nVoteHash.ToString());

            if(itVoted == mapVotedOutpoints.end()) {
                std::set<uint256> setHashes;
                setHashes.insert(txHash);
                mapVotedOutpoints.insert(std::make_pair(itOutpointLock->first, setHashes));
            } else {
                mapVotedOutpoints[itOutpointLock->first].insert(txHash);
                if(mapVotedOutpoints[itOutpointLock->first].size() > 1) {
                    // it's ok to continue, just warn user
                    LogPrintf("CInstantSend::Vote -- WARNING: Vote conflicts with some existing votes: txHash=%s, outpoint=%s, vote=%s\n",
                            txHash.ToString(), itOutpointLock->first.ToStringShort(), nVoteHash.ToString());
                }
            }

            vote.Relay(connman);
        }

        ++itOutpointLock;
    }
}
void GxsCommentTreeWidget::voteDown()
{
	std::cerr << "GxsCommentTreeWidget::voteDown()";
	std::cerr << std::endl;
	vote(mThreadId.first, mThreadId.second, mCurrentMsgId, mVoterId, false);
}