Esempio n. 1
0
unsigned long CTagBase::mineType() const
{
	if (!_tagFile)
		return ITag::MineType::UNKONW;
	ImageFile* pFile = new ImageFile(_tagFile->name());
	if (!pFile)
		return ITag::MineType::UNKONW;

	if (pFile->isValid())
	{
		TagLib::String s = pFile->mimeType();

		delete pFile;

		if (s == TagLib::String::null)
		{
			return ITag::MineType::UNKONW;
		}
		else if (s == TagLib::String("image/jpeg"))
		{
			return ITag::MineType::JPEG;
		}
		else if (s == TagLib::String("image/png"))
		{
			return ITag::MineType::PNG;
		}		
	}
	delete pFile;
	return ITag::MineType::UNKONW;
}
Esempio n. 2
0
void write_slice(const char *filename, const Grid3DDevice<double> &grid)
{
  Grid3DHost<double> h_grid;
  h_grid.init_congruent(grid);
  h_grid.copy_all_data(grid);


  int nx = grid.nx();
  int ny = grid.ny();
  int nz = grid.nz();

  ImageFile img;
  img.allocate(nx, ny);

  for (int i=0; i < nx; i++)
    for (int j=0; j < ny; j++) {
      double temperature = h_grid.at(i,j,nz/2);
      if (temperature < -2) temperature = -2;
      if (temperature > 2)  temperature = 2;
      //float3 color = make_float3(temperature, temperature, temperature);
      float3 color = hsv_to_rgb(make_float3((temperature)*360, 1, 1));
      //float3 color = pseudo_temperature((temperature+1)*.5);
      img.set_rgb(i,j,(unsigned char)(255*color.x),(unsigned char)(255*color.y),(unsigned char)(255*color.z));
    }

  img.write_ppm(filename);
}
Esempio n. 3
0
ImageFile *
Prefetcher::getTask()
{
    ImageFile *f;
    mutex.lock();
    for (;;)
    {
        while (task_no >= files.count())
        {
            cond_get.wait(&mutex);
        }
        f = &files[task_no];
        task_no++;

        QString k = f->createKey();
        if (cache.contains(k))
        {
            cache[k]; // update
            task_filled++;
            if (task_filled >= files.count())
            {
                cond_put.wakeOne();
            }
        }
        else
        {
            break;
        }
    }
    mutex.unlock();
    return f;
}
Esempio n. 4
0
QImage
PlaylistModel::loadData(const ImageFile &f)
{
    QImage img;
    QByteArray *data = prft.get(f.createKey());
    if (data)
    {
        fprintf(stderr, "cache hit\n");
        img.loadFromData(*data);
    }
    else
    {
        fprintf(stderr, "cache miss\n");
        data = f.readData();
        if (!data) return QImage();
        img.loadFromData(*data);
        delete data;
    }

    if (img.format() != QImage::Format_ARGB32)
    {
        return img.convertToFormat(QImage::Format_ARGB32);
    }
    return img;
}
Esempio n. 5
0
unsigned int ImageFileFactory::getImageDepth(std::string filename) const
{
    ImageFile* file = this->getImageFile(filename);

    unsigned int depth = file->readDepth();

    delete file;

    return depth;
}
int main(int argc, const char * argv[]) {
    ImageFile* imageFile = new ImageFile();
    imageFile->ReadImageFile("/Users/prathebaselvaraju/4-Projects/LightParamterEstimation/lightonplane-withtorus.jpeg");
    
    imageFile->PlotHistogramOfImageIntensity();
    imageFile->WriteImageFile("/Users/prathebaselvaraju/4-Projects/LightParamterEstimation/output.jpeg");
    
    delete imageFile;
    return 0;
}
Esempio n. 7
0
void
Prefetcher::Worker::run()
{
    for (;;)
    {
        ImageFile *f = master->getTask();
        QByteArray *data = f->readData();
        master->setResult(f->createKey(), data);
    }
}
Esempio n. 8
0
static void CheckTextures(std::vector<std::string> * files, MistakesClass * mistakes, const std::string &pb2path)
{
	for (size_t i = 0; i < files->size(); )
	{
		std::string extension = files->at(i).substr(files->at(i).size() - 4);

		if (   extension.compare(".jpg")
			&& extension.compare(".tga")
			&& extension.compare(".wal")
			&& extension.compare(".png")
			&& extension.compare(".pcx")  )
		{
			i++;
			continue; //not a texture file
		}

		if (files->at(i).find("hr4") != std::string::npos)
		{
			mistakes->missingFiles.push_back(files->at(i) + " - always link to the low-res version. File not added.");
			files->erase(files->begin() + i);
			continue; //mapper should link to the low res texture and leave the choice of usign hr4s to the user
		}

		ImageFile img ((pb2path + files->at(i)).c_str());
		if (img.IsOk() && img.IsHeightPowerOfTwo() && img.IsWidthPowerOfTwo())
		{
			size_t pos = files->at(i).find_last_of("/");
			std::string hr4file = files->at(i).substr(0, pos)
								  + "/hr4"
								  + files->at(i).substr(pos, files->at(i).length() - pos - 4)
								  +".img";
			hr4file = GetRealFilename(pb2path, hr4file);

			if (hr4file.length() > 0)
			{
				files->insert(files->begin() + i, hr4file);
				i++; //jump over the created entry to the check for hr4 won't be triggered.
			}
			i++;
		}
		else
		{
			mistakes->missingFiles.push_back(files->at(i) + " - resolution is not power of two. File added.");
			i++;
		}
	}

}
Esempio n. 9
0
int main(int argc, char **argv)
{
  Eqn_Diffusion1DParams params;
  params.h = 1;
  params.nx = 100;
  params.left.type = BC_NEUMANN;
  params.left.value = 0;
  params.right.type = BC_NEUMANN;
  params.right.value = 0;
  params.diffusion_coefficient = 1;

  params.initial_values.init(100, 0);

  int i,t;

  // initialize to an impulse
  for (i=0; i < 100; i++) {
    if (i < 40) params.initial_values.at(i) = 0;
    else if (i < 60) params.initial_values.at(i) = 1;
    else params.initial_values.at(i) = 0;
  }

  Eqn_Diffusion1D eqn;
  if (!eqn.set_parameters(params))
    assert(false);

  ImageFile img;
  img.allocate(100, 800);

  for (t=0; t < 800; t++) {
    eqn.advance(.1);
    eqn.copy_density_to_host();
    
    for (int i=0; i < 100; i++) {
      float soln_val = eqn.density().at(i);
      if (soln_val > 1.0f) soln_val = 1.0f;
      unsigned char color = (unsigned char) (255 * (soln_val / 1.0f));
      img.set_rgb(i,t, color, color, color);
    }
  }


  img.write_ppm("solution.ppm");

  global_timer_print();

  return 0;
}
Esempio n. 10
0
void
Fourier::shuffleNaturalToFourierOrder (ImageFile& im)
{
  ImageFileArray vReal = im.getArray();
  ImageFileArray vImag = im.getImaginaryArray();
  unsigned int ix, iy;
  unsigned int nx = im.nx();
  unsigned int ny = im.ny();

  // shuffle each x column
  for (ix = 0; ix < nx; ix++) {
    Fourier::shuffleNaturalToFourierOrder (vReal[ix], ny);
    if (im.isComplex())
      Fourier::shuffleNaturalToFourierOrder (vImag[ix], ny);
  }

  // shuffle each y row
  float* pRow = new float [nx];
  for (iy = 0; iy < ny; iy++) {
    for (ix = 0; ix < nx; ix++)
      pRow[ix] = vReal[ix][iy];
    Fourier::shuffleNaturalToFourierOrder (pRow, nx);
    for (ix = 0; ix < nx; ix++)
      vReal[ix][iy] = pRow[ix];
    if (im.isComplex()) {
      for (ix = 0; ix < nx; ix++)
        pRow[ix] = vImag[ix][iy];
      Fourier::shuffleNaturalToFourierOrder (pRow, nx);
      for (ix = 0; ix < nx; ix++)
        vImag[ix][iy] = pRow[ix];
    }
  }
  delete [] pRow;
}
Esempio n. 11
0
void AddCharacterDialog::init(Character* character)
{
    mUi.setupUi( this );
    setModal(true);

    mPrevName = "";
    mUi.lImage->setAlignment(Qt::AlignCenter);
    mUi.browseImageButton->setFilter(ChooseFileButton::ImageFilter);
    mUi.statusTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
    mUi.statusTreeWidget->setIconSize(QSize(32, 32));

    if (character) {
        this->setWindowTitle(tr("Edit Character"));
        mUi.nameEdit->setText(character->name());
        QHash<QString, ImageFile*> statesToImages = character->statesToImages();
        QHashIterator<QString, ImageFile*> it(statesToImages);
        while(it.hasNext()) {
            it.next();
            ImageFile* image = it.value();
            if (image) {
                QPixmap pixmap = image->pixmap();
                if (pixmap.height() > mUi.lImage->height())
                    pixmap = pixmap.scaledToHeight(mUi.lImage->height(), Qt::SmoothTransformation);
                mPixmapCache.insert(image->path(), pixmap);
                addState(it.key(), image->path());
            }
        }
    }

    connect(mUi.statusTreeWidget, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(onItemClicked(QTreeWidgetItem *, int)));
    connect(mUi.statusTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(onItemChanged(QTreeWidgetItem *, int)));

    connect(mUi.stateEdit, SIGNAL(textEdited(const QString&)), this, SLOT(onStateEdited(const QString&)));
    connect(mUi.browseImageButton, SIGNAL(fileSelected(const QString&)), this, SLOT(onImageSelected(const QString&)));
    connect(mUi.addStateButton, SIGNAL(clicked()), this, SLOT(addNewState()));

    show();
}
Esempio n. 12
0
int _tmain(int argc, _TCHAR* argv[]) {
#else
int main(int argc, char **argv) {
#endif

  if(argc != 2 && argc != 3) {
    fprintf(stderr, "Usage: sc <img1>\n");
    return 1;
  }

  int spSize = 5;
  if(argc == 3) {
    sscanf(argv[2], "%d", &spSize);
  }

  ImageFile imgFile (argv[1]);
  if(!imgFile.Load()) {
    fprintf(stderr, "Error loading file: %s\n", argv[1]);
    return 1;
  }

  FasTC::Image<> *img = imgFile.GetImage();

  const int kWidth = img->GetWidth();
  const int kHeight = img->GetHeight();
  const int nPixels = kWidth * kHeight;
  const uint32 pixelBufSz = nPixels * sizeof(FasTC::Pixel);

  FasTC::Pixel *pixels = new FasTC::Pixel[pixelBufSz];
  memcpy(pixels, img->GetPixels(), pixelBufSz);

  uint32 *rawPixels = new uint32[kWidth * kHeight];

  for(int i = 0; i < nPixels; i++) {
    // Pixels are stored as little endian ARGB, so we want ABGR
    pixels[i].Shuffle(0x6C); // 01 10 11 00
    rawPixels[i] = pixels[i].Pack();
  }

  int *labels = new int[nPixels];
  int numLabels;

  SLIC slic;
  slic.PerformSLICO_ForGivenStepSize(
    rawPixels,
	kWidth,
    kHeight,
    labels,
    numLabels,
	spSize, 1.0);

  std::unordered_map<uint32, Region> regions;
  CollectPixels(kWidth, kHeight, pixels, labels, regions);
  std::cout << "Num regions: " << regions.size() << std::endl;

  for(auto &r : regions) {
    r.second.Compress();
    r.second.Reconstruct();
  }

  for(int i = 0; i < nPixels; i++) {
    pixels[i] = regions[labels[i]].GetNextPixel();
    pixels[i].Shuffle(0x6C);
  }

  std::vector<Partition<4, 4> > partitions;
  EnumerateBPTC(partitions);
  std::cout << partitions.size() << " 4x4 BPTC partitions" << std::endl;

  VpTree<Partition<4, 4>, Partition<4, 4>::Distance> vptree;
  vptree.create(partitions);

  // Just to test, find the partition close to half 0 half 1..
  Partition<4, 4> test;
  for(uint32 i = 0; i < 16; i++) {
    if(i < 8) {
      test[i] = 0;
    } else {
      test[i] = 1;
    }
  }

  vector<Partition<4, 4> > closest;
  vptree.search(test, 1, &closest, NULL);
  std::cout << closest[0].GetIndex() << std::endl;

  BPTCC::CompressionSettings settings;
  settings.m_NumSimulatedAnnealingSteps = 0;
  settings.m_ShapeSelectionFn = ChosePresegmentedShape<4, 4>;

  SelectionInfo info(vptree, labels, kWidth, kHeight);
  settings.m_ShapeSelectionUserData = &info;

  uint8 *outBuf = new uint8[kWidth * kHeight];
  FasTC::CompressionJob cj(
     FasTC::eCompressionFormat_BPTC,
     reinterpret_cast<const uint8 *>(pixels),
     outBuf,
     static_cast<uint32>(kWidth),
     static_cast<uint32>(kHeight));

  StopWatch sw;
  sw.Start();
  BPTCC::Compress(cj, settings);
  sw.Stop();
  std::cout << "Compression time: " << sw.TimeInMilliseconds() << "ms" << std::endl;

  CompressedImage ci(kWidth, kHeight, FasTC::eCompressionFormat_BPTC, outBuf);
  FasTC::Image<> outImg(kWidth, kHeight, pixels);

  std::cout << "PSNR: " << outImg.ComputePSNR(&ci) << "db" << std::endl;

  ImageFile outImgFile("out.png", eFileFormat_PNG, outImg);
  outImgFile.Write();

  delete [] labels;
  delete [] rawPixels;
  delete [] pixels;
  return 0;
}
Esempio n. 13
0
int
pjrec_main (int argc, char * const argv[])
{
  Projections projGlobal;
  ImageFile* imGlobal = NULL;
  char* pszFilenameProj = NULL;
  char* pszFilenameImage = NULL;
  std::string sRemark;
  bool bOptVerbose = false;
  bool bOptDebug = 1;
  int iOptZeropad = 1;
  int optTrace = Trace::TRACE_NONE;
  double dOptFilterParam = -1;
  std::string sOptFilterName (SignalFilter::convertFilterIDToName (SignalFilter::FILTER_ABS_BANDLIMIT));
  std::string sOptFilterMethodName (ProcessSignal::convertFilterMethodIDToName (ProcessSignal::FILTER_METHOD_CONVOLUTION));
  std::string sOptFilterGenerationName (ProcessSignal::convertFilterGenerationIDToName (ProcessSignal::FILTER_GENERATION_DIRECT));
  std::string sOptInterpName (Backprojector::convertInterpIDToName (Backprojector::INTERP_LINEAR));
  std::string sOptBackprojectName (Backprojector::convertBackprojectIDToName (Backprojector::BPROJ_IDIFF));
  int iOptPreinterpolationFactor = 1;
  int nx, ny;
  char *endptr;
#ifdef HAVE_MPI
  ImageFile* imLocal;
  int mpi_nview, mpi_ndet;
  double mpi_detinc, mpi_rotinc, mpi_phmlen;
  MPIWorld mpiWorld (argc, argv);
#endif

  Timer timerProgram;

#ifdef HAVE_MPI
  if (mpiWorld.getRank() == 0) {
#endif
    while (1) {
      int c = getopt_long(argc, argv, "", my_options, NULL);
      char *endptr = NULL;

      if (c == -1)
        break;

      switch (c)
        {
        case O_INTERP:
          sOptInterpName = optarg;
          break;
        case O_PREINTERPOLATION_FACTOR:
          iOptPreinterpolationFactor = strtol(optarg, &endptr, 10);
          if (endptr != optarg + strlen(optarg)) {
            pjrec_usage(argv[0]);
            return(1);
          }
          break;
        case O_FILTER:
          sOptFilterName = optarg;
          break;
        case O_FILTER_METHOD:
          sOptFilterMethodName = optarg;
          break;
        case O_FILTER_GENERATION:
          sOptFilterGenerationName = optarg;
          break;
        case O_FILTER_PARAM:
          dOptFilterParam = strtod(optarg, &endptr);
          if (endptr != optarg + strlen(optarg)) {
            pjrec_usage(argv[0]);
            return(1);
          }
          break;
        case O_ZEROPAD:
          iOptZeropad = strtol(optarg, &endptr, 10);
          if (endptr != optarg + strlen(optarg)) {
            pjrec_usage(argv[0]);
            return(1);
          }
          break;
        case O_BACKPROJ:
          sOptBackprojectName = optarg;
          break;
        case O_VERBOSE:
          bOptVerbose = true;
          break;
        case O_DEBUG:
          bOptDebug = true;
          break;
        case O_TRACE:
          if ((optTrace = Trace::convertTraceNameToID(optarg)) == Trace::TRACE_INVALID) {
            pjrec_usage(argv[0]);
            return (1);
          }
          break;
        case O_VERSION:
#ifdef VERSION
          std::cout <<  "Version " <<  VERSION << std::endl << g_szIdStr << std::endl;
#else
          std::cout << "Unknown version number" << std::endl;
#endif
          return (0);
        case O_HELP:
        case '?':
          pjrec_usage(argv[0]);
          return (0);
        default:
          pjrec_usage(argv[0]);
          return (1);
        }
    }

    if (optind + 4 != argc) {
      pjrec_usage(argv[0]);
      return (1);
    }

    pszFilenameProj = argv[optind];

    pszFilenameImage = argv[optind + 1];

    nx = strtol(argv[optind + 2], &endptr, 10);
    ny = strtol(argv[optind + 3], &endptr, 10);

    std::ostringstream filterDesc;
    if (dOptFilterParam >= 0)
      filterDesc << sOptFilterName << ": alpha=" << dOptFilterParam;
    else
      filterDesc << sOptFilterName;

    std::ostringstream label;
    label << "pjrec: " << nx << "x" << ny << ", " << filterDesc.str() << ", " << sOptInterpName << ", preinterpolationFactor=" << iOptPreinterpolationFactor << ", " << sOptBackprojectName;
    sRemark = label.str();

    if (bOptVerbose)
      std::cout << "SRemark: " << sRemark << std::endl;
#ifdef HAVE_MPI
  }
#endif

#ifdef HAVE_MPI
  if (mpiWorld.getRank() == 0) {
    projGlobal.read (pszFilenameProj);
    if (bOptVerbose) {
      ostringstream os;
      projGlobal.printScanInfo (os);
      std::cout << os.str();
    }

    mpi_ndet = projGlobal.nDet();
    mpi_nview = projGlobal.nView();
    mpi_detinc = projGlobal.detInc();
    mpi_phmlen = projGlobal.phmLen();
    mpi_rotinc = projGlobal.rotInc();
  }

  TimerCollectiveMPI timerBcast (mpiWorld.getComm());
  mpiWorld.BcastString (sOptBackprojectName);
  mpiWorld.BcastString (sOptFilterName);
  mpiWorld.BcastString (sOptFilterMethodName);
  mpiWorld.BcastString (sOptInterpName);
  mpiWorld.getComm().Bcast (&bOptVerbose, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&bOptDebug, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&optTrace, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&dOptFilterParam, 1, MPI::DOUBLE, 0);
  mpiWorld.getComm().Bcast (&iOptZeropad, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&iOptPreinterpolationFactor, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&mpi_ndet, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&mpi_nview, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&mpi_detinc, 1, MPI::DOUBLE, 0);
  mpiWorld.getComm().Bcast (&mpi_phmlen, 1, MPI::DOUBLE, 0);
  mpiWorld.getComm().Bcast (&mpi_rotinc, 1, MPI::DOUBLE, 0);
  mpiWorld.getComm().Bcast (&nx, 1, MPI::INT, 0);
  mpiWorld.getComm().Bcast (&ny, 1, MPI::INT, 0);
  if (bOptVerbose)
      timerBcast.timerEndAndReport ("Time to broadcast variables");

  mpiWorld.setTotalWorkUnits (mpi_nview);

  Projections projLocal (mpiWorld.getMyLocalWorkUnits(), mpi_ndet);
  projLocal.setDetInc (mpi_detinc);
  projLocal.setPhmLen (mpi_phmlen);
  projLocal.setRotInc (mpi_rotinc);

  TimerCollectiveMPI timerScatter (mpiWorld.getComm());
  ScatterProjectionsMPI (mpiWorld, projGlobal, projLocal, bOptDebug);
  if (bOptVerbose)
      timerScatter.timerEndAndReport ("Time to scatter projections");

  if (mpiWorld.getRank() == 0) {
    imGlobal = new ImageFile (nx, ny);
  }

  imLocal = new ImageFile (nx, ny);
#else

  if (! projGlobal.read (pszFilenameProj)) {
    fprintf(stderr, "Unable to read projectfile file %s\n", pszFilenameProj);
    exit(1);
  }

  if (bOptVerbose) {
    std::ostringstream os;
    projGlobal.printScanInfo(os);
    std::cout << os.str();
  }

  imGlobal = new ImageFile (nx, ny);
#endif

#ifdef HAVE_MPI
  TimerCollectiveMPI timerReconstruct (mpiWorld.getComm());

  Reconstructor reconstruct (projLocal, *imLocal, sOptFilterName.c_str(), dOptFilterParam, sOptFilterMethodName.c_str(), iOptZeropad, sOptFilterGenerationName.c_str(), sOptInterpName.c_str(), iOptPreinterpolationFactor, sOptBackprojectName.c_str(), optTrace);
  if (reconstruct.fail()) {
    std::cout << reconstruct.failMessage();
    return (1);
  }
  reconstruct.reconstructAllViews();

  if (bOptVerbose)
      timerReconstruct.timerEndAndReport ("Time to reconstruct");

  TimerCollectiveMPI timerReduce (mpiWorld.getComm());
  ReduceImageMPI (mpiWorld, imLocal, imGlobal);
  if (bOptVerbose)
      timerReduce.timerEndAndReport ("Time to reduce image");
#else
  Reconstructor reconstruct (projGlobal, *imGlobal, sOptFilterName.c_str(), dOptFilterParam, sOptFilterMethodName.c_str(), iOptZeropad, sOptFilterGenerationName.c_str(), sOptInterpName.c_str(), iOptPreinterpolationFactor, sOptBackprojectName.c_str(), optTrace);
  if (reconstruct.fail()) {
    std::cout << reconstruct.failMessage();
    return (1);
  }
  reconstruct.reconstructAllViews();
#endif

#ifdef HAVE_MPI
  if (mpiWorld.getRank() == 0)
#endif
    {
      double dCalcTime = timerProgram.timerEnd();
      imGlobal->labelAdd (projGlobal.getLabel());
      imGlobal->labelAdd (Array2dFileLabel::L_HISTORY, sRemark.c_str(), dCalcTime);
      imGlobal->fileWrite (pszFilenameImage);
      if (bOptVerbose)
        std::cout << "Run time: " << dCalcTime << " seconds" << std::endl;
    }
#ifdef HAVE_MPI
  MPI::Finalize();
#endif

  return (0);
}
Esempio n. 14
0
int main(int argc, char **argv) {

  int fileArg = 1;
  if(fileArg == argc) {
    PrintUsage();
    exit(1);
  }

  char decompressedOutput[256]; decompressedOutput[0] = '\0';
  bool bNoDecompress = false;
  int numJobs = 0;
  int quality = 50;
  int numThreads = 1;
  int numCompressions = 1;
  bool bUseSIMD = false;
  bool bSaveLog = false;
  bool bUseAtomics = false;
  bool bUsePVRTexLib = false;
  bool bUseNVTT = false;
  bool bVerbose = false;
  FasTC::ECompressionFormat format = FasTC::eCompressionFormat_BPTC;

  bool knowArg = false;
  do {
    knowArg = false;

    if(strcmp(argv[fileArg], "-n") == 0) {
      fileArg++;

      if(fileArg == argc || (numCompressions = atoi(argv[fileArg])) < 0) {
        PrintUsage();
        exit(1);
      }

      fileArg++;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-f") == 0) {
      fileArg++;

      if(fileArg == argc) {
        PrintUsage();
        exit(1);
      } else {
        if(!strcmp(argv[fileArg], "PVRTC")) {
          format = FasTC::eCompressionFormat_PVRTC4;
        } else if(!strcmp(argv[fileArg], "PVRTCLib")) {
          format = FasTC::eCompressionFormat_PVRTC4;
          bUsePVRTexLib = true;
        } else if(!strcmp(argv[fileArg], "BPTCLib")) {
          format = FasTC::eCompressionFormat_BPTC;
          bUseNVTT = true;
        } else if(!strcmp(argv[fileArg], "ETC1")) {
          format = FasTC::eCompressionFormat_ETC1;
        } else if(!strcmp(argv[fileArg], "DXT1")) {
          format = FasTC::eCompressionFormat_DXT1;
        } else if(!strcmp(argv[fileArg], "DXT5")) {
          format = FasTC::eCompressionFormat_DXT5;
        }
      }

      fileArg++;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-d") == 0) {
      fileArg++;
      
      if(fileArg == argc) {
        PrintUsage();
        exit(1);
      } else {
        size_t sz = 255;
        sz = ::std::min(sz, static_cast<size_t>(strlen(argv[fileArg])));
        memcpy(decompressedOutput, argv[fileArg], sz + 1);
      }

      fileArg++;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-nd") == 0) {
      fileArg++;
      bNoDecompress = true;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-l") == 0) {
      fileArg++;
      bSaveLog = true;
      knowArg = true;
      continue;
    }
    
    if(strcmp(argv[fileArg], "-v") == 0) {
      fileArg++;
      bVerbose = true;
      knowArg = true;
      continue;
    }
    
    if(strcmp(argv[fileArg], "-simd") == 0) {
      fileArg++;
      bUseSIMD = true;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-t") == 0) {
      fileArg++;
      
      if(fileArg == argc || (numThreads = atoi(argv[fileArg])) < 1) {
        PrintUsage();
        exit(1);
      }

      fileArg++;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-q") == 0) {
      fileArg++;
      
      if(fileArg == argc || (quality = atoi(argv[fileArg])) < 0) {
        PrintUsage();
        exit(1);
      }

      fileArg++;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-j") == 0) {
      fileArg++;
      
      if(fileArg == argc || (numJobs = atoi(argv[fileArg])) < 0) {
        PrintUsage();
        exit(1);
      }

      fileArg++;
      knowArg = true;
      continue;
    }

    if(strcmp(argv[fileArg], "-a") == 0) {
      fileArg++;
      bUseAtomics = true;
      knowArg = true;
      continue;
    }

  } while(knowArg && fileArg < argc);

  if(fileArg == argc) {
    PrintUsage();
    exit(1);
  }

  char basename[256];
  ExtractBasename(argv[fileArg], basename, 256);

  ImageFile file (argv[fileArg]);
  if(!file.Load()) {
    fprintf(stderr, "Error loading file: %s\n", argv[fileArg]);
    return 1;
  }

  FasTC::Image<> img(*file.GetImage());

  if(bVerbose) {
    fprintf(stdout, "Entropy: %.5f\n", img.ComputeEntropy());
    fprintf(stdout, "Mean Local Entropy: %.5f\n", img.ComputeMeanLocalEntropy());
  }

  std::ofstream logFile;
  ThreadSafeStreambuf streamBuf(logFile);
  std::ostream logStream(&streamBuf);
  if(bSaveLog) {
    char logname[256];
    sprintf(logname, "%s.log", basename);
    logFile.open(logname);
  }
  
  SCompressionSettings settings;
  settings.format = format;
  settings.bUseSIMD = bUseSIMD;
  settings.bUseAtomics = bUseAtomics;
  settings.iNumThreads = numThreads;
  settings.iQuality = quality;
  settings.iNumCompressions = numCompressions;
  settings.iJobSize = numJobs;
  settings.bUsePVRTexLib = bUsePVRTexLib;
  settings.bUseNVTT = bUseNVTT;
  if(bSaveLog) {
    settings.logStream = &logStream;
  } else {
    settings.logStream = NULL;
  }

  CompressedImage *ci = CompressImage(&img, settings);
  if(NULL == ci) {
    fprintf(stderr, "Error compressing image!\n");
    return 1;
  }

  double PSNR = img.ComputePSNR(ci);
  if(PSNR > 0.0) {
    fprintf(stdout, "PSNR: %.3f\n", PSNR);
  }
  else {
    fprintf(stderr, "Error computing PSNR\n");
  }

  if(bVerbose) {
    double SSIM = img.ComputeSSIM(ci);
    if(SSIM > 0.0) {
      fprintf(stdout, "SSIM: %.9f\n", SSIM);
    } else {
      fprintf(stderr, "Error computing SSIM\n");
    }
  }

  if(!bNoDecompress) {
    if(decompressedOutput[0] != '\0') {
      memcpy(basename, decompressedOutput, 256);
    } else if(format == FasTC::eCompressionFormat_BPTC) {
      strcat(basename, "-bptc.png");
    } else if(format == FasTC::eCompressionFormat_PVRTC4) {
      strcat(basename, "-pvrtc-4bpp.png");
    } else if(format == FasTC::eCompressionFormat_DXT1) {
      strcat(basename, "-dxt1.png");
    } else if(format == FasTC::eCompressionFormat_ETC1) {
      strcat(basename, "-etc1.png");
    }

    EImageFileFormat fmt = ImageFile::DetectFileFormat(basename);
    ImageFile cImgFile (basename, fmt, *ci);
    cImgFile.Write();
  }

  // Cleanup 
  delete ci;
  if(bSaveLog) {
    logFile.close();
  }
  return 0;
}
Esempio n. 15
0
int main(int argc, char **argv) {
  if(argc < 3 || argc > 5) {
    PrintUsageAndExit();
  }

  bool diff_images = false;
  float diff_multiplier = 1.0;
  int arg = 1;
  if (strncmp(argv[arg], "-d", 2) == 0) {
    diff_images = true;
    arg++;

    if (argc == 5) {
      diff_multiplier = static_cast<float>(atoi(argv[arg]));
      if (diff_multiplier < 0) {
        PrintUsageAndExit();
      }
      arg++;
    }
  }

  ImageFile img1f (argv[arg]);
  if(!img1f.Load()) {
    fprintf(stderr, "Error loading file: %s\n", argv[arg]);
    return 1;
  }
  arg++;

  ImageFile img2f (argv[arg]);
  if(!img2f.Load()) {
    fprintf(stderr, "Error loading file: %s\n", argv[arg]);
    return 1;
  }
  arg++;

  FasTC::Image<> &img1 = *img1f.GetImage();
  FasTC::Image<> &img2 = *img2f.GetImage();

  if (img1.GetWidth() != img2.GetWidth() ||
      img1.GetHeight() != img2.GetHeight()) {
    std::cerr << "Images differ in dimension!" << std::endl;
    return 1;
  }

  if (diff_images) {
    FasTC::Image<> diff = img1.Diff(&img2, diff_multiplier);

    char fname_buf [5 + 16 + 4 + 1]; // "diff-" + hash + ".png" + null
    memset(fname_buf, 0, sizeof(fname_buf));
    strncat(fname_buf, "diff-", 5);
    gen_random(fname_buf + 5, 16);
    strncat(fname_buf + 5 + 16, ".png", 4);

    EImageFileFormat fmt = ImageFile::DetectFileFormat(fname_buf);
    ImageFile cImgFile (fname_buf, fmt, diff);
    cImgFile.Write();
  }

  double PSNR = img1.ComputePSNR(&img2);
  if(PSNR > 0.0) {
    fprintf(stdout, "PSNR: %.3f\n", PSNR);
  }
  else {
    fprintf(stderr, "Error computing PSNR\n");
  }

  double SSIM = img1.ComputeSSIM(&img2);
  if(SSIM > 0.0) {
    fprintf(stdout, "SSIM: %.9f\n", SSIM);
  } else {
    fprintf(stderr, "Error computing MSSIM\n");
  }

  return 0;
}