예제 #1
0
파일: imagelistmodel.cpp 프로젝트: vos/qsm
void ImageListModel::fetchMore(const QModelIndex &)
{
    int remainder = m_imageInfoList.count() - m_imageInfoCount;
    int itemsToFetch = qMin(100, remainder);

    int beginIndex = m_imageInfoCount;
    int endIndex = beginIndex + itemsToFetch;
    if (endIndex >= m_imageInfoList.count())
        endIndex = m_imageInfoList.count() - 1;

    beginInsertRows(QModelIndex(), beginIndex, endIndex);
    m_imageInfoCount += itemsToFetch;
    endInsertRows();

    // start multithreaded image loading
    for (int i = beginIndex; i <= endIndex; i++) {
        const ImageInfo imageInfo = m_imageInfoList.at(i);
        if (imageInfo.exists()) {
            ImageLoader *imageLoader = new ImageLoader(imageInfo.imagePath(), i);
            imageLoader->setScaleSize(MainWindow::MAX_THUMBNAIL_SIZE, MainWindow::MAX_THUMBNAIL_SIZE);
            connect(imageLoader, SIGNAL(imageLoaded(QImage, int, int, int)), SLOT(thumbnailLoaded(QImage, int, int, int)));
            m_imageLoaderPool.start(imageLoader);
        }
    }

    emit changed();
    qDebug("ImageListModel::fetchMore(): from %d to %d", beginIndex, endIndex);
}
예제 #2
0
void WeatherItemFactory::updateItem(ListView* list, bb::cascades::VisualNode *listItem,
        const QString &type, const QVariantList &indexPath, const QVariant &data)
{
    Q_UNUSED(list);
    Q_UNUSED(indexPath);
    Q_UNUSED(type);

    // Update the control with the correct data.
    QVariantMap map = data.value<QVariantMap>();
    WeatherItem *weatherItem = static_cast<WeatherItem *>(listItem);

    ImageLoader *imloader = new ImageLoader();
    imloader->loadImage(map["weatherIconUrl"].toString(), weatherItem->getConditionsImage(), "/wsymbols01_png_64/", ".png");

    //set labels
    weatherItem->setTime(map["time"].toString());

    weatherItem->setWindSpeed(map["windspeedKmph"].toString());

    weatherItem->setTemperature(map["tempC"]);

    weatherItem->setCloudCover(map["cloudcover"].toString());

    weatherItem->setPressure(map["pressure"].toString());

    weatherItem->setHumidity(map["humidity"].toString());

    weatherItem->setSwellHeight(map["swellHeight_m"].toString());

    //rotate arrows
    weatherItem->setWindDirection(180 + map["winddirDegree"].toFloat());

    weatherItem->setSwellDirection(180 + map["swellDir"].toFloat());
}
예제 #3
0
bool OverlayEffect::draw(ImageOf<PixelRgb>& src2, ImageOf<PixelRgb>& dest2) {
  if (needRead) {
    readEffectData();
    needRead = false;
  }
  dest2 = src2;

  if (img.isValid()) {
    for (int x=0; x<dest2.width()&&x<img.width(); x++) {
      for (int y=0; y<dest2.height()&&y<img.height(); y++) {
	PixelBgra v = img.pixel(x,y);
	if (v.a==0) {
	  dest2(x,y) = PixelRgb(v.r,v.g,v.b);
	} else if (v.a>=127) {
	  // do nothing, leave copied value
	} else {
	  PixelRgb& o = dest2(x,y);
	  float f = v.a/127.0;
	  if (f>1) f = 1;
	  int r = (int)((1-f)*v.r+f*o.r);
	  int g = (int)((1-f)*v.g+f*o.g);
	  int b = (int)((1-f)*v.b+f*o.b);
	  dest2(x,y) = PixelRgb(r,g,b);
	}
      }
    }
  }


  return true;
}
예제 #4
0
void MainScreen::onInit(ScreenContext& sc)
{
    // Store engine ref
    mEngine = sc.GetEngine();

    // Store file data cache ref
    mFileDataCache = sc.GetFileDataCache();

    // Cube rotation state
    mRotationData.degreesInc = 0.05f;
    mRotationData.rotating = false;

    // Camera initial position
    mCamera.SetPos(glm::vec3(0, 0, 8));

    // Add sample UV Sphere
    ModelData sphereModel = GenUVSphere(1, 32, 32);
    mEngine->GetModelStore().Load("4", std::move(sphereModel));

    // Create world objects
    SetupWorld();

    // Create world lights
    SetupLights();

    // Cam shouldn't follow character initially
    mFollowingCharacter = false;

    // Initial choosen moving light
    mMovingLightIndex = 0;

    // Init character
    mCharacter.Init(&mEngine->GetWindow(), mScene.get());

    // Load the skybox
    ImageLoader imLoader;
    auto& cubemapStore = mEngine->GetCubemapStore();
    cubemapStore.Load(skybox, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/bluesky.tga"], "tga"));
    mEngine->GetSkyboxRenderer().SetCubemapId(cubemapStore[skybox]->id);

    // Load the irr map
    mEngine->GetCubemapStore().Load(irrmap, imLoader.Load(*(*mFileDataCache)["ext/Assets/Textures/Skybox/Bluesky/bluesky_irr.tga"], "tga"));

    // Load the rad map
    for (unsigned int i = 0; i < 9; ++i) {
        mEngine->GetCubemapStore().Load(
            radmap,
            imLoader.Load(*(*mFileDataCache)[
                              "ext/Assets/Textures/Skybox/Bluesky/bluesky_rad_" + std::to_string(i) + ".tga"], "tga"), i);
    }

    // Do not show AABBs by default
    mShowAABBs = false;

    // Do not show Debug info by default
    mShowDbgInfo = false;

    // Init renderform creator
    mRenderformCreator = std::make_unique<RenderformCreator>(&(mEngine->GetModelStore()), &(mEngine->GetMaterialStore()));
}
unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth)
{
	// the purpose of this phase is to make the images sortable such that 
	// in a sort list of images, every image that an image depends on
	// occurs in the list before it.
	if ( fDepth == 0 ) {
		// break cycles
		fDepth = maxDepth;
		
		// get depth of dependents
		unsigned int minDependentDepth = maxDepth;
		for(unsigned int i=0; i < libraryCount(); ++i) {
			ImageLoader* dependentImage = libImage(i);
			if ( (dependentImage != NULL) && !libIsUpward(i) ) {
				unsigned int d = dependentImage->recursiveUpdateDepth(maxDepth);
				if ( d < minDependentDepth )
					minDependentDepth = d;
			}
		}
	
		// make me less deep then all my dependents
		fDepth = minDependentDepth - 1;
	}
	
	return fDepth;
}
예제 #6
0
unsigned int __stdcall Texture::Atlas::ThreadLoadTexture( void* data ) {
  Thread::Work *work = ( Thread::Work* ) data;
  ThreadDataLoadTexture *loader = ( ThreadDataLoadTexture* ) work->data;
  //__log.PrintInfo( Filelevel_DEBUG, "Texture::Atlas::ThreadLoadTexture => begin: data[%d] size[%d; %d]", loader->data->getLength(), loader->size.width, loader->size.height );
  //

  ImageLoader image;
  if( !image.LoadFromBuffer( ( Byte* ) loader->data->getData(), loader->data->getLength() ) ) {
    __log.PrintInfo( Filelevel_ERROR, "Texture::Atlas::ThreadLoadTexture => image.LoadFromBuffer failed" );
    work->status = Thread::THREAD_WORK_STATUS_ERROR;
    return 1;
  }
  Dword
    *dst = ( Dword* ) loader->atlas->textureData.getData(),
    *src = ( Dword* ) image.GetImageData();
  for( Dword y = 0; y < image.GetImageSize().height; ++y ) {
    memcpy( dst + ( loader->item->rect.top + y ) * loader->atlas->size.width + loader->item->rect.left, src + y * image.GetImageSize().width, image.GetImageSize().width * 4 );
  }
  loader->atlas->FlushToGPU();

  //done
  delete loader->data;
  delete loader;
  work->status = Thread::THREAD_WORK_STATUS_DONE;
  //__log.PrintInfo( Filelevel_DEBUG, "Texture::Atlas::ThreadLoadTexture => done" );
  return 0;
}//ThreadLoadTexture
// private method that handles circular dependencies by only search any image once
const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name, 
			const ImageLoader** dsiStart, const ImageLoader**& dsiCur, const ImageLoader** dsiEnd, const ImageLoader** foundIn) const
{
	const ImageLoader::Symbol* sym;
	// search self
	if ( notInImgageList(this, dsiStart, dsiCur) ) {
		sym = this->findExportedSymbol(name, false, foundIn);
		if ( sym != NULL )
			return sym;
		*dsiCur++ = this;
	}

	// search directly dependent libraries
	for(unsigned int i=0; i < libraryCount(); ++i) {
		ImageLoader* dependentImage = libImage(i);
		if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
			const ImageLoader::Symbol* sym = dependentImage->findExportedSymbol(name, false, foundIn);
			if ( sym != NULL )
				return sym;
		}
	}
	
	// search indirectly dependent libraries
	for(unsigned int i=0; i < libraryCount(); ++i) {
		ImageLoader* dependentImage = libImage(i);
		if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
			*dsiCur++ = dependentImage; 
			const ImageLoader::Symbol* sym = dependentImage->findExportedSymbolInDependentImagesExcept(name, dsiStart, dsiCur, dsiEnd, foundIn);
			if ( sym != NULL )
				return sym;
		}
	}

	return NULL;
}
예제 #8
0
void PipelineManager::setup(QStringList fx, QDir &input, QDir &output)
{
    // Chargement des images comme première étape du pipeline
    ImageLoader *loader = new ImageLoader(this);
    loader->setName("loader");
    loader->setImageDir(input);
    stageList.append(loader);

    // Préparation des effets
    foreach (QString fxName, fx) {
        if (!effects.hasEffect(fxName)) {
            qDebug() << "unkown effect " << fxName;
            continue;
        }
        EffectStage *fxStage = new EffectStage(this);
        fxStage->setName(fxName);
        fxStage->setEffect(effects.effect(fxName));
        stageList.append(fxStage);
    }

    // Sauvegarde des images comme dernière étape du pipeline
    ImageSaver *saver = new ImageSaver(this);
    saver->setName("saver");
    saver->setOutput(output);
    stageList.append(saver);
}
예제 #9
0
void test_video() {

	VideoCapture cap(CV_CAP_ANY);
	ImageProcessor processor;
	ImageLoader loader;
	NeuralNetwork net;
	net.load(NET_FILE_NAME);

	//net.visualize_hidden_units(1, 50);

	if (!cap.isOpened()) {
		cout << "Failed to initialize camera\n";
		return;
	}

	namedWindow("CameraCapture");
	namedWindow("ProcessedCapture");

	cv::Mat frame;
	while (true) {

		cap >> frame;

		cv::Mat processedFrame = processor.process_image(frame);

		if(processedFrame.rows * processedFrame.cols == INPUT_LAYER_SIZE) {

			mat input = loader.to_arma_mat(processedFrame);

			int label = net.predict(input);

			if(label == 0)
				putText(frame, "A", Point(500, 300), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar::all(0), 3, 8);
			else if(label == 1)
				putText(frame, "E", Point(500, 300), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar::all(0), 3, 8);
			else if(label == 2)
				putText(frame, "I", Point(500, 300), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar::all(0), 3, 8);
			else if(label == 3)
				putText(frame, "O", Point(500, 300), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar::all(0), 3, 8);
			else if(label == 4)
				putText(frame, "U", Point(500, 300), FONT_HERSHEY_SCRIPT_SIMPLEX, 2, Scalar::all(0), 3, 8);
		}

		imshow("CameraCapture", frame);
		imshow("ProcessedCapture", processedFrame);

		int key = waitKey(5);

		if(key == 13) {
			imwrite("captura.jpg", frame);
		}
		if (key == 27)
			break;
	}

	destroyAllWindows();
}
예제 #10
0
void OverlayEffect::readEffectData() {
  if (workOverlay!="") {
    if (workOverlay!=readOverlay) {
      img.load(workOverlay.c_str());
      printf("overlay size %dx%d\n", img.width(), img.height());
      readOverlay = workOverlay;
    }
  }
}
예제 #11
0
int main()
{
	ImageLoader loader;
	auto f = loader.LoadImage("../Resource/Fig0310(a)(Moon Phobos).jpg");
	auto low_high(HW::strechlim(f));
	//auto hist(HW::imhist(f,255));
	auto g = HW::imadjust(f, low_high, 0,1);

	ImageWriter writer;
	writer.WritePNGImage(g, "imadjustTest.png");
	return 0;
}
예제 #12
0
파일: mouse.cpp 프로젝트: KoMaTo3/LightTest
/*
=============
  SetCursor
=============
*/
void Mouse::SetCursor( const std::string &imageFileName )
{
  this->cursor.isHardware = true;

  ImageLoader image;
  image.LoadFromFile( imageFileName );

  this->cursor.size.Set( float( image.GetImageSize()->width ) , float( image.GetImageSize()->height ) );
  this->cursor.spriteOffset.Set( this->cursor.size.x * 0.5f * this->cursor.pixelsToTexels.x, this->cursor.size.y * 0.5f * this->cursor.pixelsToTexels.y, 0.0f );

  ShowCursor( false );
}//SetCursor
예제 #13
0
 Assets::Texture* Md2Parser::loadTexture(const Md2Skin& skin) {
     const Path skinPath(String(skin.name));
     MappedFile::Ptr file = m_fs.openFile(skinPath);
     
     Color avgColor;
     const ImageLoader image(ImageLoader::PCX, file->begin(), file->end());
     
     const Buffer<unsigned char>& indices = image.indices();
     Buffer<unsigned char> rgbImage(indices.size() * 3);
     m_palette.indexedToRgb(indices, indices.size(), rgbImage, avgColor);
     
     return new Assets::Texture(skin.name, image.width(), image.height(), avgColor, rgbImage);
 }
