Пример #1
0
BOOL CSBitmap::FromImage(Magick::Image & image)
{
	if(image.columns() > 0 && image.rows() > 0) {
		m_Column = image.columns();
		m_Row    = image.rows();
		if(NULL != m_pBuffer) {
			free(m_pBuffer);
			m_pBuffer = NULL;
		}

		m_pBuffer = (Pixel *)malloc(3 * m_Column * m_Row);
		if(NULL == m_pBuffer) {
			m_Column = m_Row = 0;
			return FALSE;
		}

		try {
			image.write(0,0,m_Column, m_Row, "RGB", MagickCore::CharPixel, m_pBuffer);
		}
		catch (const Magick::Error & err ) {
			free(m_pBuffer);
			m_Column = m_Row = 0;
			return FALSE; 	
		}

		return TRUE;

	}

	return FALSE;
}
Пример #2
0
void Magick::PixelData::init(Magick::Image &image_,const ::ssize_t x_,
  const ::ssize_t y_,const size_t width_,const size_t height_,
  std::string map_,const StorageType type_)
{
  size_t
    size;

  _data=(void *) NULL;
  _length=0;
  _size=0;
  if ((x_ < 0) || (width_ == 0) || (y_ < 0) || (height_ == 0) ||
      (x_ > image_.columns()) || ((width_ + x_) > image_.columns())
      || (y_ > image_.rows()) || ((height_ + y_) > image_.rows())
      || (map_.length() == 0))
    return;

  switch(type_)
  {
    case CharPixel:
      size=sizeof(unsigned char);
      break;
    case DoublePixel:
      size=sizeof(double);
      break;
    case FloatPixel:
      size=sizeof(float);
      break;
    case IntegerPixel:
    case LongPixel:
      size=sizeof(unsigned int);
      break;
    case QuantumPixel:
      size=sizeof(Quantum);
      break;
    case ShortPixel:
      size=sizeof(unsigned short);
      break;
    default:
      throwExceptionExplicit(OptionError,"Invalid type");
      return;
  }

  _length=width_*height_*map_.length();
  _size=_length*size;
  _data=AcquireMagickMemory(_size);

  GetPPException;
  MagickCore::ExportImagePixels(image_.constImage(),x_,y_,width_,height_,
    map_.c_str(),type_,_data,exceptionInfo);
  if (exceptionInfo->severity != UndefinedException)
    relinquish();
  ThrowPPException(image_.quiet());
}
Пример #3
0
int SingleMaskConvolutionAlgorithm::DoYourJob(Magick::Image& image)
{
  image.modifyImage();
  Magick::Pixels pixelCache(image);
  Magick::PixelPacket* pixels;
  for(int x=0;x<image.columns();x++)
    {
      int rectangleWidth=ConvolutionMask.Width;
      int maskX=x-ConvolutionMask.Width/2;
      if(maskX<0)
        {
          rectangleWidth+=maskX;
          maskX=0;
        }
      if(maskX+rectangleWidth>image.columns())
        rectangleWidth=image.columns()-maskX;

      for(int y=0;y<image.rows();y++)
        {
          int rectangleHeight=ConvolutionMask.Height;
          int maskY=y-ConvolutionMask.Height/2;
          if(maskY<0)
            {
              rectangleHeight+=maskY;
              maskY=0;
            }
          if(maskY+rectangleHeight>image.rows())
            rectangleHeight=image.rows()-maskY;
          
          pixels=pixelCache.get(maskX,maskY,rectangleWidth,rectangleHeight);
          Magick::PixelPacket maskResult;
          maskResult.red=maskResult.green=maskResult.blue=0;

          for(int mx=0;mx<rectangleWidth;mx++)
            for(int my=0;my<rectangleHeight;my++)
              {
                maskResult.red+=ConvolutionMask[mx][my]*pixels[mx+rectangleWidth*my].red;
                maskResult.green+=ConvolutionMask[mx][my]*pixels[mx+rectangleWidth*my].green;
                maskResult.blue+=ConvolutionMask[mx][my]*pixels[mx+rectangleWidth*my].blue;
              }

          maskResult.red/=ConvolutionMask.Weight;
          maskResult.green/=ConvolutionMask.Weight;
          maskResult.blue/=ConvolutionMask.Weight;
          
          OperationPerPixel(pixels,x,y,&maskResult);
        }
    }
  pixelCache.sync();
  return 0;
}
Пример #4
0
  void PipelineStabDetect::init(Magick::Image img) {
    width = img.columns();
    height = img.rows();

    if (!vsFrameInfoInit(&fi, width, height, PF_RGB24)) {
      throw runtime_error("Failed to initialize frame info");
    }
    fi.planes = 1; // I don't understand vs frame info... But later is assert for planes == 1

    if (vsMotionDetectInit(&md, &stabConf->mdConf, &fi) != VS_OK) {
      throw runtime_error("Initialization of Motion Detection failed, please report a BUG");
    }
    vsMotionDetectGetConfig(&stabConf->mdConf, &md);

    *verboseOutput << "Video stabilization settings (pass 1/2):" << endl;
    *verboseOutput << "     shakiness = " << stabConf->mdConf.shakiness << endl;
    *verboseOutput << "      accuracy = " << stabConf->mdConf.accuracy << endl;
    *verboseOutput << "      stepsize = " << stabConf->mdConf.stepSize << endl;
    *verboseOutput << "   mincontrast = " << stabConf->mdConf.contrastThreshold << endl;
    *verboseOutput << "        tripod = " << stabConf->mdConf.virtualTripod << endl;
    *verboseOutput << "          show = " << stabConf->mdConf.show << endl;
    *verboseOutput << "        result = " << stabConf->stabStateFile->fileName() << endl;


    //f = fopen(stabStateFile->fileName().toStdString(), "w");
    f = stabConf->openStabStateFile("w");
    if (vsPrepareFile(&md, f) != VS_OK) {
      throw runtime_error(QString("cannot write to transform file %1").arg(stabConf->stabStateFile->fileName()).toStdString());
    }

    initialized = true;
  }
