Example #1
0
QString WorkerThread::getFirstMessage()
{

        QMutexLocker ll(&m2);
        if (messStack.size()==0) return "";
        QString s = messStack.front();
        messStack.pop_front();
        return s;
}
void GridTriangleFill::sortByAscendingY (QPoint p0In,
                                         QPoint p1In,
                                         QPoint p2In,
                                         QPoint &p0,
                                         QPoint &p1,
                                         QPoint &p2) const
{
  // Sort by ascending y value
  QList<QPoint> list;
  list << p0In << p1In << p2In;
  std::sort (list.begin(), list.end(), compareByY);

  p0 = list.front();
  list.pop_front();
  p1 = list.front();
  list.pop_front();
  p2 = list.front();
}
QStringList ModelRestorationForm::getSelectedModels(void)
{
	QStringList list;
	QList<QListWidgetItem *> items;

	items=tmp_files_lst->selectedItems();

	while(!items.isEmpty())
	{
		list.push_back(items.front()->data(Qt::UserRole).toString());
		items.pop_front();
	}

	return(list);
}
void ImbricableReader::createTree(BaseObject::shared_BaseObject root, QDomElement dom)
{
    typedef  QPair<BaseObject::shared_BaseObject,QDomElement> MyPair;

    QList<MyPair> list;
    list.append(MyPair(root,dom));

    Weak_ImbricableReader this_weak = boost::dynamic_pointer_cast<ImbricableReader>(this->shared_from_this());

    while(!list.empty())
    {
        MyPair &p = list.first();

        if(p.second.hasChildNodes())
        {
            QDomNode node = p.second.firstChild();
            while(!node.isNull())
            {
                QDomElement e = node.toElement();
                if(!e.isNull())
                {
                    BaseObject::shared_BaseObject obj(createObject(&e));
                    if(obj)
                    {
                        obj->setParent(p.first);
                        list.append(MyPair(obj,e));
                    }
                    else qWarning() << " -> The object can't be created:" << e.tagName();

                }

                if(p.first->getVisitorAccessFlag() == ElementFlags::ImbrLoader_VA)
                {
                    ImbricableReaderVisitorAccess::Shared_ImbricableReaderVisitorAccess access = boost::dynamic_pointer_cast<ImbricableReaderVisitorAccess>(p.first);
                    if(access)access->execAfterChildrenLoading(this_weak);
                }

                node = node.nextSibling();
            }
        }
        list.pop_front();
    }
}
Example #5
0
	QModelIndex cast( NifModel * nif, const QModelIndex & index ) override final
	{
		QModelIndex iData = getStripsData( nif, index );
		QModelIndex iLength = nif->getIndex( iData, "Strip Lengths" );
		QModelIndex iPoints = nif->getIndex( iData, "Points" );

		if ( !( iLength.isValid() && iPoints.isValid() ) )
			return index;

		QList<QVector<quint16> > strips;

		for ( int r = 0; r < nif->rowCount( iPoints ); r++ )
			strips += nif->getArray<quint16>( iPoints.child( r, 0 ) );

		if ( strips.isEmpty() )
			return index;

		QVector<quint16> strip = strips.first();
		strips.pop_front();

		for ( const QVector<quint16>& s : strips ) {
			// TODO: optimize this
			if ( strip.count() & 1 )
				strip << strip.last() << s.first() << s.first() << s;
			else
				strip << strip.last() << s.first() << s;
		}

		nif->set<int>( iData, "Num Strips", 1 );
		nif->updateArray( iLength );
		nif->set<int>( iLength.child( 0, 0 ), strip.size() );
		nif->updateArray( iPoints );
		nif->updateArray( iPoints.child( 0, 0 ) );
		nif->setArray<quint16>( iPoints.child( 0, 0 ), strip );

		return index;
	}