예제 #14
0
 void
 Image::load( const std::string &filename )
 {
   using namespace std;
   size_t pos = filename.find_last_of('.');
   if ( pos == string::npos ) {
     std::string mess("Image::load: Can't load image ");
     mess.append(filename);
     throw new Exception(mess);
   }
   const string ext = filename.substr(pos+1);
   ImageLoader *imgLoader = ImageLoader::getImageLoader(ext);
   imgData = imgLoader->load(filename);
 }
void ClientStateIndicator::RunConnectionAnimation(wxTimerEvent& WXUNUSED(event)){
	
	if(indexIndVis < numOfIndic){
		indexIndVis++;
		for(int j = 0; j < indexIndVis; j++){
			ImageLoader *currInd = m_connIndV[j];
			currInd->Show(true);
		}
	}else{
		indexIndVis = 0;
		for(int i = 0; i < numOfIndic; i++){
			ImageLoader *currInd = m_connIndV[i];
			currInd->Show(false);
		}
	}
}
예제 #16
0
	EntityArchetype::EntityArchetype(xmlpp::Document* doc, ImageLoader& loader, Database* db) {
		const xmlpp::Element* root = dynamic_cast<const xmlpp::Element*>(doc->get_root_node());
			
		name = dynamic_cast<const xmlpp::Element*>(root->find("name")[0])->get_child_text()->get_content();
		width = atoi(dynamic_cast<const xmlpp::Element*>(root->find("width")[0])->get_child_text()->get_content().c_str());
		height = atoi(dynamic_cast<const xmlpp::Element*>(root->find("height")[0])->get_child_text()->get_content().c_str());
		frames = atoi(dynamic_cast<const xmlpp::Element*>(root->find("frames")[0])->get_child_text()->get_content().c_str());
		std::string imgName = dynamic_cast<const xmlpp::Element*>(root->find("image")[0])->get_child_text()->get_content();
		
		if (!root->find("scripts").empty()) {
			const xmlpp::Element* scripts = dynamic_cast<const xmlpp::Element*>(root->find("scripts")[0]);
			if (!scripts->find("idle").empty())
				idleScript = dynamic_cast<const xmlpp::Element*>(scripts->find("idle")[0])->get_child_text()->get_content();
			if (!scripts->find("timer").empty())
				timerScript = dynamic_cast<const xmlpp::Element*>(scripts->find("timer")[0])->get_child_text()->get_content();
			if (!scripts->find("init").empty())
				initScript = dynamic_cast<const xmlpp::Element*>(scripts->find("init")[0])->get_child_text()->get_content();
		}
		
		std::vector<xmlpp::Node*> modeNodes = root->find("modes");
		for (unsigned int i = 0; i < modeNodes.size(); ++i) {
			modes.push_back(dynamic_cast<const xmlpp::Element*>(modeNodes[i])->get_child_text()->get_content());
		}
		
		image = loader.loadFromFile("gfx/entities/" + imgName);
	}