Пример #5
0
void texture_t::load_2d( const string & file_name )
{
   Magick::Image img;

   img.read(file_name);

   glTexEnvf      (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

   int res_y = img.rows()
      ,res_x = img.columns();

   scoped_array<unsigned char> data(new unsigned char[res_x * res_y * 3]);

   img.write   (0, 0, res_x, res_y, "RGB", CharPixel, data.get());

   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16, res_x, res_y, 0, GL_RGB, GL_UNSIGNED_BYTE
                ,data.get());

   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
Пример #6
0
//----------------------------------------------------------------------------------------------------------------------
// Image Magick Image loading routines
//----------------------------------------------------------------------------------------------------------------------
bool Image::load( const std::string &_fname  ) noexcept
{
  #ifdef IMAGE_DEBUG_ON
  std::cerr<<"loading with ImageMagick"<<std::endl;
  #endif
  Magick::Image image;
  Magick::Blob blob;

  try
  {
    image.read(_fname);
    // need to flip image as OpenGL uses textures starting the other way round.
    image.flip();
    image.write(&blob, "RGBA");
  }
  catch (Magick::Error& Error)
  {
  std::cout << "Error loading texture '" << _fname << "': " << Error.what() << std::endl;
  return false;
  }
  m_width=image.columns();
  m_height=image.rows();
  m_channels=4;
  m_format=GL_RGBA;
  m_data.reset(new unsigned char[ m_width*m_height*m_channels]);
  // simple memcpy of the blob data to our internal data, not worrying about RGB/RGBA
  // here (as OpenGL doesn't really either).
  memcpy(m_data.get(),blob.data(),blob.length());
  return true;
}
Пример #7
0
/////////////////////////////////////////////////////////
// really open the file ! (OS dependent)
//
/////////////////////////////////////////////////////////
bool imageMAGICK :: load(std::string filename, imageStruct&result, gem::Properties&props)
{
  Magick::Image image;
  try {
    ::verbose(2, "reading '%s' with ImageMagick", filename.c_str());
    // Read a file into image object
    try {
      image.read( filename );
    } catch (Magick::Warning e) {
      verbose(1, "magick loading problem: %s", e.what());
    }

    result.xsize=static_cast<GLint>(image.columns());
    result.ysize=static_cast<GLint>(image.rows());
    result.setCsizeByFormat(GL_RGBA);
    result.reallocate();

    result.upsidedown=true;

    try {
      image.write(0,0,result.xsize,result.ysize,
                  "RGBA",
                  Magick::CharPixel,
                  reinterpret_cast<void*>(result.data));
    } catch (Magick::Warning e) {
      verbose(1, "magick decoding problem: %s", e.what());
    }
  }catch( Magick::Exception e )  {
    verbose(1, "magick loading image failed with: %s", e.what());
    return false;
  }
  return true;
}
Пример #8
0
bool CubemapTexture::load() {
    Magick::Image *img;
    Magick::Blob blob;

    glGenTextures(1, &_tex);
    glBindTexture(GL_TEXTURE_CUBE_MAP, _tex);
    for (uint i=0; i < sizeof(types) / sizeof(types[0]); i++) {
        img = new Magick::Image(_fs[i]);
        try {
            img->write(&blob, "RGBA");
        } catch (Magick::Error &err) {
            std::cerr << "Could not load texture " << _fs[i] << ": " << err.what() << std::endl;
            delete (img);
            return false;
        }
        std::cout << "Cubemap texture loaded: " << _fs[i] << std::endl;
        glTexImage2D(types[i], 0, GL_RGB, img->columns(), img->rows(), 0, GL_RGBA, GL_UNSIGNED_BYTE, blob.data());
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
        delete img;
    }
    return true;
}
Пример #9
0
void texture_t::load_cube_map( vector<string> const & files_names )
{
   Magick::Image img;

   for (int i = 0; i < files_names.size(); ++i)
   {
      img.read(files_names[i]);

      int res_x = img.rows()
         ,res_y = img.columns();

      scoped_array<unsigned char> data(new unsigned char[res_x * res_y * 3]);

      if (i == 2 || i == 3)
         img.flip();
      else
         img.flop();

      img.write(0, 0, res_x, res_y, "RGB", CharPixel, data.get());

      glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

      glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16, res_x, res_y, 0, GL_RGB
                   ,GL_UNSIGNED_BYTE, data.get());
   }

   glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
Пример #10
0
bool CubemapTexture::Load()
{
    glGenTextures(1, &m_textureObj);
    glBindTexture(GL_TEXTURE_CUBE_MAP, m_textureObj);

    Magick::Image* pImage = NULL;
    Magick::Blob blob;

    for (unsigned int i = 0 ; i < ARRAY_SIZE_IN_ELEMENTS(types) ; i++) {
        pImage = new Magick::Image(m_fileNames[i]);
        
        try {            
            pImage->write(&blob, "RGBA");
        }
        catch (Magick::Error& Error) {
            cout << "Error loading texture '" << m_fileNames[i] << "': " << Error.what() << endl;
            delete pImage;
            return false;
        }

        glTexImage2D(types[i], 0, GL_RGB, pImage->columns(), pImage->rows(), 0, GL_RGBA, GL_UNSIGNED_BYTE, blob.data());
        
        delete pImage;
    }    
    
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);           
    
    return true;
}
Пример #11
0
  void PipelineStabDetect::onInput(InputImageInfo info, Magick::Image image) {
    try {
      if (!initialized) {
        init(image);
      }
      if (image.rows() != height || image.columns() != width) {
        throw runtime_error(QString("Not uniform image size! %").arg(info.file.fileName()).toStdString());
      }


      Magick::Blob blob;
      // set raw RGBS output format & convert it into a Blob  
      if (image.depth() > 8)
        *err << "Warning: we lost some information by converting to 8bit depth (now " << image.depth() << ")" << endl;
      image.depth(8);
      image.magick("RGB");
      image.write(&blob);

      LocalMotions localmotions;
      VSFrame frame;
      size_t dataLen = blob.length();

      Q_ASSERT(fi.planes == 1);
      Q_ASSERT(dataLen == image.baseColumns() * image.baseRows() * 3);

      if (stabConf->mdConf.show > 0) { // create copy of blob
        frame.data[0] = new uint8_t[dataLen];
        memcpy(frame.data[0], blob.data(), dataLen);
      } else {
        frame.data[0] = (uint8_t*) blob.data();
      }
      frame.linesize[0] = image.baseColumns() * 3;

      if (vsMotionDetection(&md, &localmotions, &frame) != VS_OK) {
        throw runtime_error("motion detection failed");
      } else {
        if (vsWriteToFile(&md, f, &localmotions) != VS_OK) {
          throw runtime_error("cannot write to transform file");
        }
        vs_vector_del(&localmotions);
      }

      if (stabConf->mdConf.show > 0) {
        // if we want to store transformations, we have to create new image...
        Magick::Geometry g(width, height);
        Magick::Blob oblob(frame.data[0], dataLen);

        Magick::Image oimage;
        oimage.read(oblob, g, 8, "RGB");
        delete[] frame.data[0];
        emit input(info, oimage);
      } else {
        emit input(info, image);
      }

    } catch (exception &e) {
      emit error(e.what());
    }
  }
