Exemplo n.º 1
0
void BlobDetector::detect()
{

    double sigmaFirst = data->getSigmaFirst();
    double sigmaStep = data->getSigmaStep();
    for (int oID = 0; oID < data->octavs.size(); oID++)
    {
        //data->octavs[oID]->genDOG();
        double sigma = sigmaFirst*(1<<oID);
        double littlesigma = 1;

        for (int layerID = 1; layerID < data->octavs[oID]->dogs.size()-1; layerID++)
        {
            unique_ptr<HarrisDetector> harrisDetector = make_unique<HarrisDetector>(data->octavs[oID]->layers[layerID].get());
            harrisDetector->configure(0.01,0.06,1);
            ImageMap* img =  data->octavs[oID]->dogs[layerID].get();
            for (int x=0;x<img->getWidth();x++)
            {
                for (int y=0;y<img->getHeight();y++)
                {
                    bool isMax = true;
                    bool isMin = true;
                    double val = img->getData(x,y);//* sigma;
                    if(val<0.031 && val>-0.031) continue;
                    //double ds =  sigma/sigmaStep;
                    //int dl = layerID;
                    for (int dl = layerID-1; dl <= layerID+1; dl++)
                    {
                        ImageMap* img1 =  data->octavs[oID]->dogs[dl].get();
                        for(int dx = x-1; dx <= x+1; dx++)
                        {
                            for(int dy = y-1; dy <= y+1; dy++)
                            {
                                double val1 = img1->getData(dx,dy);//*ds;
                                if (dx != x || dy != y || dl != layerID)
                                {
                                    isMax &= (val1 < val);
                                    isMin &= (val1 > val);
                                }

                            }
                        }
                      //  ds*=sigmaStep;
                    }
                    if (isMax || isMin)
                    {
                        Blob b = Blob(x,y,sigma,val);
                        b.scale = (oID);
                        data->blobs.push_back(b);
                        data->blobs[data->blobs.size()-1].isClone = false;
                        data->descriptors.push_back(harrisDetector->calcDescriptor(littlesigma,&(data->blobs[data->blobs.size()-1])));
                    }
               }
          }
            littlesigma*=sigmaStep;
            sigma*=sigmaStep;
       }
    }
}
Exemplo n.º 2
0
	Point Contour::commitPoint(const Point& p, const Image& img, ImageMap& split)
	{
		if (split.getAssignedSegment(p) == NULL && img.isFilled(p))
		{
			split.assignSegment(p, this);
			push_back(p);
		}
		return p;
	}
Exemplo n.º 3
0
/**
 * Get a sprite reference from the \a rcd_file, retrieve the corresponding sprite, and put it in the \a spr destination.
 * @param rcd_file File to load from.
 * @param sprites Sprites already loaded from this file.
 * @param [out] spr Pointer to write the loaded sprite to.
 * @return Loading was successful.
 */