void ImageLoader::bindAllLazyPointers(const LinkContext& context, bool recursive)
{
	if ( ! fAllLazyPointersBound ) {
		fAllLazyPointersBound = true;

		if ( recursive ) {
			// bind lower level libraries first
			for(unsigned int i=0; i < libraryCount(); ++i) {
				ImageLoader* dependentImage = libImage(i);
				if ( dependentImage != NULL )
					dependentImage->bindAllLazyPointers(context, recursive);
			}
		}
		// bind lazies in this image
		this->doBindJustLazies(context);
	}
}
예제 #18
0
Sampler2D::Sampler2D(const std::string &filename, u32 s){
	settings = s;

	ImageLoader loader;
	ImageData image = loader.loadTrueRaw(filename);
	width = image.width;
	height = image.height;
	info("SAMPLER", "from:", filename, width, ":", height);
	switch(image.originalFormat){
		case gl::RED :
			data = make_unique<SamplerSingleChannelU8>(image.data, image.width, image.height);
			break;
		case gl::BGR : break;
		case gl::BGRA : break;
	};

}
예제 #19
0
FrameDisplayGL ::FrameDisplayGL(QWidget *parent)
{
    QGLFormat frmt;
    setFormat(frmt);

    currWidth =visibleRegion().boundingRect().width();
    currHeight=visibleRegion().boundingRect().height();
    QString msg = QString("Loading image into QImage");
    Profiler timer(msg);
    timer.start();
    ImageLoader i;
    QString x("/home/xmk/programming/capella/test/images/m51.jpg");
    image = i.imageLoader( &x, 0 );

    //i.loadImage("/home/xmk/programming/skeleton/test/images/m42.jpg", 1 );
    timer.finish();
}
void ImageRGBA::load(const boost::filesystem::path &pfname, const ImageLoader &loader)
{
  this->loadBase(pfname, loader, 32);

  if(loader.hasPremultiplyAlpha())
  {
    this->premultiplyAlpha();
  }
}
예제 #21
0
Background::Background(ImageLoader& loader, Matrix2D<TileAndOverlay_s>* matrixPointer) :
    m_matrixPointer(matrixPointer),
    m_tileMap(),
    m_offsetx(0),
    m_offsety(0),
    m_h(0),
    m_w(0)
{
    m_tileMap[TileEnum_FOREST] = &loader.getImage(FOREST_TILE_PATH);
    m_tileMap[TileEnum_GRASS]  = &loader.getImage(GRASS_TILE_PATH);
    m_tileMap[TileEnum_WATER]  = &loader.getImage(WATER_TILE_PATH);

    /* Pick the width and height of the first tile, assume they are all equally sized */
    m_h = m_tileMap.begin()->second->getHeight();
    m_w = m_tileMap.begin()->second->getWidth();

    std::cout << "Loaded images" << std::endl;
}
void ImageGridDataProvider::loadMoreImages()
{
	int count = 0;
	int s = this->m_imageFilePaths.size();

	qDebug() << "[ImageGridDataProvider::loadMoreImages] m_loadedItems: " << m_loadedItems << ", s: " << s << ", m_loadingCount: " << m_loadingCount;

	// Make sure the model never loads more images than it should at the same time or more than it should
	if(m_loadingCount == 0 && m_loadedItems < s){

		ImageLoader *loader = NULL;
		while( count < ImageGridDataProvider::MAX_ITENS && s > (count + m_loadedItems) ){

			// don't forget to set the Parent Object or else is memory leak!
			loader = new ImageLoader( m_imageFilePaths.at(m_loadedItems + count), this);

			bool ok = connect(loader,
							SIGNAL(imageChanged()), this,
							SLOT(onImageChanged()));
			Q_UNUSED(ok);
			Q_ASSERT_X(ok,"[ImageGridDataProvider::loadMoreImages]", "connect imageChanged failed");

			m_dataModel->append( loader );
			loader->load();

			// Don't start loading images while ImageLoader instances are created on this while loop or else we have a race condition!
			// m_loadedItems is incremented on onImageChanged and it's possible that an image is finished loading before the while is done.

			++count;
			++m_loadingCount;
			Q_ASSERT_X(m_loadingCount <= ImageGridDataProvider::MAX_ITENS,"[ImageGridDataProvider::loadMoreImages]", "loading count max exceed!");
		}

		// Start loading the images only after the loop is done! This a very simple way of preventing the race condition.
		/*for(int i = 0; i < count; i++){
			loader = m_dataModel->value(m_loadedItems + i);
			loader->load();
		}*/
		loader = NULL;
	}
	else{
		qDebug() << "[ImageGridDataProvider::loadMoreImages] maximum loading reached! Must wait until all images finish loading or must add new images to load.";
	}
}
예제 #23
0
파일: loader.cpp 프로젝트: hgl888/neon
extern void* start(int img_size, int inner_size, bool center, bool flip,
                   bool rgb, bool multiview, int minibatch_size,
                   char *filename, int macro_start,
                   uint num_data, uint num_labels, bool macro,
                   DeviceParams* params) {
    static_assert(sizeof(int) == 4, "int is not 4 bytes");
    try {
        int nchannels = (rgb == true) ? 3 : 1;
        int item_max_size = nchannels*inner_size*inner_size;
        // These objects will get freed in the destructor of ImageLoader.
        Device* device;
#if HASGPU
        if (params->_type == CPU) {
            device = new Cpu(params);
        } else {
            device = new Gpu(params);
        }
#else
        assert(params->_type == CPU);
        device = new Cpu(params);
#endif
        Reader*     reader;
        if (macro == true) {
            reader = new MacrobatchReader(filename, macro_start,
                                          num_data, minibatch_size);
        } else {
            reader = new ImageFileReader(filename, num_data,
                                         minibatch_size, img_size);
        }
        Decoder* decoder = new ImageDecoder(inner_size, flip);
        ImageLoader* loader = new ImageLoader(minibatch_size, item_max_size,
                                              num_labels, device,
                                              reader, decoder);
        int result = loader->start();
        if (result != 0) {
            printf("Could not start data loader. Error %d", result);
            delete loader;
            exit(-1);
        }
        return (void *) loader;
    } catch(...) {
        return 0;
    }
}
예제 #24
0
void ShopItemFactory::updateItem(ListView* list, bb::cascades::VisualNode *listItem,
        const QString &type, const QVariantList &indexPath, const QVariant &data)
{
    Q_UNUSED(list);
    Q_UNUSED(indexPath);
    Q_UNUSED(type);

    // Update the control with the correct data.
    QVariantMap map = data.value<QVariantMap>();
    ShopItem *recipeItem = static_cast<ShopItem *>(listItem);
    //recipeItem->updateItem(map["fruit"].toString());
    ImageLoader *imloader = new ImageLoader();
    imloader->loadImage(map["productthumb"].toString(), recipeItem->itemImage(),"/products/",".png");

    //set labels
    recipeItem->setTitle(map["productname"].toString());

    recipeItem->setDescription("Credits: " + map["productprice"].toString() + "\nCards: "+map["productnumcards"].toString());
}
예제 #25
0
int main(int argc, char** argv) {

	ImageLoader loader;
	ImageProcessor processor;
	vector<pair<mat, mat> > training_data, validation_data, test_data;
	//MNISTDataLoader::load_mnist_data(training_data, validation_data, test_data,	MNIST_DIR, CANT_VALIDATION_ELEMENTS);
	loader.load_image_data(training_data, validation_data, test_data, SIGN_IMAGE_DIR, CANT_VALIDATION_ELEMENTS);

	//visualize_data(training_data, 50, 255);

	train_net(training_data, validation_data);
	//evaluate_net(test_data);

	//test_video();

	//processor.process_image_dir(SIGN_IMAGE_DIR);

	return 0;
}
예제 #26
0
    void ImageFont::addGlyph(unsigned char c, int &x,
                             int &y, const Color& separator)
    {
        ImageLoader* il = Image::_getImageLoader();

        Color color;
        do
        {
            ++x;

            if (x >= il->getWidth())
            {
                y += mHeight + 1;
                x = 0;

                if (y >= il->getHeight())
                {
                    std::string str;
                    std::ostringstream os(str);
                    os << "Image ";
                    os << mFilename;
                    os << " with font is corrupt near character '";
                    os << c;
                    os << "'";
                    //throw GCN_EXCEPTION(os.str());
                    assert(0);
                }
            }

            color = il->getPixel(x, y);

        } while (color == separator);

        int w = 0;

        do
        {
            ++w;

            if (x+w >= il->getWidth())
            {
                std::string str;
                std::ostringstream os(str);
                os << "Image ";
                os << mFilename;
                os << " with font is corrupt near character '";
                os << c;
                os << "'";
                //throw GCN_EXCEPTION(os.str());
                assert(0);
            }

            color = il->getPixel(x + w, y);

        } while (color != separator);

        mGlyph[c] = Rectangle(x, y, w, mHeight);

        x += w;
    }