Пример #12
0
  //! Returns remaining image size after removing black edges
  Magick::Geometry
  bbox (const Magick::Image& image) const
  {
    const Magick::Color black ("black");

#define is_black(x,y) (black == image.pixelColor (x, y))

    const unsigned int
      cols = image.columns (),
      rows = image.rows ();

    unsigned int x_min, x_max, y_min, y_max;

    bool found;
    unsigned int x, y;

    found = false;
    y = 0;
    do {
      x = 0;
      do {
        found = !is_black (x, y);
      } while (!found && cols != ++x);
    } while (!found && rows != ++y);
    y_min = y;

    found = false;
    y = rows;
    do {
      x = 0;
      do {
        found = !is_black (x, y-1);
      } while (!found && cols != ++x);
    } while (!found && 0 != --y);
    y_max = y;

    found = false;
    x = 0;
    do {
      y = 0;
      do {
        found = !is_black (x, y);
      } while (!found && rows != ++y);
    } while (!found && cols != ++x);
    x_min = x;

    found = false;
    x = cols;
    do {
      y = 0;
      do {
        found = !is_black (x-1, y);
      } while (!found && rows != ++y);
    } while (!found && 0 != --x);
    x_max = x;

    return Magick::Geometry (x_max - x_min, y_max - y_min, x_min, y_min);
  }