Example #6
0
Spell Magic::generateSpell(SpellField field)
{
    QList<Position> list;
    QList<ActiveEffect> effects;
    QList<ActiveEffect>::iterator iter;
    ActiveEffect* worker;

    //crating mask for field
    bool **mask = new bool*[field.size.x];
    for (int i = 0; i < field.size.x; ++i){
        mask[i] = new bool[field.size.y];
        for(int n = 0; n < field.size.y; ++n)
            if(field.map[i][n] != Runes::End)
                mask[i][n] = true;
            else
                mask[i][n] = false;
    }

    if(field.mainRune.x > -1 && field.mainRune.y > -1 && field.map[field.mainRune.x][field.mainRune.y] != Runes::End){
        Position current(field.mainRune.x,field.mainRune.y);

        ActiveEffect work;
        Effect effect;
        int cost = 0;

        Rune *mainRune = runes[field.map[current.x][current.y]];
        work.effect = mainRune->combinationEffect(field.map[current.x][current.y]);
        work.coefficient = 1;
        effects.append(work);
        cost += mainRune->getCost();
        mask[current.x][current.y] = false;

        //select next rune
        if(current.x > 0 && mask[current.x-1][current.y]){
            list.append(Position(current.x-1,current.y));
            mask[current.x-1][current.y] = false;
        }
        if(current.x < field.size.x-1 && mask[current.x+1][current.y]){
            list.append(Position(current.x+1,current.y));
            mask[current.x+1][current.y] = false;
        }
        if(current.y > 0 && mask[current.x][current.y-1]){
            list.append(Position(current.x,current.y-1));
            mask[current.x][current.y-1] = false;
        }
        if(current.y < field.size.y-1 && mask[current.x][current.y+1]){
            list.append(Position(current.x,current.y+1));
            mask[current.x][current.y+1] = false;
        }


        while(!list.isEmpty()){
            current = list.first();

            //qDebug() << current.x << " " << current.y;

            list.pop_front();
            effect = mainRune->combinationEffect(field.map[current.x][current.y]);
            bool flag = true;
            for(iter = effects.begin(); iter != effects.end(); iter++){
                if(iter->effect == effect)
                {
                    iter->coefficient++;
                    flag = false;
                    break;
                }
            }
            if(flag){
                work.effect = effect;
                effects.append(work);
            }
            cost += runes[field.map[current.x][current.y]]->getCost();

            //select next rune
            if(current.x > 0&& mask[current.x-1][current.y]){
                list.append(Position(current.x-1,current.y));
                mask[current.x-1][current.y] = false;
            }
            if(current.x < field.size.x-1 && mask[current.x+1][current.y]){
                list.append(Position(current.x+1,current.y));
                mask[current.x+1][current.y] = false;
            }
            if(current.y > 0 && mask[current.x][current.y-1]){
                list.append(Position(current.x,current.y-1));
                mask[current.x][current.y-1] = false;
            }
            if(current.y < field.size.y-1 && mask[current.x][current.y+1]){
                list.append(Position(current.x,current.y+1));
                mask[current.x][current.y+1] = false;
            }

        }
        int size;
        worker = new ActiveEffect[size = effects.size()];
        for(int i = 0; i < size; i++){
            worker[i] = effects.first();
            effects.pop_front();
        }
        return Spell("Success", cost, worker, size);
    }
    return Spell("Error", 1,worker, 0);
}
Example #7
0
  void CacheThread::run()
  {
    while (!p->exit_)
    {
      // Wait until we're told there are images we need to request.
      waiting_mutex_.lock();

      // Next, get all of them and sort them by priority.
      p->unprocessed_mutex_.lock();
      QList<ImagePtr> images = p->unprocessed_.values();
      p->unprocessed_mutex_.unlock();

      qSort(images.begin(), images.end(), ComparePriority);

      // Go through all of them and request them.  Qt's network manager will
      // only handle six simultaneous requests at once, so we use a semaphore
      // to limit ourselves to that many.
      // Each individual image will release the semaphore when it is done loading.
      // Also, only load up to a certain number at a time in this loop.  If there
      // are more left afterward, we'll start over.  This ensures that we
      // concentrate on processing the highest-priority images.
      int count = 0;
      while (!p->exit_ && !images.empty() && count < MAXIMUM_SEQUENTIAL_REQUESTS)
      {
        p->network_request_semaphore_.acquire();

        ImagePtr image = images.front();
        p->unprocessed_mutex_.lock();
        if (!image->Loading() && !image->Failed())
        {
          count++;
          image->SetLoading(true);
          images.pop_front();

          QString uri = image->Uri();
          size_t hash = p->uri_to_hash_map_[uri];
          if (uri.startsWith(QString("file:///")))
          {
            image->InitializeImage();
            QString filepath = uri.replace(QString("file:///"), QString("/"));
            if (!image->GetImage()->load(filepath))
            {
              image->ClearImage();
              image->AddFailure();
            }

            p->unprocessed_.remove(hash);
            p->uri_to_hash_map_.remove(uri);
            image->SetLoading(false);
            p->network_request_semaphore_.release();
          }
          else
          {
            Q_EMIT RequestImage(image->Uri());
          }
        }
        else
        {
          images.pop_front();
        }
        p->unprocessed_mutex_.unlock();

      }
      if (!images.empty())
      {
        waiting_mutex_.unlock();
      }
    }
  }