bool LoadSpriteFromFile(RcdFileReader *rcd_file, const ImageMap &sprites, ImageData **spr)
{
	uint32 val = rcd_file->GetUInt32();
	if (val == 0) {
		*spr = nullptr;
		return true;
	}
	const auto iter = sprites.find(val);
	if (iter == sprites.end()) return false;
	*spr = iter->second;
	return true;
}
Exemplo n.º 4
0
void ImageLoader::load_library(Atom name, const std::string& filename) {
    ImageMap images;
    if (has_extension(filename, ".ilb")) {
        BOOST_LOG_TRIVIAL(info) << "Loading image library: " << filename;
        load_ilb(filename, graphics, images);
    } else if (has_extension(filename, ".hss")) {
        BOOST_LOG_TRIVIAL(info) << "Loading image library: " << filename;
        load_hss(filename, graphics, images);
    } else {
        BOOST_LOG_TRIVIAL(warning) << "Don't know how to load image library: " << filename;
    }

    ImageLibraryResource *lib = resources->image_libraries[name].get();
    for (auto iter = images.begin(); iter != images.end(); iter++) {
        Image *image = iter->second;
        lib->images[image->id].reset(image);
    }
    lib->loaded = true;
}
Exemplo n.º 5
0
int ShellBrowserChild::get_entry_image(ShellEntry* entry, LPCITEMIDLIST pidl, int shgfi_flags, ImageMap& cache)
{
	SHFILEINFO sfi;
	int idx = -1;

	ImageMap::const_iterator found = cache.find(entry);

	if (found != cache.end())
		return found->second;

	if (SHGetFileInfo((LPCTSTR)pidl, 0, &sfi, sizeof(sfi), shgfi_flags|SHGFI_PIDL|SHGFI_ICON|SHGFI_ADDOVERLAYS)) {
		idx = ImageList_AddIcon(_himl, sfi.hIcon);

		DestroyIcon(sfi.hIcon);
	}

	cache[entry] = idx;

	return idx;
}
Exemplo n.º 6
0
void SpecificWorker::getImages(const CameraList &cameras, ImageMap &images)
{
	if( cameras.size() <= MAX_CAMERAS and ( cameraParamsMap.find(cameras.front()) != cameraParamsMap.end()))
	{
		//uint size = cameraParamsMap[cameras.front()].colorHeight * cameraParamsMap[cameras.front()].colorWidth * 3;
		RoboCompRGBDBus::Image img;
		img.camera = cameraParamsMap[cameras.front()];
		QMutexLocker ml(mutex);
		img.colorImage.resize( readBuffer.size());
		img.colorImage.swap( readBuffer );
		images.insert( std::pair<std::string, RoboCompRGBDBus::Image>("default", img));
		std::cout << "camera name " <<cameras.front() << " " << img.colorImage.size() << " " << images.empty() << std::endl;
	}
}
Exemplo n.º 7
0
int main()
{
	ImageMap figurel;
	short int lowerLegl[] = { 1, 10, 2, 10, 3, 10, -1, -1 };
	short int thighl[] = { 4, 9, 5, 8, 6, 7 , 7 , 6, -1, -1 };
	short int thigh2[] = { 6, 7, 7, 8, 8, 9, -1, -1 };
	short int lowerLeg2[] = { 8, 10, 8, 11, -1, -1 };
	short int torso[] = { 8, 5, 9, 4, 10, 3, 11, 2, -1, -1 };
	short int upperArms[] = { 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, -1, -1 };
	short int foreArml[] = { 12, 5, 13, 4, -1, -1 };
	short int foreArm2[] = { 6, 3, 5, 4, -1, -1 };
	short int * figurelAllParts[] =
	{
		lowerLegl, lowerLeg2, thighl, thigh2, torso,
		upperArms, foreArml, foreArm2, 0
	};
	int k = 0;
	for (int k = 0; figurelAllParts[k] != 0; k++)
		figurel.add(figurelAllParts[k]);
	ImageMap figure2;
	short int p2LowerLegl[] = { 1, 11, 2, 10, 3, 9, -1, -1 };
	short int p2thighl[] = { 3, 9, 3, 8, 3, 7 - 1, -1 };
	short int p2thigh2[] = { 4, 7, 5, 7, 6, 7, -1, -1 };
	short int p2LowerLeg2[] = { 6, -8, 6, 9, -1, -1 };
	short int p2torso[] = { 3, 6, 3, 5, 3, 4, 3, 3, 3, 2, 3, 1, -1, -1 };
	short int p2UpperArms[] = { 1, 3, 2, 3, 4, 3, 5, 3, -1, -1 };
	short int p2foreArm1[] = { 1, 4, 1, 5, -1, -1 };
	short int p2foreArm2[] = { 5, 2, 5, 1, -1, -1 };
	short int *figure2Al1Parts[] =
	{
		p2LowerLegl, p2thighl, p2thigh2, p2LowerLeg2,
		p2torso, p2UpperArms, p2foreArm1, p2foreArm2, 0
	};

	for (int k = 0; figure2Al1Parts[k] != 0; k++)
		figure2.add(figure2Al1Parts[k]);
	ImageMap figure3;

	short int p3torso[] = { 4, 7, 4, 6, 4, 5, 4, 4, 4, 3, 4, 2, 4, 1, -1, -1 };
	short int p3Thighl[] = { 5, 8, 6, 9, -1, -1 };
	short int p3Thigh2[] = { 3, 8, 2, 9, -1, -1 };
	short int p3LowerLegl[] = { 6, 10, 6, 11, -1, -1 };
	short int p3LowerLeg2[] = { 1, 8, 0, 7, -1, -1 };
	short int p3UpperArml[] = { 3, 4, 2, 5, -1, -1 };
	short int p3UpperArm2[] = { 5, 4, 6, 5, -1, -1 };
	short int p3ForeArml[] = { 3, 6, 4, 7, -1, -1 };
	short int p3ForeArm2[] = { 7, 4, 8, 3, -1, -1 };
	short int * figure3Al1Parts[] =
	{
		p3torso, p3Thighl, p3Thigh2, p3LowerLegl,
		p3LowerLeg2,p3UpperArml, p3UpperArm2,
		p3ForeArml, p3ForeArm2, 0
	};

	for (int k = 0; figure3Al1Parts[k] != 0; k++)
		figure3.add(figure3Al1Parts[k]);
	system("cls");
	ImageMap *sequence[3] = { &figurel, &figure2, &figure3 };
	k = 0;
	int pos = 0;
	while (pos <= 60)
	{
		sequence[k]->displayAt(pos, 3);
		Sleep(400);

		sequence[k]->eraseAt(pos, 3);
		k = (k + 1) % 3;
		pos = pos + 8;
	}
	sequence[k]->displayAt(pos, 3);
	return 0;
		
}
Exemplo n.º 8
0
int GetImageIndex(const wxString &fileName)
{
  int imageInd = -1;
  wxString fileExt = fileName.AfterLast(wxChar('.'));

#ifdef _WIN32
  // Special case for windows executables, icon and cursor files.
  if (fileExt.CmpNoCase(wxT("exe")) == 0 || fileExt.CmpNoCase(wxT("ico")) == 0 || fileExt.CmpNoCase(wxT("cur")) == 0)
  {
    // Do we already have an icon for the file?
    ImageMap::iterator it = g_imageMap.find(fileName);
    if (it != g_imageMap.end())
    {
      // Use exsiting icon.
      imageInd = it->second;
    }
    else
    {
      wxString fullname = fileName;
      if (fileExt.CmpNoCase(wxT("exe")) == 0)
        fullname += wxT(";0"); // Icon index.

      // Try to load 16x16 icon. Load any icon if fails.
      wxIcon icon;
      if (!icon.LoadFile(fullname, wxBITMAP_TYPE_ICO, 16, 16))
        icon.LoadFile(fullname, wxBITMAP_TYPE_ICO);

      // Add the icon into the list.
      if (icon.Ok())
      {
        if (fileExt.CmpNoCase(wxT("cur")) != 0)
        {
          // Convert to bitmap. It fixes the alpha problem.
          wxBitmap bmp(icon);
          if (bmp.Ok())
            imageInd = g_imageList->Add(bmp);
        }
        else
        {
          // Can't convert cursor to bitmap.
          imageInd = g_imageList->Add(icon);
        }
      }

      if (imageInd >= 0)
        g_imageMap.insert(ImagePair(fileName, imageInd));
    }
  }
#endif // _WIN32

  if (imageInd < 0 && fileExt.Length() > 0)
  {
    // Do we already have an icon for the file type?
    ImageMap::iterator it = g_imageMap.find(fileExt);
    if (it != g_imageMap.end())
    {
      // Use exsiting icon.
      imageInd = it->second;
    }
    else
    {
      // Ask mime types manager for the file type.
      // TODO: For some types (sdf, sln) it returns wrong index for the icon. Fix it.
      // TODO: For some types (doc, html) it returns invalid file name for the icon. Fix it.
      wxFileType *fileType = wxTheMimeTypesManager->GetFileTypeFromExtension(fileExt);
      if (fileType != NULL)
      {
        // Get icon location.
        wxIconLocation iconLoc;
        if (fileType->GetIcon(&iconLoc))
        {
          wxString fullname = iconLoc.GetFileName();
#ifdef _WIN32
          if (iconLoc.GetIndex())
            fullname << wxT(';') << iconLoc.GetIndex();
#endif

          // Try to load 16x16 icon. Load any icon if fails.
          wxIcon icon;
          if (!icon.LoadFile(fullname, wxBITMAP_TYPE_ICO, 16, 16))
            icon.LoadFile(fullname, wxBITMAP_TYPE_ICO);

          // Add the icon into the list.
          if (icon.Ok())
          {
            // Convert to bitmap. It fixes the alpha problem.
            wxBitmap bmp(icon);
            if (bmp.Ok())
              imageInd = g_imageList->Add(bmp);
          }

          if (imageInd >= 0)
            g_imageMap.insert(ImagePair(fileExt, imageInd));
        }

        delete fileType;
      }
    }
  }

  // If no image found.
  if (imageInd < 0)
  {
    // Set default image.
    g_imageMap.insert(ImagePair(fileExt, kUnknownFileImage));
    imageInd = kUnknownFileImage;
  }

  return imageInd;
}
Exemplo n.º 9
0
/**
 * Load sprites from the disk.
 * @param filename Name of the RCD file to load.
 * @return Error message if load failed, else \c nullptr.
 * @todo Try to re-use already loaded blocks.
 * @todo Code will use last loaded surface as grass.
 */