Пример #13
0
Preprocessor::Preprocessor (const Magick::Image& page, const unsigned int& x, const unsigned int& y, const unsigned int& height, const unsigned int& width)
:	clip_(0),
	clipHeight_(height),
	clipWidth_(width),
	statistics_(),
	regions_(0),
	delimiters_(0),
	inlineRegions_(),
	patterns_(0),
	averageCharacterHeight_(0.0),
	averageCharacterWidth_(0.0),
	averageSpaceBetweenCharacters_(0.0)
{
	if ( (height == 0) && (width == 0) )
		throw NessieException ("Preprocessor::Preprocessor() : Constructor has 0 size.");

	if ( width > page.columns() )
		throw NessieException ("Preprocessor::Preprocessor() : The press clip's width cannot be wider than the underlying page's.");

	if ( height > page.rows() )
		throw NessieException ("Preprocessor::Preprocessor() : The press clip's height cannot be higher than the underlying page's.");

	if ( x >= page.rows() || y >= page.columns() )
		throw NessieException ("Preprocessor::Preprocessor() : The press clip's top leftmost pixel falls outside the page.");

	if( (x + height) > page.rows() || (y + width) > page.columns() )
		throw NessieException ("Preprocessor::Preprocessor() : The clip does not fall completely within the underlying page.");

	// Create a view over the input image
	Magick::Pixels imageView(const_cast<Magick::Image&>(page));
	Magick::PixelPacket *pixels = imageView.get(x, y, clipWidth_, clipHeight_);

	// Traverse the view to get the pixel values
	Magick::ColorGray grayLevel;
	for ( unsigned int i = 0; i < clipHeight_; ++i )
	{
		for ( unsigned int j = 0; j < clipWidth_; ++j )
		{
			grayLevel = *pixels++;
			clip_.push_back( static_cast<unsigned char>(round(grayLevel.shade() * 255.0)) );
		}
	}

	statistics_.clipSize(clip_.size());
}
Пример #14
0
int AlgorithmShiftNoise::DoYourJob(Magick::Image& image)
{
    srand(time(NULL));

    image.modifyImage();
    Magick::Pixels pixelCache(image);

    Magick::PixelPacket* pixels=pixelCache.get(0,0,image.columns(), image.rows());

    for (int fromX=0; fromX<image.columns(); fromX++)
        for(int fromY=0; fromY<image.rows(); fromY++)
        {
            int luck=rand()%100;
            if (luck>Percent)
                continue;

            int toX=rand()%image.columns();
            int toY=rand()%image.rows();

            Magick::PixelPacket tmp=pixels[fromX+fromY*image.columns()];
            pixels[fromX+fromY*image.columns()]=pixels[toX+toY*image.columns()];
            pixels[toX+toY*image.columns()]=tmp;
        }

    pixelCache.sync();

    return 0;
}
wxBitmap MagickToBitmap(Magick::Image image, int width, int height)
{
    Magick::Geometry geom(width, height);
    geom.aspect(true);
    image.resize(geom);
    unsigned char* rgb = static_cast<unsigned char*>(malloc(sizeof(char) * 3 * width * height));
    image.write(0, 0, image.columns(), image.rows(), "RGB", Magick::CharPixel, rgb);
    return wxBitmap(wxImage(width, height, rgb));
}
Пример #16
0
void handleReshape(int w, int h) {
	float ratio = 1.0;
	
	if(w < image.columns() || h < image.rows()) {
		const float xratio = w / (image.columns() * 1.0);
		const float yratio = h / (image.rows() * 1.0);
		ratio = xratio < yratio ? xratio : yratio;
		glPixelZoom(ratio, ratio);
	}
	
	const int x = (int)((w - (image.columns() * ratio)) / 2);
	const int y = (int)((h - (image.rows() * ratio)) / 2);
	glViewport(x, y, w - x, h - y);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, w, 0, h);
	glMatrixMode(GL_MODELVIEW);
}
Пример #17
0
int DetailedAlgorithm::DoYourJob(Magick::Image& image)
{
  image.modifyImage();
  Magick::Pixels pixelCache(image);
  for(int x=0;x<image.columns();x++)
    for(int y=0;y<image.rows();y++)
      OperationPerPixel(pixelCache.get(x,y,1,1),x,y);
  pixelCache.sync();
  return 0;
}
Пример #18
0
  void PipelineStabTransform::init(Magick::Image img) {
    width = img.columns();
    height = img.rows();


    if (!vsFrameInfoInit(&fi, width, height, PF_RGB24)) {
      throw runtime_error("Failed to initialize frame format");
    }
    fi.planes = 1; // I don't understand vs frame info... But later is assert for planes == 1

    if (vsTransformDataInit(&td, &stabConf->tsConf, &fi, &fi) != VS_OK) {
      throw runtime_error("initialization of vid.stab transform failed, please report a BUG");
    }
    vsTransformGetConfig(&stabConf->tsConf, &td);

    *verboseOutput << "Video transformation/stabilization settings (pass 2/2):" << endl;
    *verboseOutput << "    input     = " << stabConf->stabStateFile->fileName() << endl;
    *verboseOutput << "    smoothing = " << stabConf->tsConf.smoothing << endl;
    *verboseOutput << "    optalgo   = " <<
      (stabConf->tsConf.camPathAlgo == VSOptimalL1 ? "opt" :
      (stabConf->tsConf.camPathAlgo == VSGaussian ? "gauss" : "avg")) << endl;
    *verboseOutput << "    maxshift  = " << stabConf->tsConf.maxShift << endl;
    *verboseOutput << "    maxangle  = " << stabConf->tsConf.maxAngle << endl;
    *verboseOutput << "    crop      = " << (stabConf->tsConf.crop ? "Black" : "Keep") << endl;
    *verboseOutput << "    relative  = " << (stabConf->tsConf.relative ? "True" : "False") << endl;
    *verboseOutput << "    invert    = " << (stabConf->tsConf.invert ? "True" : "False") << endl;
    *verboseOutput << "    zoom      = " << (stabConf->tsConf.zoom) << endl;
    *verboseOutput << "    optzoom   = " << (
      stabConf->tsConf.optZoom == 1 ? "Static (1)" : (stabConf->tsConf.optZoom == 2 ? "Dynamic (2)" : "Off (0)")) << endl;
    if (stabConf->tsConf.optZoom == 2)
      *verboseOutput << "    zoomspeed = " << stabConf->tsConf.zoomSpeed << endl;
    *verboseOutput << "    interpol  = " << getInterpolationTypeName(stabConf->tsConf.interpolType) << endl;

    //f = fopen(stabStateFile->fileName().toStdString(), "r");
    f = stabConf->openStabStateFile("r");
    VSManyLocalMotions mlms;
    if (vsReadLocalMotionsFile(f, &mlms) == VS_OK) {
      // calculate the actual transforms from the local motions
      if (vsLocalmotions2Transforms(&td, &mlms, &trans) != VS_OK) {
        throw runtime_error("calculating transformations failed");
      }
    } else { // try to read old format
      if (!vsReadOldTransforms(&td, f, &trans)) { /* read input file */
        throw runtime_error(QString("error parsing input file %1").arg(stabConf->stabStateFile->fileName()).toStdString());
      }
    }

    fclose(f);
    f = NULL;

    if (vsPreprocessTransforms(&td, &trans) != VS_OK) {
      throw runtime_error("error while preprocessing transforms");
    }
    initialized = true;
  }