Example #8
0
void ActorEditTool::selectActor(wt::ASceneActor* actor){
	if(mState == eSTATE_NORMAL){
		if(mSelectedActor){
			mSelectedActor->setBoundingBoxColor(wt::Color::Green());
		}

		mSelectedActor = actor;

		ui.transform->setEnabled(actor!=NULL);

		if(!actor){
			return;
		}

		mSelectedActor->setBoundingBoxColor(wt::Color::Red());

		wt::Scene& scene = *mScene;

		glm::vec3 pos;
		mSelectedActor->getTransformable()->getTranslation(pos);

		glm::vec3 eyePos;
		mScene->getCamera().getTranslation(eyePos);

		if(actor->getActorType() == wt::ASceneActor::eTYPE_MODELLED){
			// We don't want this to emit a signal
			ui.comboBoxAnimation->blockSignals(true);
			ui.comboBoxAnimation->clear();

			ui.comboBoxAnimation->setEnabled(true);
			ui.comboBoxAnimation->addItem("none");

			wt::ModelledActor* modelledActor = static_cast<wt::ModelledActor*>(actor);

			if(static_cast<wt::ModelledActor*>(actor)->getModel()){
				// Populate the animation combo box with the current actors animations
				uint32_t index = 1;
				int32_t activeIndex = -1;
				for(wt::Model::AnimationMap::iterator i=static_cast<wt::ModelledActor*>(actor)->getModel()->getAnimations().begin(); i!=static_cast<wt::ModelledActor*>(actor)->getModel()->getAnimations().end(); i++){
					ui.comboBoxAnimation->addItem(i->first.c_str());

					if(modelledActor->getAnimationPlayer()->getCurrentAnimation() == i->second){
						activeIndex = index;
					}

					++index;
				}

				ui.comboBoxAnimation->blockSignals(false);

				if(activeIndex > 0){
					ui.comboBoxAnimation->setCurrentIndex(activeIndex);
				}
			}

			ui.stackedWidget->setCurrentIndex(0);

			ui.comboBoxAnimation->blockSignals(false);
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_PARTICLE_EFFECT){
			ui.stackedWidget->setCurrentIndex(1);
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_POINT_LIGHT){
			ui.stackedWidget->setCurrentIndex(2);

			const wt::PointLight* light = static_cast<const wt::PointLight*>(actor);
		
			ui.lightAttenuation->setValue(glm::vec3(
				light->getDesc().attenuation.constant,
				light->getDesc().attenuation.linear,
				light->getDesc().attenuation.quadratic
			));

			ui.lightColor->setColor(
				light->getDesc().color
			);

			ui.lightAmbientIntensity->setValue(
				light->getDesc().ambientIntensity
			);

			ui.lightDiffuseIntensity->setValue(
				light->getDesc().diffuseIntensity
			);
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_SOUND){
			ui.stackedWidget->setCurrentIndex(3);

			const wt::Sound* sound = dynamic_cast<const wt::Sound*>(actor);

			ui.volume->setValue( sound->getSound()->getVolume()*100.0f );

			ui.attenuation->setValue( sound->getSound()->getAttenuation() );

			ui.minDistance->setValue( sound->getSound()->getMinimumDistance() );

			ui.pitch->setValue( sound->getSound()->getPitch() );
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_COLLIDER){
			ui.stackedWidget->setCurrentIndex(4);
		}
		else{
			WT_THROW("Unsupported actor type");
		}

		// Update tarnsform information
		updateSelectionStats();
	}
	else if(mState == eSTATE_PICK_ATTACH_ACTOR){
		if(actor == NULL){
			mAttachActor = NULL;
		}

		if(actor->getActorType() == wt::ASceneActor::eTYPE_MODELLED){
			 mAttachActor = dynamic_cast<wt::ModelledActor*>(actor);

			 

			 if(mAttachActor->getModel()->hasSkeleton()){
				 QList<wt::SkeletonBone*> bones;
				 bones << mAttachActor->getModel()->getSkeleton();

				 ui.attachBone->clear();

				 while(!bones.empty()){
					 wt::SkeletonBone* bone = bones.front();
					 bones.pop_front();

					 for(uint32_t i=0; i<bone->getNumChildren(false); i++){
						 bones.push_back(bone->getChildAt(i));
					 }

					 QString boneName = QString(bone->getName().c_str());
					 ui.attachBone->addItem( boneName );
				 }
			 }
		}
		
		mState = eSTATE_NORMAL;
		
	}
}
Example #9
0
  /**
  * \Brief Problem Factory
  * Select features from user's choice layers within
  * a specific bounding box
  * param nbLayers # wanted layers
  * param layersFactor layers importance
  * param layersName layers in problem
  * param lambda_min west bbox
  * param phi_min south bbox
  * param lambda_max east bbox
  * param phi_max north bbox
  * param scale the scale
  */
  Problem* Pal::extract( int nbLayers, char **layersName, double *layersFactor, double lambda_min, double phi_min, double lambda_max, double phi_max, double scale, std::ofstream *svgmap )
  {
    Q_UNUSED( svgmap );
    // to store obstacles
    RTree<PointSet*, double, 2, double> *obstacles = new RTree<PointSet*, double, 2, double>();

    Problem *prob = new Problem();

    int i, j;

    double bbx[4];
    double bby[4];

    double amin[2];
    double amax[2];

    int max_p = 0;

    LabelPosition* lp;

    bbx[0] = bbx[3] = amin[0] = prob->bbox[0] = lambda_min;
    bby[0] = bby[1] = amin[1] = prob->bbox[1] = phi_min;
    bbx[1] = bbx[2] = amax[0] = prob->bbox[2] = lambda_max;
    bby[2] = bby[3] = amax[1] = prob->bbox[3] = phi_max;


    prob->scale = scale;
    prob->pal = this;

    LinkedList<Feats*> *fFeats = new LinkedList<Feats*> ( ptrFeatsCompare );

    FeatCallBackCtx *context = new FeatCallBackCtx();
    context->fFeats = fFeats;
    context->scale = scale;
    context->obstacles = obstacles;
    context->candidates = prob->candidates;

    context->bbox_min[0] = amin[0];
    context->bbox_min[1] = amin[1];

    context->bbox_max[0] = amax[0];
    context->bbox_max[1] = amax[1];

#ifdef _EXPORT_MAP_
    context->svgmap = svgmap;
#endif

#ifdef _VERBOSE_
    std::cout <<  nbLayers << "/" << layers->size() << " layers to extract " << std::endl;
    std::cout << "scale is 1:" << scale << std::endl << std::endl;

#endif


    /* First step : extract feature from layers
     *
     * */
    int oldNbft = 0;
    Layer *layer;

    QList<char*> *labLayers = new QList<char*>();

    lyrsMutex->lock();
    for ( i = 0; i < nbLayers; i++ )
    {
      for ( QList<Layer*>::iterator it = layers->begin(); it != layers->end(); ++it ) // iterate on pal->layers
      {
        layer = *it;
        // Only select those who are active and labellable (with scale constraint) or those who are active and which must be treated as obstaclewhich must be treated as obstacle
        if ( layer->active
             && ( layer->obstacle || ( layer->toLabel && layer->isScaleValid( scale ) ) ) )
        {

          // check if this selected layers has been selected by user
          if ( strcmp( layersName[i], layer->name ) == 0 )
          {
            // check for connected features with the same label text and join them
            if ( layer->getMergeConnectedLines() )
              layer->joinConnectedFeatures();

            context->layer = layer;
            context->priority = layersFactor[i];
            // lookup for feature (and generates candidates list)

#ifdef _EXPORT_MAP_
            *svgmap << "<g inkscape:label=\"" << layer->name << "\"" << std::endl
            <<  "    inkscape:groupmode=\"layer\"" << std::endl
            <<  "    id=\"" << layer->name << "\">" << std::endl << std::endl;
#endif

            context->layer->modMutex->lock();
            context->layer->rtree->Search( amin, amax, extractFeatCallback, ( void* ) context );
            context->layer->modMutex->unlock();

#ifdef _EXPORT_MAP_
            *svgmap  << "</g>" << std::endl << std::endl;
#endif

#ifdef _VERBOSE_
            std::cout << "Layer's name: " << layer->getName() << std::endl;
            std::cout << "     scale range: " << layer->getMinScale() << "->" << layer->getMaxScale() << std::endl;
            std::cout << "     active:" << layer->isToLabel() << std::endl;
            std::cout << "     obstacle:" << layer->isObstacle() << std::endl;
            std::cout << "     toLabel:" << layer->isToLabel() << std::endl;
            std::cout << "     # features: " << layer->getNbFeatures() << std::endl;
            std::cout << "     # extracted features: " << context->fFeats->size() - oldNbft << std::endl;
#endif
            if ( context->fFeats->size() - oldNbft > 0 )
            {
              char *name = new char[strlen( layer->getName() ) +1];
              strcpy( name, layer->getName() );
              labLayers->push_back( name );
            }
            oldNbft = context->fFeats->size();


            break;
          }
        }
      }
    }
    delete context;
    lyrsMutex->unlock();

    prob->nbLabelledLayers = labLayers->size();
    prob->labelledLayersName = new char*[prob->nbLabelledLayers];
    for ( i = 0; i < prob->nbLabelledLayers; i++ )
    {
      prob->labelledLayersName[i] = labLayers->front();
      labLayers->pop_front();
    }

    delete labLayers;

    if ( fFeats->size() == 0 )
    {
#ifdef _VERBOSE_
      std::cout << std::endl << "Empty problem" << std::endl;
#endif
      delete fFeats;
      delete prob;
      delete obstacles;
      return NULL;
    }

    prob->nbft = fFeats->size();
    prob->nblp = 0;
    prob->featNbLp = new int [prob->nbft];
    prob->featStartId = new int [prob->nbft];
    prob->inactiveCost = new double[prob->nbft];

    Feats *feat;

#ifdef _VERBOSE_
    std::cout << "FIRST NBFT : " << prob->nbft << std::endl;
#endif

    // Filtering label positions against obstacles
    amin[0] = amin[1] = -DBL_MAX;
    amax[0] = amax[1] = DBL_MAX;
    FilterContext filterCtx;
    filterCtx.cdtsIndex = prob->candidates;
    filterCtx.scale = prob->scale;
    filterCtx.pal = this;
    obstacles->Search( amin, amax, filteringCallback, ( void* ) &filterCtx );

    if ( isCancelled() )
    {
      delete fFeats;
      delete prob;
      delete obstacles;
      return 0;
    }

    int idlp = 0;
    for ( i = 0; i < prob->nbft; i++ ) /* foreach feature into prob */
    {
      feat = fFeats->pop_front();
#ifdef _DEBUG_FULL_
      std::cout << "Feature:" << feat->feature->getLayer()->getName() << "/" << feat->feature->getUID() << " candidates " << feat->nblp << std::endl;
#endif
      prob->featStartId[i] = idlp;
      prob->inactiveCost[i] = pow( 2, 10 - 10 * feat->priority );

      switch ( feat->feature->getGeosType() )
      {
        case GEOS_POINT:
          max_p = point_p;
          break;
        case GEOS_LINESTRING:
          max_p = line_p;
          break;
        case GEOS_POLYGON:
          max_p = poly_p;
          break;
      }

      // sort candidates by cost, skip less interesting ones, calculate polygon costs (if using polygons)
      max_p = CostCalculator::finalizeCandidatesCosts( feat, max_p, obstacles, bbx, bby );

#ifdef _DEBUG_FULL_
      std::cout << "All costs are set" << std::endl;
#endif
      // only keep the 'max_p' best candidates
      for ( j = max_p; j < feat->nblp; j++ )
      {
        // TODO remove from index
        feat->lPos[j]->removeFromIndex( prob->candidates );
        delete feat->lPos[j];
      }
      feat->nblp = max_p;

      // update problem's # candidate
      prob->featNbLp[i] = feat->nblp;
      prob->nblp += feat->nblp;

      // add all candidates into a rtree (to speed up conflicts searching)
      for ( j = 0; j < feat->nblp; j++, idlp++ )
      {
        lp = feat->lPos[j];
        //lp->insertIntoIndex(prob->candidates);
        lp->setProblemIds( i, idlp ); // bugfix #1 (maxence 10/23/2008)
      }
      fFeats->push_back( feat );
    }

#ifdef _DEBUG_FULL_
    std::cout << "Malloc problem...." << std::endl;
#endif


    idlp = 0;
    int nbOverlaps = 0;
    prob->labelpositions = new LabelPosition*[prob->nblp];
    //prob->feat = new int[prob->nblp];

#ifdef _DEBUG_FULL_
    std::cout << "problem malloc'd" << std::endl;
#endif


    j = 0;
    while ( fFeats->size() > 0 ) // foreach feature
    {
      if ( isCancelled() )
      {
        delete fFeats;
        delete prob;
        delete obstacles;
        return 0;
      }

      feat = fFeats->pop_front();
      for ( i = 0; i < feat->nblp; i++, idlp++ )  // foreach label candidate
      {
        lp = feat->lPos[i];
        lp->resetNumOverlaps();

        // make sure that candidate's cost is less than 1
        lp->validateCost();

        prob->labelpositions[idlp] = lp;
        //prob->feat[idlp] = j;

        lp->getBoundingBox( amin, amax );

        // lookup for overlapping candidate
        prob->candidates->Search( amin, amax, LabelPosition::countOverlapCallback, ( void* ) lp );

        nbOverlaps += lp->getNumOverlaps();
#ifdef _DEBUG_FULL_
        std::cout << "Nb overlap for " << idlp << "/" << prob->nblp - 1 << " : " << lp->getNumOverlaps() << std::endl;
#endif
      }
      j++;
      delete[] feat->lPos;
      delete feat;
    }
    delete fFeats;

    //delete candidates;
    delete obstacles;


    nbOverlaps /= 2;
    prob->all_nblp = prob->nblp;
    prob->nbOverlap = nbOverlaps;


#ifdef _VERBOSE_
    std::cout << "nbOverlap: " << prob->nbOverlap << std::endl;
    std::cerr << scale << "\t"
              << prob->nbft << "\t"
              << prob->nblp << "\t"
              << prob->nbOverlap << "\t";
#endif

    return prob;
  }