const char *SpriteManager::Load(const char *filename)
{
	RcdFileReader rcd_file(filename);
	if (!rcd_file.CheckFileHeader("RCDF", 2)) return "Bad header";

	ImageMap sprites; // Sprites loaded from this file.
	TextMap  texts;   // Texts loaded from this file.
	TrackPiecesMap track_pieces; // Track pieces loaded from this file.

	/* Load blocks. */
	for (uint blk_num = 1;; blk_num++) {
		if (!rcd_file.ReadBlockHeader()) return nullptr; // End reached.

		/* Skip meta blocks. */
		if (strcmp(rcd_file.name, "INFO") == 0) {
			rcd_file.SkipBytes(rcd_file.size);
			continue;
		}

		if (strcmp(rcd_file.name, "8PXL") == 0 || strcmp(rcd_file.name, "32PX") == 0) {
			ImageData *imd = LoadImage(&rcd_file);
			if (imd == nullptr) {
				return "Image data loading failed";
			}
			std::pair<uint, ImageData *> p(blk_num, imd);
			sprites.insert(p);
			continue;
		}

		if (strcmp(rcd_file.name, "SURF") == 0) {
			if (!this->LoadSURF(&rcd_file, sprites)) return "Surface block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "TSEL") == 0) {
			if (!this->LoadTSEL(&rcd_file, sprites)) return "Tile-selection block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "PATH") == 0) {
			if (!this->LoadPATH(&rcd_file, sprites)) return "Path-sprites block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "TCOR") == 0) {
			if (!this->LoadTCOR(&rcd_file, sprites)) return "Tile-corners block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "FUND") == 0) {
			if (!this->LoadFUND(&rcd_file, sprites)) return "Foundation block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "PLAT") == 0) {
			if (!this->LoadPLAT(&rcd_file, sprites)) return "Platform block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "SUPP") == 0) {
			if (!this->LoadSUPP(&rcd_file, sprites)) return "Support block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "BDIR") == 0) {
			if (!this->LoadBDIR(&rcd_file, sprites)) return "Build arrows block loading failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "GCHK") == 0) {
			if (!_gui_sprites.LoadGCHK(&rcd_file, sprites)) return "Loading Checkable GUI sprites failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "GBOR") == 0) {
			if (!_gui_sprites.LoadGBOR(&rcd_file, sprites)) return "Loading Border GUI sprites failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "GSLI") == 0) {
			if (!_gui_sprites.LoadGSLI(&rcd_file, sprites)) return "Loading Slider bar GUI sprites failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "GSCL") == 0) {
			if (!_gui_sprites.LoadGSCL(&rcd_file, sprites)) return "Loading Scrollbar GUI sprites failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "GSLP") == 0) {
			if (!_gui_sprites.LoadGSLP(&rcd_file, sprites, texts)) return "Loading slope selection GUI sprites failed.";
			continue;
		}

		if (strcmp(rcd_file.name, "ANIM") == 0) {
			Animation *anim = new Animation;
			if (!anim->Load(&rcd_file)) {
				delete anim;
				return "Animation failed to load.";
			}
			if (anim->person_type == PERSON_INVALID || anim->anim_type == ANIM_INVALID) {
				delete anim;
				return "Unknown animation.";
			}
			this->AddBlock(anim);
			this->AddAnimation(anim);
			this->store.RemoveAnimations(anim->anim_type, (PersonType)anim->person_type);
			continue;
		}

		if (strcmp(rcd_file.name, "ANSP") == 0) {
			AnimationSprites *an_spr = new AnimationSprites;
			if (!an_spr->Load(&rcd_file, sprites)) {
				delete an_spr;
				return "Animation sprites failed to load.";
			}
			if (an_spr->person_type == PERSON_INVALID || an_spr->anim_type == ANIM_INVALID) {
				delete an_spr;
				return "Unknown animation.";
			}
			this->AddBlock(an_spr);
			this->store.AddAnimationSprites(an_spr);
			continue;
		}

		if (strcmp(rcd_file.name, "PRSG") == 0) {
			if (!LoadPRSG(&rcd_file)) return "Graphics Person type data failed to load.";
			continue;
		}

		if (strcmp(rcd_file.name, "TEXT") == 0) {
			TextData *txt = new TextData;
			if (!txt->Load(&rcd_file)) {
				delete txt;
				return "Text block failed to load.";
			}
			this->AddBlock(txt);

			std::pair<uint, TextData *> p(blk_num, txt);
			texts.insert(p);
			continue;
		}

		if (strcmp(rcd_file.name, "SHOP") == 0) {
			ShopType *shop_type = new ShopType;
			if (!shop_type->Load(&rcd_file, sprites, texts)) {
				delete shop_type;
				return "Shop type failed to load.";
			}
			_rides_manager.AddRideType(shop_type);
			continue;
		}

		if (strcmp(rcd_file.name, "TRCK") == 0) {
			auto tp = std::make_shared<TrackPiece>();
			if (!tp->Load(&rcd_file, sprites)) {
				return "Track piece failed to load.";
			}
			track_pieces.insert({blk_num, tp});
			continue;
		}

		if (strcmp(rcd_file.name, "RCST") == 0) {
			CoasterType *ct = new CoasterType;
			if (!ct->Load(&rcd_file, texts, track_pieces)) {
				delete ct;
				return "Coaster type failed to load.";
			}
			_rides_manager.AddRideType(ct);
			continue;
		}

		if (strcmp(rcd_file.name, "CSPL") == 0) {
			if (!LoadCoasterPlatform(&rcd_file, sprites)) return "Coaster platform failed to load.";
			continue;
		}

		if (strcmp(rcd_file.name, "CARS") == 0) {
			CarType *ct = GetNewCarType();
			if (ct == nullptr) return "No room to store a car type.";
			if (!ct->Load(&rcd_file, sprites)) return "Car type failed to load.";
			continue;
		}

		/* Unknown block in the RCD file. Skip the block. */
		fprintf(stderr, "Unknown RCD block '%s', version %i, ignoring it\n", rcd_file.name, rcd_file.version);
		rcd_file.SkipBytes(rcd_file.size);
	}
}
Exemplo n.º 10
0
void SymbolLayout::prepare(const GlyphMap& glyphMap, const GlyphPositions& glyphPositions,
                           const ImageMap& imageMap, const ImagePositions& imagePositions,
                           const OverscaledTileID& tileID, const std::string& sourceID) {
    const bool textAlongLine = layout.get<TextRotationAlignment>() == AlignmentType::Map &&
        layout.get<SymbolPlacement>() == SymbolPlacementType::Line;

    auto glyphMapIt = glyphMap.find(layout.get<TextFont>());
    const Glyphs& glyphs = glyphMapIt != glyphMap.end()
        ? glyphMapIt->second : Glyphs();

    auto glyphPositionsIt = glyphPositions.find(layout.get<TextFont>());
    const GlyphPositionMap& glyphPositionMap = glyphPositionsIt != glyphPositions.end()
        ? glyphPositionsIt->second : GlyphPositionMap();

    for (auto it = features.begin(); it != features.end(); ++it) {
        auto& feature = *it;
        if (feature.geometry.empty()) continue;

        std::pair<Shaping, Shaping> shapedTextOrientations;
        optional<PositionedIcon> shapedIcon;

        // if feature has text, shape the text
        if (feature.text) {
            auto applyShaping = [&] (const std::u16string& text, WritingModeType writingMode) {
                const float oneEm = 24.0f;
                const Shaping result = getShaping(
                    /* string */ text,
                    /* maxWidth: ems */ layout.get<SymbolPlacement>() != SymbolPlacementType::Line ?
                        layout.evaluate<TextMaxWidth>(zoom, feature) * oneEm : 0,
                    /* lineHeight: ems */ layout.get<TextLineHeight>() * oneEm,
                    /* anchor */ layout.evaluate<TextAnchor>(zoom, feature),
                    /* justify */ layout.evaluate<TextJustify>(zoom, feature),
                    /* spacing: ems */ util::i18n::allowsLetterSpacing(*feature.text) ? layout.evaluate<TextLetterSpacing>(zoom, feature) * oneEm : 0.0f,
                    /* translate */ Point<float>(layout.evaluate<TextOffset>(zoom, feature)[0] * oneEm, layout.evaluate<TextOffset>(zoom, feature)[1] * oneEm),
                    /* verticalHeight */ oneEm,
                    /* writingMode */ writingMode,
                    /* bidirectional algorithm object */ bidi,
                    /* glyphs */ glyphs);

                return result;
            };

            shapedTextOrientations.first = applyShaping(*feature.text, WritingModeType::Horizontal);

            if (util::i18n::allowsVerticalWritingMode(*feature.text) && textAlongLine) {
                shapedTextOrientations.second = applyShaping(util::i18n::verticalizePunctuation(*feature.text), WritingModeType::Vertical);
            }
        }

        // if feature has icon, get sprite atlas position
        if (feature.icon) {
            auto image = imageMap.find(*feature.icon);
            if (image != imageMap.end()) {
                shapedIcon = PositionedIcon::shapeIcon(
                    imagePositions.at(*feature.icon),
                    layout.evaluate<IconOffset>(zoom, feature),
                    layout.evaluate<IconAnchor>(zoom, feature),
                    layout.evaluate<IconRotate>(zoom, feature) * util::DEG2RAD);
                if (image->second->sdf) {
                    sdfIcons = true;
                }
                if (image->second->pixelRatio != pixelRatio) {
                    iconsNeedLinear = true;
                } else if (layout.get<IconRotate>().constantOr(1) != 0) {
                    iconsNeedLinear = true;
                }
            }
        }

        // if either shapedText or icon position is present, add the feature
        if (shapedTextOrientations.first || shapedIcon) {
            addFeature(std::distance(features.begin(), it), feature, shapedTextOrientations, shapedIcon, glyphPositionMap, tileID, sourceID);
        }
        
        feature.geometry.clear();
    }

    compareText.clear();
}
Exemplo n.º 11
0
void imageCorpusAnalysisApp::analyzeDirectory(string dirName) {
    
    ofDirectory DIR;
    string fdpPath, fp;
    
    totalNumImages = 0;
    totalNumBlobs = 0;
    totalNumImagesToBeAnalyzed = 0;
    currentImageNum = 0;
    
    // scan for fdb file
    DIR.allowExt("fdb");
    int numFDBFiles = DIR.listDir(dirName);
    cout << "# of .fdb files found (should be 1): " << numFDBFiles << endl;
    
    if (numFDBFiles == 1) {
        
        fdpPath = DIR.getPath(0);
        cout << ".fdb file path: " << fdpPath << "\n";
        ifstream ifile;
        ifile.open(ofToDataPath(fdpPath).c_str(), ios::in); // ofToDataPath ???
        string readin;
        
        if (ifile.is_open()) {
            
            getline(ifile, readin);
            string basename = readin;                           // don't use yet
            getline(ifile, readin);
            int numImages = (int)atoi(readin.c_str());          // used only for scanning array
            getline(ifile, readin);
            int numBlobs = (int)atoi(readin.c_str());           // don't use
            getline(ifile, readin);
            int threshold = (int)atoi(readin.c_str());          // this had better be right!
            
            cout << "Initial conditions (from .fdb file): " << numImages << "|" << numBlobs << "|" << threshold << "\n";
            
            for (int i=0; i<numImages; i++) {
                
                getline(ifile, readin, ' ');
                int bindex = (int)atoi(readin.c_str());         // blob index DUMMY!!!!!
//                getline(ifile, readin, ' ');
//                int bthresh = (int)atoi(readin.c_str());        // threshold (*for now, not used)
                getline(ifile, readin, ' ');
                int blobs = (int)atoi(readin.c_str());          // # just for this file

                getline(ifile, readin);
                stringstream ss;
                string blobPng, blobTxt;
                string bstring = readin.c_str();
//                cout << "|" << bstring << "|\n";
//                vector<int> blobvec;
                
                for (int b=0; b<blobs; b++) {

                    ss << bstring << "_" << b << ".png";
//                    cout << "SS: " << ss.str() << "\n";
                    blobPng = ss.str();
                    ss.clear(); ss.str(std::string());

                    ss << bstring << "_" << b << ".txt";
                    blobTxt = ss.str();
                    ss.clear(); ss.str(std::string());
                    
//                    cout << "blobPng/blobTxt:  " << blobPng << " | " << blobTxt << "\n";

                }
//                cout << "inserting: " << totalNumImages << "|" << bstring << "\n";
                mappedFileNames.insert(pair<int, string>(totalNumImages, bstring));
                mappedThresholds.insert(pair<int, int>(totalNumImages, threshold));
//                mappedBlobIDs.insert(pair<int, vector<int> >(totalNumImages, blobvec));
                
                totalNumImages++;
                totalNumBlobs = numBlobs;
                
            }
            
            cout << "After scanning .fdb file...\n";
            cout << "  *total # of images: " << totalNumImages << "\n";
            cout << "  *total # of blobs: " << totalNumBlobs << "\n";
            cout << "  *total # of images TO BE ANALYZED: " << totalNumImagesToBeAnalyzed << "\n";
        }
        ifile.close();
        
    }
    
    string jpegFileName;
    ofDirectory DIR2;
    DIR2.allowExt("jpg");
    int numJPGFiles = DIR2.listDir(dirName);
    cout << "# of JPEG files to import: " << numJPGFiles << "\n";
    
    for (int j=0; j<numJPGFiles; j++) {
        jpegFileName = ofFilePath::removeExt(DIR2.getName(j));
//        cout << ":::  " << jpegFileName << endl;
        
        bool matchFlag = false;
        
        map<int, string>::iterator itz;
        for (itz = mappedFileNames.begin(); itz != mappedFileNames.end(); itz++) {

//            cout << "compare: " << (*itz).second << "|" << jpegFileName << "\n";
            if ((*itz).second == jpegFileName) { // we have a match : do not add to be analyzed
            
                matchFlag = true;
                break;
            
            }
        }
        
        cout << "broke! ... " << (int)matchFlag << "\n";
        if (matchFlag == 0) {
            
            cout << "***total num images: " << totalNumImages << " + j: " << j << "\n";
            cout << "add to analyze: " << (totalNumImages + j) << ", " << jpegFileName << "\n";
            toBeAnalyzedFileNames.insert(pair<int, string>((totalNumImages + totalNumImagesToBeAnalyzed), jpegFileName));
            totalNumImagesToBeAnalyzed++;
        
        }
    }

    cout << "After scanning directory for .jpg files...\n";
    cout << "  * total # of images: " << totalNumImages << "\n"; // TO BE MAPPED (NOT ANALYZED)
    cout << "  * total # of blobs: " << totalNumBlobs << "\n";
    cout << "  * # of images YET TO BE ANALYZED: " << totalNumImagesToBeAnalyzed << "\n";
    cout << "  ** mapped file names map contains:\n";
    
    map<int, string>::iterator it;
    for (it = mappedFileNames.begin(); it != mappedFileNames.end(); it++) {
//        cout << (*it).first << "|" << (*it).second << "\n";
        currentImageNum++;
    }
    
//    cout << "current image #: " << currentImageNum << "\n";
    
    // setup out.fdb
    ofFile ofile;
    ofile.open("random/1/out.fdb", ofFile::WriteOnly);
    
    
    cout << "\n\n\nREPORT: \n\n";    
    // iterate over mapped and pull in metadata/pngs
    cout << "mapped:\n";
    if (mappedFileNames.begin() == mappedFileNames.end()) {
        cout << "\n no mapped files to import.\n";
    } else {
//        for (it = mappedFileNames.begin(); it != mappedFileNames.end(); it++) {
//            cout << "map w/o analyzing: " << (*it).first << "|" << (*it).second << "\n";            
            
        ifstream ifile;
        string fullPath, readin;
//        stringstream ss;
//        ss << "random/" << mappedFileNames[i] << ".jpg";
//        cout << "**************\n\n" << ss.str() << "\n\n";
        ifile.open(ofToDataPath(fdpPath).c_str(), ios::in);
        
        
        if ((ifile.is_open()) && (ofile.is_open())) {
                    
            for (int i=0; i<totalNumImages; i++) {
                
                ImageMap im;
                im.setup(gStandardThreshold);
                im.prefab = true;
                
                stringstream oss;
                
                getline(ifile, readin, ' ');
                int imnum = atoi(readin.c_str());
                cout << "     i|imnum: " << i << "|" << imnum << "   ...   ";
                im.imageID = imnum;
                getline(ifile, readin, ' ');
                im.numberOfRegions = atoi(readin.c_str());
                getline(ifile, readin);
                im.imageFileBase = readin;
                
                //                cout << imnum << "|" << im.numberOfRegions << "||" << basename << "\n";
                    
                for (int reg=0; reg<im.numberOfRegions; reg++) {
                    
                    
                    // get the .txt files' + the .png files' names
                    stringstream sst, ssp, ssmd;
                    sst << dirName << im.imageFileBase << "_" << reg << ".txt";
                    ssp << dirName << im.imageFileBase << "_" << reg << ".png";
                    
                    ofFile mdfile;
                    mdfile.open(sst.str());
                    
                    if ((im.numberOfRegions > 0) && (mdfile.is_open())) {
                        string name;
                        int regionIndex;
                        CvPoint anchor;
                        CvSize size;
                        float area, ratio;
                        CvPoint centroid;
                        int rgbmax;
                        getline(mdfile, readin);
                        name = readin; // DUMMY!
                        getline(mdfile, readin);
                        regionIndex = atoi(readin.c_str());
                        cout << "ri: " << regionIndex << "\n";
                        
                        getline(mdfile, readin, ' ');
                        size.width = atoi(readin.c_str());
                        getline(mdfile, readin);
                        size.height = atoi(readin.c_str());
                        getline(mdfile, readin, ' ');
                        anchor.x = atoi(readin.c_str());
                        getline(mdfile, readin);
                        anchor.y = atoi(readin.c_str());
                        
                        
                        getline(mdfile, readin);
                        area = atof(readin.c_str());
                        getline(mdfile, readin);
                        ratio = atof(readin.c_str());
                        
                        getline(mdfile, readin, ' ');
                        centroid.x = atof(readin.c_str());
                        getline(mdfile, readin);
                        centroid.y = atof(readin.c_str());
                        
                        getline(mdfile, readin);
                        rgbmax = atoi(readin.c_str());
                        
                        im.constructPrefabRegion(name, regionIndex, anchor, size, area, ratio, centroid, rgbmax);
                        
                        im.mappedRegions[regionIndex].regionHistogram.setup();
                        int vals[64];
                        int* vptr;
                        vptr = vals;
                        
                        for (int h=0; h<64; h++) {                   // N_REGIONS!
                           
//                            getline(mdfile, readin, ' ');
//                            int rd = atoi(readin.c_str());
//                            getline(mdfile, readin, ' ');
//                            int gn = atoi(readin.c_str());
//                            getline(mdfile, readin);
//                            int bl = atoi(readin.c_str());
                            getline(mdfile, readin, ' ');
                            vals[h] = atoi(readin.c_str());
                            
//                            im.mappedRegions[regionIndex].regionHistogram.injectHistogram(h, rd, gn, bl);
                        }
                        im.mappedRegions[regionIndex].regionHistogram.injectHistogram(vptr);
                        
//                        int w = im.mappedRegions[regionIndex].size.width*2;
//                        int h = im.mappedRegions[regionIndex].size.height*2;
                        //                        cout << w << "|" << h << "\n";
                        //                        cout << ssp.str() << "\n";
                        //                        cout << ssp.str() << "\n";
//                        ofImage image;
//                        image.loadImage(ssp.str());
//                        
//                        //                        cout << image.width << "\n\n";
//                        
//                        im.mappedRegions[regionIndex].regionImage.allocate(image.width, image.height);
//                        im.mappedRegions[regionIndex].regionImage.setFromPixels(image.getPixels(), image.width, image.height);
                        
                        //                        cout << "and now the histogram:\n" << im.mappedRegions[regionIndex].regionHistogram.writeOutHistogram();
                        
                    } else {
                        cout << "no regions for this file!!!\nor " << sst.str() << " is missing...\n";
                    }
                }                                
//                cout << "inserting imagemap at: " << i << "\n"; 
                mappedImages.insert(pair<int, ImageMap>(i, im));
                // map one line of out.fdb
                oss << im.imageID << " " << im.numberOfRegions << " " << im.imageFileBase << "\n";

                ofile << oss.str();
                oss.flush();

            }
        } else {
            cout << "ERROR: COULD NOT LOAD FILE!\n";
        }
        
    }
    currentImageNum = totalNumImages;
    
    // iterate over toBeAnalyzed and perform analysis
    //    - write txt and png files!
//    cout << "\nto be Analyzed:\n";

//    cout << "curr. image: " << currentImageNum << "\n";
    
    for (it = toBeAnalyzedFileNames.begin(); it != toBeAnalyzedFileNames.end(); it++) {
        stringstream ss, oss;
        ss << "random/1/" << (*it).second << ".jpg";
//        cout << "analyzing: " << (*it).first << "  | " << ss.str() << "\n";
        
        ImageMap newIM;
//        mappedImages.insert(pair<int, ImageMap>(currentImageNum, newIM));
        
        newIM.setup(gStandardThreshold);
        newIM.setupDownsampleThresholdAnalyze( (int)((*it).first), (string)(ss.str()) );

//        cout << "#: " << newIM.numberOfRegions << "\n";
        
        for (int r=0; r<newIM.numberOfRegions; r++) {
//            cout << "r: " << r << endl;
            newIM.findContourMask(r, true);
            newIM.writeAnalysis(r);
            totalNumBlobs++;
        }
        // map one line of out.fdb
        oss.flush();
        oss << newIM.imageID << " " << newIM.numberOfRegions << " " << newIM.imageFileBase << "\n";
        
        mappedImages.insert(pair<int, ImageMap>(currentImageNum, newIM));
        
        totalNumImages++;
        currentImageNum++;
        
        ofile << oss.str();
        oss.flush();
    }
    
    stringstream oss;
    oss << "random/1/" << "\n";
    cout << "TOTALS:\n" << totalNumImages << "\n" << totalNumBlobs << "\n" << gStandardThreshold << "\n";
    oss << totalNumImages << "\n" << totalNumBlobs << "\n" << gStandardThreshold << "\n";
    ofile << oss.str();
    ofile.close();
    
}
Exemplo n.º 12
0
void ZoneListWidget::_createImages(ImageMap& retlist)
{
    retlist.clear();

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( "EntityTex",
                   Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,
                   256, 256, 0, Ogre::PF_A8R8G8B8 , Ogre::TU_RENDERTARGET );

    Ogre::RenderTexture *rttTex = texture->getBuffer()->getRenderTarget();
    Ogre::SceneManager *mSceneMgr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "EntityTexMgr");

    Ogre::Light *dirl = mSceneMgr->createLight("DisplayLight");
    dirl->setDirection(-1,-1,-1);
    dirl->setDiffuseColour(1,1,1);
    dirl->setType(Ogre::Light::LT_DIRECTIONAL);

    Ogre::Camera* RTTCam = mSceneMgr->createCamera("EntityCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0,0,1);
    RTTCam->lookAt(0,0,0);

    Ogre::Viewport *v = rttTex->addViewport( RTTCam );
    v->setClearEveryFrame( true );
    v->setBackgroundColour(Ogre::ColourValue(0,0,0,0));

    ModularZoneFactory* factory = dynamic_cast<ModularZoneFactory*>(OgitorsRoot::getSingletonPtr()->GetEditorObjectFactory("Modular Zone Object"));
    if(!factory)return;
    factory->loadZoneTemplates();
    ZoneInfoMap zoneTemplates = factory->getZoneTemplateMap();

    Ogre::Entity *mEntity;

    unsigned char dataptr[300 * 300 * 6];
    unsigned char *dataptr2;
    Ogre::PixelBox pb(256,256,1,Ogre::PF_A8R8G8B8, dataptr);

    EntityMap entities;
    ZoneInfoMap::iterator zi;
    for(zi=zoneTemplates.begin();zi!=zoneTemplates.end();++zi)
    {
        Ogre::String addstr = (*zi).second.mMesh;
        if(entities.find((*zi).first) == entities.end())
            entities.insert(EntityMap::value_type((*zi).first,addstr));
    }

    EntityMap::const_iterator ite = entities.begin();

    while(ite != entities.end())
    {
        Ogre::String addstr = ite->second;

        mEntity = mSceneMgr->createEntity("MZP_Preview", addstr);

        mSceneMgr->getRootSceneNode()->attachObject(mEntity);

        //TODO: It would be nice to retrieve a Preview Camera Position from
        //the .zone file
        //TODO: also render portal outlines clearly so that the user can see
        //how the zone is laid out
        Ogre::Vector3 vSize = mEntity->getBoundingBox().getCorner(Ogre::AxisAlignedBox::NEAR_RIGHT_TOP);//.getHalfSize();//============
        Ogre::Vector3 vCenter = mEntity->getBoundingBox().getCenter();

//FIXME ------ NICE PREVIEWS NEEDED - bigger

        vSize += Ogre::Vector3(vSize.z, vSize.z, vSize.z);

        float maxsize = std::max(std::max(vSize.x,vSize.y),vSize.z);

        //vSize = Ogre::Vector3(0, 0, maxsize * 1.1f) + vCenter;
        vSize = Ogre::Vector3(maxsize * 0.5f, vSize.y, maxsize * 0.5f) + vCenter;
        //vSize.x +=vSize.x/2;//Maybe test to see which is larger x/2 or z/2 and use that?
        //vSize.z +=vSize.x/2;
        //RTTCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

        RTTCam->setPosition(vSize.x,vSize.y,vSize.z);
        RTTCam->lookAt(vCenter.x,vCenter.y,vCenter.z);

        rttTex->update();
        rttTex->copyContentsToMemory(pb, Ogre::RenderTarget::FB_FRONT);


        dataptr2 = new unsigned char[96 * 96 * 4];
        Ogre::PixelBox pb2(96,96,1,Ogre::PF_A8R8G8B8, dataptr2);
        Ogre::Image::scale(pb,pb2);

        addstr.erase(addstr.length() - 5, 5);
        retlist.insert(ImageMap::value_type((*ite).first, dataptr2));

        mEntity->detachFromParent();
        mSceneMgr->destroyEntity(mEntity);

        ite++;
    }

    rttTex->removeAllViewports();
    Ogre::Root::getSingletonPtr()->destroySceneManager(mSceneMgr);
    Ogre::TextureManager::getSingletonPtr()->unload(texture->getName());
    Ogre::TextureManager::getSingletonPtr()->remove(texture->getName());
}