Пример #19
0
int SimpleAlgorithm::DoYourJob(Magick::Image& image)
{
  //"Note: The main benefit of the 'Pixels' class is that it provides efficient access to raw image pixels"
  image.modifyImage();
  Magick::Pixels pixelCache(image);
  for(int x=0;x<image.columns();x++)
    for(int y=0;y<image.rows();y++)
      OperationPerPixel(pixelCache.get(x,y,1,1));
  pixelCache.sync();
  return 0;
}
Пример #20
0
int AlgorithmHough::DoYourJob(Magick::Image& image)
{
    BW(image);
    std::cout<<"BW"<<std::endl;
    Accu(image);
    std::cout<<"Ac"<<std::endl;
    Blur(Accu.Accumulator);
    std::cout<<"Bl"<<std::endl;

    HoughResult max=Accu.Maximum();
    std::cout<<"Max"<<std::endl;

    Magick::Image result(image.size(), Magick::Color("white"));

    result.modifyImage();
    Magick::Pixels pixelCache(result);
    Magick::PixelPacket* pixels=pixelCache.set(0,0,image.columns(),image.rows());
    for(int x=0; x<image.columns(); x++)
        for(int y=0; y<image.rows(); y++)
        {
            double fi_f=max.Fi-90;
            double r_=double(x)*cos(fi_f*3.14/180.0)+double(y)*sin(fi_f*3.14/180.0);

            int pixelIndex=x+y*image.columns();

            if(r_<0) //jak wyżej
                continue;

            if(round(r_)==max.R)
                pixels[pixelIndex].red=pixels[pixelIndex].blue=pixels[pixelIndex].green=0;
            else
                pixels[pixelIndex].red=pixels[pixelIndex].blue=pixels[pixelIndex].green=(1<<QuantumDepth)-1;
        }

    pixelCache.sync();

    image=result;

    std::cout<<"R: "<<max.R<<" FI: "<<max.Fi<<" Value: "<<max.Value<<std::endl;
    return 0;
}
Пример #21
0
void drawScene() {
	// get the axises
	Vector3d ux = (camera->v % camera->vup).normalize();
	Vector3d uy = camera->vup.normalize();
	Vector3d uz = -camera->v.normalize();
	Vector3d origin = camera->vp - (camera->focal * uz);
	
	// loop over every pixel
	for(int row = 0; row < image.rows(); row++) {
		for(int col = 0; col < image.columns(); col++) {
			Vector3d p = origin + camera->p(row, col, ux, uy);
			Vector3d ur = perspective ? (p - camera->vp).normalize() : -uz;

			double distance, min = -1;
			Sphere* sphere;
			
			
			// loop over the spheres
			for(int i = 0; i < nspheres; i++) {
				distance = spheres[i]->intersection(p, ur);
				if(distance > 0 && (min < 0 || distance < min)) {
					min = distance;
					sphere = spheres[i];
				}
			}

			Color color(0, 0, 0);
			  
			// if a sphere is hit loop over the lights
			if(min > 0) {
				Color ambient = sphere->material.color * sphere->material.ambient;
				Color diffuse(0, 0, 0);
				Color specular(0, 0, 0);
				Vector3d hit = p + (ur * min);				
				for(int i = 0; i < 3; i++) {
					diffuse = diffuse + lights[i]->diffuse(ur, hit, *sphere);
					specular = specular + lights[i]->specular(ur, hit, *sphere);
				}
				
        Color reflection = Light::reflection(*sphere, ur, hit, spheres, nspheres, lights, nlights, 0);
				
				// total up the color
				color = ambient + diffuse + specular + reflection;
			}
			
			image.pixelColor(col, row, color.ColorRGB());
		}
	}
	
	image.flip();
	imageToPixmap();
}
Пример #22
0
void VoxelGrid::
paintHeightMap(const GridDescription & gridDesc,
	const HeightMap & instruction)
{
	Rect3i yeeRect = instruction.yeeRect();
	Vector3i u1 = instruction.rowDirection();
	Vector3i u2 = -instruction.columnDirection();
	Vector3i u3 = instruction.upDirection();
	
	int nUp = abs(dot(u3, yeeRect.p2-yeeRect.p1)) + 1;
	
	Mat3i matrixImgToGrid(Mat3i::withColumns(u1,u2,u3));
	
	// this will select the correct corner of the fill rect regardless of the
	// direction of the image unit vectors.  This point corresponds to the
	// origin of the image (top-left pixel of the .bmp or .*).
	Vector3i fillOrigin = clip(yeeRect,
		Vector3i(-100000*u1 + -100000*u2 + -100000*u3) );
	
	// now the image!
	Magick::Image heightMap;
	try {
		heightMap.read(instruction.imageFileName());
		FillStyle style = instruction.fillStyle();
		Paint* paint = Paint::paint(instruction.material());
		
		// iterate over rows and columns of the image; extrude into grid
		for (unsigned int row = 0; row < heightMap.rows(); row++)
		for (unsigned int col = 0; col < heightMap.columns(); col++)
		{
			Magick::ColorGray color = heightMap.pixelColor(col, row);
			int height = int(double(nUp)*color.shade());
			
			Vector3i p = fillOrigin + matrixImgToGrid*Vector3i(col, row, 0);
			for (int up = 0; up < height; up++)
			{
				Vector3i pGrid = p + u3*up;
				if (style == kPECStyle)
					paintPEC(paint, pGrid[0], pGrid[1], pGrid[2]);
				else if (style == kPMCStyle)
					paintPMC(paint, pGrid[0], pGrid[1], pGrid[2]);
                else
                    paintYeeCell(paint, pGrid[0], pGrid[1], pGrid[2]);
			}
		}
	} catch (Magick::Exception & magExc) {
		cerr << "Error reading HeightMap.  Maybe a file type issue?\n";
		cerr << "Caught ImageMagick exception " << magExc.what() << endl;
		LOG << "Exception logged.  Exiting.\n";
		exit(1);
	}
}
Пример #23
0
  void AdjustLuminance::onInput(InputImageInfo info, Magick::Image img) {
    std::vector<std::pair < Magick::Color, size_t>> histogram;
    Magick::colorHistogram(&histogram, img);
    Magick::Image original = img;
    /* gamma correction rules:
     * http://www.imagemagick.org/Usage/transform/#evaluate_pow
     * 
     *  updatedColor = color ^ (1 / gamma)
     *  gamma = 1 / log(color, updatedColor)
     *  gamma = 1 / (log(updatedColor) / log(color))
     * 
     * We can't compute gamma just from current and target luminance, 
     * but we can estimate it. 
     * 
     * We can compute expected luminance after gamma 
     * correction from image histogram, it is relatively fast. 
     * So we iterate gamma estimation ten times. Results are relatively good.
     */
    double gamma = 1.0;
    double targetLuminance = info.luminanceChange + info.luminance;
    double expectedLuminance = info.luminance;

    for (int iteration = 0; iteration < 10; iteration++) {

      gamma *= 1 / (
        std::log(Magick::Color::scaleQuantumToDouble(targetLuminance)) /
        std::log(Magick::Color::scaleQuantumToDouble(expectedLuminance)));

      expectedLuminance = ComputeLuminance::computeLuminance(histogram, gamma);

      *verboseOutput << QString("%1 iteration %2 changing gamma to %3 (expected luminance: %4, target %5, abs(diff) %6)")
        .arg(info.file.filePath())
        .arg(iteration)
        .arg(gamma)
        .arg(expectedLuminance)
        .arg(targetLuminance)
        .arg(std::abs(expectedLuminance - targetLuminance))
        << endl;
    }

    img.gamma(gamma);
    if (debugView) {
      original.transform(
        Magick::Geometry(original.columns(), original.rows()),
        Magick::Geometry(original.columns() / 2, original.rows())
        );
      img.composite(original, 0, 0, Magick::DissolveCompositeOp);
    }
    //img.brightnessContrast(brighnessChange, /* contrast */0.0);
    emit input(info, img);
  }