void ImageLoader::markedUsedRecursive(const std::vector<DynamicReference>& dynamicReferences)
{
	// already visited here
	if ( fMarkedInUse )
		return;
	fMarkedInUse = true;
	
	// clear mark on all statically dependent dylibs
	for(unsigned int i=0; i < libraryCount(); ++i) {
		ImageLoader* dependentImage = libImage(i);
		if ( dependentImage != NULL ) {
			dependentImage->markedUsedRecursive(dynamicReferences);
		}
	}
	
	// clear mark on all dynamically dependent dylibs
	for (std::vector<ImageLoader::DynamicReference>::const_iterator it=dynamicReferences.begin(); it != dynamicReferences.end(); ++it) {
		if ( it->from == this )
			it->to->markedUsedRecursive(dynamicReferences);
	}
	
}
예제 #28
0
	Ball(Renderer& renderer, ImageLoader& imageLoader, int m_x, int m_y, double m_ballSpeed = 1.0, double m_moveAngle = 0.0) : 
		GameObject(renderer, imageLoader.loadSurface(g_assetsFolder + "ball.bmp", renderer), m_x, m_y, getBallWidth(), getBallWidth()) {
		ballSpeed = m_ballSpeed;
		moveX = ballSpeed * cos(m_moveAngle);
		moveY = ballSpeed * sin(m_moveAngle);
	}