Example #10
0
void MainWindow::compareFiles()
{
    if(list_hist.size() != 0)
    {
        QDir dir;
        QStringList filtros ;
        filtros << "*.jpg" << ".*png" << "*.bmp";

        QString fileName = QFileDialog::getOpenFileName(this,
                                                        tr("Load Image to Compare"),
                                                        QDir::currentPath(),
                                                        tr("Images (*.jpg *.png *.bmp)"));

        QDir file = QFileInfo(fileName).absoluteDir();

        if(fileName.toStdString() != "")
        {
            QString image = fileName.split( "/" ).back();
            QString image_path = file.absolutePath() + "/" + image;
            QString xml = "hist_"+ QString("%1").arg(this->imageID +1, 6, 10, QChar('0')) + ".xml";
            QString xml_path = dir.absolutePath() + "/" + this->HistFolder+"/"+ xml;

            // Extract HSV and compare.
            Histogram *h = new Histogram(image.toStdString(), image_path.toStdString(), xml_path.toStdString());

            // COMPARE HISTOGRAM

            // PARALLEL CODE
            int i;
            QList<Histogram*> list_hist;
            list_hist = this->list_hist;

            #pragma omp parallel firstprivate(list_hist) shared(h)
            {
                #pragma omp for private(i)
                for(i = 0; i < list_hist.length(); i++)
                    h->compareHistogram(h, list_hist.at(i), 1);

                #pragma omp barrier
            }

            // END PARALLEL CODE

            // SORT TOP 15
            QList<Histogram*> ranking;

            for(i = 0; i < list_hist.length(); i++)
            {
                if(ranking.length() < 15)
                {
                    ranking.push_back(list_hist.at(i));
                }
                else
                {
                    if(list_hist.at(i)->getCompare() > ranking.at(0)->getCompare())
                    {
                        ranking.pop_front();
                        ranking.push_back(list_hist.at(i));
                    }
                }

                qSort(ranking.begin(), ranking.end(), compLess<Histogram>());

            }

            this->edit->append("\nTOP 15:\n");

            QList<QString> imagesToShow;

            for(i = ranking.length() - 1; i >= 0 ; i--)
            {
                QString text = "Image: " + QString::fromStdString(ranking.at(i)->getName()) + " is " + QString::number(ranking.at(i)->getCompare()) + "% similar";
                imagesToShow.append("images/" + QString::fromStdString(ranking.at(i)->getName()));

                this->edit->append(text);
            }

            ShowImages showImages(imagesToShow);
            showImages.setWindowTitle("View Images");
            showImages.exec();
        }

    }
    else
    {
        QMessageBox msgBox;
        QString stringMsg = "No existe BBDD de imágenes para comparar.";

        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText(stringMsg);
        msgBox.exec();
    }
}
Example #11
0
void BFSForest::buildForest() {
	QList<RoadVertexDesc> seeds;
	QList<int> groups;

	QMap<RoadEdgeDesc, bool> visitedEdge;
	QMap<RoadVertexDesc, bool> visitedVertex;

	// ルートとして与えられた頂点について
	for (int i = 0; i < roots.size() / 2; i++) {
		RoadVertexDesc src = roots[i * 2];
		RoadVertexDesc tgt = roots[i * 2 + 1];

		// エッジの取得
		RoadEdgeDesc e_desc = GraphUtil::getEdge(roads, src, tgt);

		// エッジのグループ、seedフラグを設定
		roads->graph[e_desc]->group = i;
		roads->graph[e_desc]->seed = true;

		// 頂点srcが既存のシードと重複している場合
		if (seeds.contains(src)) {
			// 頂点srcをコピーする
			RoadVertex* v = new RoadVertex(roads->graph[src]->pt);
			RoadVertexDesc new_src = boost::add_vertex(roads->graph);
			roads->graph[new_src] = v;

			// 古いエッジを削除
			roads->graph[e_desc]->valid = false;

			// 新しいエッジを追加
			e_desc = GraphUtil::addEdge(roads, new_src, tgt, roads->graph[e_desc]);

			src = new_src;
		}

		// 頂点tgtが既存のシードと重複している場合
		if (seeds.contains(tgt)) {
			// 頂点tgtをコピーする
			RoadVertex* v = new RoadVertex(roads->graph[tgt]->pt);
			RoadVertexDesc new_tgt = boost::add_vertex(roads->graph);
			roads->graph[new_tgt] = v;

			// 古いエッジを削除
			roads->graph[e_desc]->valid = false;

			// 新しいエッジを追加
			e_desc = GraphUtil::addEdge(roads, src, new_tgt, roads->graph[e_desc]);

			tgt = new_tgt;
		}

		// src、tgtが更新されたかも知れないので、おおもとのデータも更新しておく
		roots[i * 2] = src;
		roots[i * 2 + 1] = tgt;

		// シードを登録する
		seeds.push_back(src);
		seeds.push_back(tgt);
		groups.push_back(i);
		groups.push_back(i);

		// ルートエッジ・頂点を訪問済みとマークする
		visitedEdge[e_desc] = true;
		visitedVertex[src] = true;
		visitedVertex[tgt] = true;
	}

	// ルート頂点リストからスタートして、BFSで全頂点を訪問する
	while (!seeds.empty()) {
		RoadVertexDesc parent = seeds.front();
		seeds.pop_front();

		int group = groups.front();
		groups.pop_front();

		std::vector<RoadVertexDesc> children;

		// 隣接ノードリストを先に洗い出す
		std::vector<RoadVertexDesc> nodes;
		std::vector<RoadEdgeDesc> edges;
		RoadOutEdgeIter ei, eend;
		for (boost::tie(ei, eend) = boost::out_edges(parent, roads->graph); ei != eend; ++ei) {
			if (!roads->graph[*ei]->valid) continue;
			if (visitedEdge[*ei]) continue;

			// 隣接ノードを取得
			RoadVertexDesc child = boost::target(*ei, roads->graph);
			if (!roads->graph[child]->valid) continue;

			if (getParent(parent).contains(child)) continue;

			nodes.push_back(child);
			edges.push_back(*ei);

			// 当該エッジを通過したとマークする
			visitedEdge[*ei] = true;
		}

		// 洗い出した隣接ノードに対して、訪問する
		for (int i = 0; i < nodes.size(); i++) {
			RoadVertexDesc child = nodes[i];

			if (visitedVertex.contains(child)) { // 訪問済みの場合
				RoadEdgeDesc orig_e_desc = GraphUtil::getEdge(roads, parent, child);

				// もともとのエッジを無効にする
				roads->graph[orig_e_desc]->valid = false;

				// 対象ノードが訪問済みの場合、対象ノードをコピーして子ノードにする
				RoadVertexDesc child2 = GraphUtil::addVertex(roads, roads->graph[child]);
				roads->graph[child2]->virt = false;

				// エッジ作成
				RoadEdgeDesc e_desc = GraphUtil::addEdge(roads, parent, child2, roads->graph[orig_e_desc]);

				roads->graph[e_desc]->group = group;

				children.push_back(child2);
			} else { // 未訪問の場合
				visitedVertex[child] = true;
				roads->graph[edges[i]]->group = group;

				children.push_back(child);

				seeds.push_back(child);
				groups.push_back(group);
			}
		}

		this->children.insert(parent, children);
	}
}