Пример #24
0
ItemSequence_t
WidthFunction::evaluate(
  const ExternalFunction::Arguments_t& aArgs,
  const StaticContext*                          aSctxCtx,
  const DynamicContext*                         aDynCtx) const
{

  Magick::Image lImage;
  ImageFunction::getOneImageArg(aDynCtx, aArgs, 0, lImage);
  unsigned int lResult = (unsigned int)lImage.columns();
  return ItemSequence_t(new SingletonItemSequence(
      theModule->getItemFactory()->createUnsignedInt(lResult)));

}
Пример #25
0
void ObjectData::loadTexture(string objID, string textureFileName)
{

    list<singleObject>::iterator iter;
    for (iter = listOfObjects.begin() ; iter != listOfObjects.end(); iter++)
        {
            if ( iter->id == objID )
            {
                // load texture image
                Magick::InitializeMagick("");
                Magick::Image image;
                Magick::Blob m_blob;
                try 
                    { 
                     // Read a file into image object 
                     if ( textureFileName != "")
                        {
                         image.read( textureFileName );
                         image.flip();
                         image.write(&m_blob, "RGBA");
                        }
                     else
                        {
                         throw std::invalid_argument("No texture file found");
                        }

                    } 
                catch(exception& tmp) 
                    { 
                     cout << "Error while reading in texture image, texture file not found"  << endl; 
                    } 

                int imageWidth = image.columns();
                int imageHeight = image.rows();


                // setup texture
                glGenTextures(1, &(iter->bTexture)); 
                glActiveTexture(GL_TEXTURE0);
                glBindTexture(GL_TEXTURE_2D,  iter->bTexture);

                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_blob.data());

                glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                }
        }

}
Пример #26
0
// use the Magick++ library to load an image with a given file name into
// an OpenGL rectangle texture
bool InitializeTexture(MyTexture *texture, const string &imageFileName)
{
    Magick::Image myImage;

    // try to read the provided image file
    try {
        myImage.read(imageFileName);
    }
    catch (Magick::Error &error) {
        cout << "Magick++ failed to read image " << imageFileName << endl;
        cout << "ERROR: " << error.what() << endl;
        return false;
    }

    // store the image width and height into the texture structure
    texture->width = myImage.columns();
    texture->height = myImage.rows();

    // create a Magick++ pixel cache from the image for direct access to data
    Magick::Pixels pixelCache(myImage);
    Magick::PixelPacket *pixels;
    pixels = pixelCache.get(0, 0, texture->width, texture->height);

    // determine the number of stored bytes per pixel channel in the cache
    GLenum channelDataType;
    switch (sizeof(Magick::Quantum)) {
        case 4:     channelDataType = GL_UNSIGNED_INT;      break;
        case 2:     channelDataType = GL_UNSIGNED_SHORT;    break;
        default:    channelDataType = GL_UNSIGNED_BYTE;
    }

    // create a texture name to associate our image data with
    if (!texture->textureName)
        glGenTextures(1, &texture->textureName);

    // bind the texture as a "rectangle" to access using image pixel coordinates
    glBindTexture(GL_TEXTURE_RECTANGLE, texture->textureName);

    // send image pixel data to OpenGL texture memory
    glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB, texture->width, texture->height,
                 0, GL_BGRA, channelDataType, pixels);

    // unbind this texture
    glBindTexture(GL_TEXTURE_RECTANGLE, 0);

    return !CheckGLErrors();
}
Пример #27
0
CTexture::CTexture(const std::string& filename)
   : texture(GL_TEXTURE_2D)
{
   Log::msg("loading texture from ", filename);
   Magick::Image img;
   Magick::Blob blob;
   img.read(std::string("aersy-res/") + filename);
   mHasAlpha = !img.isOpaque();
   img.write(&blob, mHasAlpha ? "RGBA" : "RGB");
   bind();
   const GLenum format = mHasAlpha ? GL_RGBA : GL_RGB;
   glTexImage2D(GL_TEXTURE_2D, 0, format, img.columns(), img.rows(), 0, format, GL_UNSIGNED_BYTE, blob.data());
   glGenerateMipmap(_target);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
   unbind();
}
Пример #28
0
bool Texture::Load(){
	try{
		mimage.read(mfileName);
		mimage.write(&mblob, "RGBA");
		}
	catch (Magick::Error& Error){
		cout<<"Didn't load texture"<<mfileName<<Error.what()<<endl;
		return false;
		}
	glGenTextures(1, &mtextureObj);
	glBindTexture(mtextureTarget, mtextureObj);
	glTexImage2D(mtextureTarget, 0, GL_RGBA, mimage.columns(), mimage.rows(), 0, GL_RGBA, GL_UNSIGNED_BYTE, mblob.data());
	glTexParameterf(mtextureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(mtextureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glBindTexture(mtextureTarget, 0);
	return true;
	}
Пример #29
0
/** getTiles
  *
  * Given a map gets the tiles for the map
  */
int HandlerUtils::GetTiles(const Map& map, Magick::Image& tileset, std::vector<Magick::Image>& tiles)
{
    int numTilesX = tileset.columns() / map.GetTileWidth();
    int numTilesY = tileset.rows() / map.GetTileHeight();
    tiles.reserve(numTilesX * numTilesY);
    for (int i = 0; i < numTilesY; i++)
    {
        for (int j = 0; j < numTilesX; j++)
        {
            Magick::Geometry dim(map.GetTileWidth(), map.GetTileHeight(), j * map.GetTileWidth(), i * map.GetTileHeight());
            int index = i * numTilesX + j;
            tiles[index] = tileset;
            tiles[index].crop(dim);
        }
    }

    return 0;
}
/*----------------------------------------------------------------------------
 Reads image data from a file into the raw data with dimensions
----------------------------------------------------------------------------*/
void read_img( string filename, Magick::Blob &blob, int &width, int &height )
{
    Magick::Image *magick;  /* ImageMagick object */

    /* load the file into an ImageMagick object */
    magick = new Magick::Image( filename.c_str() );

    /* get image dimensions from ImageMagick */
    width = magick->columns();
    height = magick->rows();

    /* convert image to grayscale, 8-bit depth and get raw data */
    magick->modifyImage();
    magick->write( &blob, "GRAY", 8 );

    /* enough magick for now */
    delete magick;
}