예제 #29
0
/*
=============
  LoadTexture
=============
*/
Texture::Atlas::Item* Texture::Atlas::LoadTexture( const std::string& textureFileName, const bool forceLoad )
{
  ImageLoader image;
  Size size( 0, 0 );
  memory *deferredLoadingData;

  if( forceLoad ) {
    if( !image.LoadFromFile( textureFileName ) ) {
      __log.PrintInfo( Filelevel_ERROR, "Texture::Atlas::LoadTexture => file not found '%s'", textureFileName.c_str() );
      return NULL;
    }
    size = image.GetImageSize();
  } else {
    deferredLoadingData = new memory();
    __fileManager->GetFile( textureFileName, *deferredLoadingData );
    size = ImageLoader::GetImageSizeFromBuffer( ( Byte* ) deferredLoadingData->getData(), deferredLoadingData->getLength() );
  }

  if( !this->atlas.HasPlace( size ) ) {
    __log.PrintInfo( Filelevel_ERROR, "Texture::Atlas::LoadTexture => atlas can't find needed place [ %d; %d ]", size.width, size.height );
    return NULL;
  }

  Texture::Atlas::Item *item = new Texture::Atlas::Item();
  Rect< Dword > fullRect;
  this->atlas.Cut( size + Size( this->borderPerItem * 2, this->borderPerItem * 2 ), &fullRect );
  item->rect = Rect< Dword >( fullRect.left + 1, fullRect.top + 1, fullRect.right - 1, fullRect.bottom - 1 );
  item->textureFileName = textureFileName;

  Vec2 scale( float( item->rect.right - item->rect.left + 1 ) / float( this->size.width ), float( item->rect.bottom - item->rect.top + 1 ) / float( this->size.height ) );
  Vec2 translate( float( item->rect.left ) / float( this->size.width ), float( item->rect.top ) / float( this->size.height ) );

  item->matTransform.Identity();
  Mat4 matTranslate, matScale, matInvTranslate, matInvScale;
  matTranslate.Identity();
  matInvTranslate.Identity();
  matScale.Identity();
  matInvScale.Identity();

  matScale[ 0 ][ 0 ] = scale.x;
  matScale[ 1 ][ 1 ] = scale.y;
  matInvScale[ 0 ][ 0 ] = 1.0f / scale.x;
  matInvScale[ 1 ][ 1 ] = 1.0f / scale.y;

  matTranslate[ 0 ][ 3 ] = translate.x;
  matTranslate[ 1 ][ 3 ] = translate.y;
  matInvTranslate[ 0 ][ 3 ] = -translate.x;
  matInvTranslate[ 1 ][ 3 ] = -translate.y;

  //__log.PrintInfo( Filelevel_DEBUG, "matrix translate: [ %3.3f; %3.3f ]", translate.x, translate.y );
  //__log.PrintInfo( Filelevel_DEBUG, "matrix scale: [ %3.3f; %3.3f ]", scale.x, scale.y );

  item->matTransform = matTranslate * matScale;
  item->matInvTransform = matInvScale * matInvTranslate;

  //размещение картинки в текстуре
  if( forceLoad ) {
    //this->Bind();
    Dword
      *dst = ( Dword* ) this->textureData.getData(),
      *src = ( Dword* ) image.GetImageData();
    for( Dword y = 0; y < image.GetImageSize().height; ++y ) {
      memcpy( dst + ( item->rect.top + y ) * this->size.width + item->rect.left, src + y * image.GetImageSize().width, image.GetImageSize().width * 4 );
    }
    //glTexImage2D( GL_TEXTURE_2D, 0, 4, this->size.width, this->size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, this->textureData.getData() );
    //this->Unbind();
    this->FlushToGPU();
  } else {
    // TODO: здесь отложенная загрузка
    // класть в стек deferredLoadingData, указатель на атлас и Texture::Atlas::Item item
    ThreadDataLoadTexture *loader = new ThreadDataLoadTexture();
    loader->data = deferredLoadingData;
    loader->size = size;
    loader->atlas = this;
    loader->item = item;
    extern Thread::Pipeline *__workPipeline;
    __workPipeline->Add( loader, Texture::Atlas::ThreadLoadTexture );
  }

  this->textures.push_back( item );
  return item;
}//LoadTexture
예제 #30
0
int main(int argc, char** args){

	srand(time(NULL));
	functions func;
	ofstream a;
	a.open("output.log");

	// check if the MALAG approves PG studies
	bool MALAG = true;
	if( argc > 1){
		if(args[1][6] == 'n'){
			MALAG = false;
		}
	}

	//////// READING INPUT FILES ////////

	int numOfSemesters = 0;
	int CS_elective = 0; // number of elective courses a CS student has to take
	int PG_elective = 0; // number of elective courses a PG student has to take
	string s1("curriculum.conf");
	func.readCurriculum(s1, numOfSemesters, CS_elective, PG_elective);
	s1.clear();

	vector<Course*> CS_courses;
	vector<Course*> PG_courses;
	vector<Course*> EL_courses;
	string s2("courses.conf");
	func.readCourses(s2, CS_courses, PG_courses, EL_courses);
	s2.clear();

	vector<Student*> CS_students;
	vector<Student*> PG_students;
	string s3("students.conf");
	func.readStudents(s3, CS_students, PG_students, CS_elective, PG_elective);
	s3.clear();

	// sort courses and students
	func.sortCourses(CS_courses, numOfSemesters);
	func.sortCourses(PG_courses, numOfSemesters);
	func.sortCourses(EL_courses, numOfSemesters);
	func.quicksort(CS_students, 0, CS_students.size()-1);
	func.quicksort(PG_students, 0, PG_students.size()-1);

	// check if the MALAG approves politics & government studies
	if (!MALAG){
		for (int i = 0 ; i < (int)PG_students.size() ; i++){
			string s = PG_students[i]->getID() + " is being denied his education";
			func.print(s);
		}
	}

	//////// A DEGREE SIMULATION ////////

	for (int i = 1 ; i <= numOfSemesters ; i++){
		func.printSemester(i);

		///// REGISTRATION //////
		for (int j = 0 ; j < (int)CS_students.size() ; j++){
			CS_students[j]->reg(i, CS_courses, EL_courses);
		}
		if (MALAG){
			for (int j = 0 ; j < (int)PG_students.size() ; j++){
				PG_students[j]->reg(i, PG_courses, EL_courses);
			}
		}

		///// TEACHING /////
		for (int j = 0 ; j < (int)CS_courses.size() ; j++){
			CS_courses[j]->teach();
		}
		if (MALAG){
			for (int j = 0 ; j < (int)PG_courses.size() ; j++){
				PG_courses[j]->teach();
			}
		}
		for (int j = 0 ; j < (int)EL_courses.size() ; j++){
			EL_courses[j]->teach();
		}
	}

	///// GRADUATION /////

	// make a list of all the students who started their studies
	vector<Student*> newList;
	newList = CS_students;
	if (MALAG){
		for (int i = 0 ; i < (int)PG_students.size() ; i++){
			newList.push_back(PG_students[i]);
		}
		func.quicksort(newList, 0, newList.size()-1);
	}

	ImageOperations opr;
	int CS_size = CS_students.size();
	int PG_size = PG_students.size();
	ImageLoader CS_picture = ImageLoader(100, 100*CS_size);
	ImageLoader PG_picture = ImageLoader(100, 100*PG_size);
	int CS_counter = 0;
	int PG_counter = 0;

	for (int i = 0 ; i < (int)newList.size() ; i++){
		// resize image
		ImageLoader srcPic(newList[i]->getImage());
		ImageLoader newPic = ImageLoader(100, 100);
		opr.resize(srcPic.getImage(),newPic.getImage());
		srcPic.getImage().release();

		// graduation for CS students
		if (newList[i]->type() == 'C'){
			string line = func.toString(newList[i]->getID()) + " has ";
			if((newList[i])->isGraduated((int)CS_courses.size(), CS_elective)){
				line = line + "graduated";
				opr.copy_paste_image(newPic.getImage(), CS_picture.getImage(), CS_counter*100);
				CS_counter++;
			}
			else{
				line = line + "not graduated";
				ImageLoader greyscale(100, 100);
				opr.rgb_to_greyscale(newPic.getImage(), greyscale.getImage());
				opr.copy_paste_image(greyscale.getImage(), CS_picture.getImage(), CS_counter*100);
				CS_counter++;
				greyscale.getImage().release();
			}
			func.print(line);
		}
		// graduation for PG students
		else{
			string line = func.toString(newList[i]->getID()) + " has ";
			if((newList[i])->isGraduated((int)PG_courses.size(), PG_elective)){
				line = line + "graduated";
				opr.copy_paste_image(newPic.getImage(), PG_picture.getImage(), PG_counter*100);
				PG_counter++;
			}
			else{
				line = line + "not graduated";
				ImageLoader greyscale = ImageLoader(100, 100);
				opr.rgb_to_greyscale(newPic.getImage(), greyscale.getImage());
				opr.copy_paste_image(greyscale.getImage(), PG_picture.getImage(), PG_counter*100);
				PG_counter++;
				greyscale.getImage().release();
			}
			func.print(line);
		}
		newPic.getImage().release();
	}

	CS_picture.saveImage("CS.jpg");
	PG_picture.saveImage("PG.jpg");
	CS_picture.displayImage();
	PG_picture.displayImage();

	///// DELETE DATA /////

	// delete courses
	func.deleteVector(CS_courses);
	func.deleteVector(PG_courses);
	func.deleteVector(EL_courses);

	// delete students
	func.deleteVector(CS_students);
	func.deleteVector(PG_students);

	// delete images
	CS_picture.getImage().release();
	PG_picture.getImage().release();

	a.close();
}