Ejemplo n.º 1
0
HRESULT OpenList_Add (
   HOPENLIST * phlst,
   LPCTSTR     pszPath,
   DWORD       fdwOpen,
   LPARAM      lParam)
{
   HRESULT hr = S_OK;

   hr = PtrList_CreateIfNot(phlst, 16, 16);
   if (FAILED(hr))
      return hr;

   int cbPath = StrAllocBytes(pszPath);
   int cbItem = NUMBYTES(OPENLIST_FILE) + cbPath;

   POPENLIST_FILE polf = PtrList_AllocItem(*phlst, cbItem);
   if ( ! polf)
      return E_OUTOFMEMORY;

   ZeroStruct(polf);
   CopyMemory(polf->szPathName, pszPath, cbPath);
   polf->fdwOpen = fdwOpen & 0xFFFF0000;
   polf->lParam  = lParam;

   hr = PtrList_AppendItem(*phlst, polf);
   return hr;
}
Ejemplo n.º 2
0
void bprint_Initialize(BPRINT_BUFFER & bp)
{
   if (bp.cchMax <= 0)
      bp.cchMax = 0x0FFFF;
   if ( ! bp.psz)
      bp.psz = (LPTSTR) malloc((bp.cchMax+1) * NUMBYTES(bp.psz[0]));
   bp.cch = 0;
   bp.CodePage = CP_ACP;
}
Ejemplo n.º 3
0
HRESULT VegasFSRender::writeData(ISfProgress* progress) {
  BOOL useAudio = (m_pIAudioStream &&
                   m_pTemplate->pAudioTemplate &&
                   m_pTemplate->pAudioTemplate->cNumAStreams);
  BOOL useVideo = (m_pIVideoStream &&
                   m_pTemplate->pVideoTemplate &&
                   m_pTemplate->pVideoTemplate->cNumVStreams);

  if (!useVideo)
    return SF_E_NOVIDEO;

  HWND activewnd = GetForegroundWindow();
  DWORD threadid = GetWindowThreadProcessId(activewnd, NULL);
  AttachThreadInput(GetCurrentThreadId(), threadid, TRUE);

  ZeroMemory(&FfpHeader, NUMBYTES(FfpHeader));

  LPTSTR pszFileName;
#ifdef UNICODE
  pszFileName = m_szFileName;
#else
  TCHAR szFileName[MAX_PATH];
  SfMBFromWC(szFileName, m_szFileName, MAX_PATH);
  pszFileName = szFileName;
#endif
  HRESULT hr = S_OK;

  hr = m_pIVideoStream->GetFrameCount(&FfpHeader.Video.cfTotal);
  hr = m_pIVideoStream->GetFrameRate(&FfpHeader.Video.dFPS);
  FfpHeader.Video.ntLength = SfVideo_FramesToTime(
      FfpHeader.Video.cfTotal, FfpHeader.Video.dFPS);
  FfpHeader.Video.bih = *m_pTemplate->pVideoTemplate->pbihCodec;
  FfpHeader.Video.cbFrameSize = FSDibImageBytes(&FfpHeader.Video.bih);
  if (useAudio) {
    hr = m_pIAudioStream->GetSampleCount(&FfpHeader.Audio.ccTotal);
    FfpHeader.Audio.wfx = m_pTemplate->pAudioTemplate->wfx;
    hr = m_pIAudioStream->GetStreamLength(&FfpHeader.Audio.ntLength);
    FfpHeader.Audio.ntLength = SfAudio_CellsToTime(FfpHeader.Audio.ccTotal,
        FfpHeader.Audio.wfx.nSamplesPerSec);
  }

  Init(!!useAudio, FfpHeader.Audio.wfx.nSamplesPerSec,
      FfpHeader.Audio.wfx.wBitsPerSample, FfpHeader.Audio.wfx.nChannels,
      (DWORD)FfpHeader.Video.cfTotal, FfpHeader.Video.dFPS,
      FfpHeader.Video.bih.biWidth, FfpHeader.Video.bih.biHeight, activewnd, pszFileName);
  hr = S_OK;
  if (!Run())
    hr = SF_E_CANCEL;

  EnableWindow(activewnd, TRUE);
  SetForegroundWindow(activewnd);
  AttachThreadInput(GetCurrentThreadId(), threadid, FALSE);
  return hr;
}
Ejemplo n.º 4
0
Py::Object
_image_module::frombuffer(const Py::Tuple& args) {
  _VERBOSE("_image_module::frombuffer");

  args.verify_length(4);

  PyObject *bufin = new_reference_to(args[0]);
  int x = Py::Int(args[1]);
  int y = Py::Int(args[2]);
  int isoutput = Py::Int(args[3]);

  if (PyObject_CheckReadBuffer(bufin) != 1)
    throw Py::ValueError("First argument must be a buffer.");

  Image* imo = new Image;

  imo->rowsIn = y;
  imo->colsIn = x;
  Py_ssize_t NUMBYTES(imo->colsIn * imo->rowsIn * imo->BPP);

  Py_ssize_t buflen;
  const agg::int8u *rawbuf;
  if (PyObject_AsReadBuffer(bufin, reinterpret_cast<const void**>(&rawbuf), &buflen) != 0)
    throw Py::ValueError("Cannot get buffer from object.");

  // Check buffer is required size.
  if (buflen != NUMBYTES)
    throw Py::ValueError("Buffer length must be width * height * 4.");

  // Copy from input buffer to new buffer for agg.
  agg::int8u* buffer = new agg::int8u[NUMBYTES];
  if (buffer==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("_image_module::frombuffer could not allocate memory");
  memmove(buffer, rawbuf, NUMBYTES);

  if (isoutput) {
    // make the output buffer point to the input buffer

    imo->rowsOut  = imo->rowsIn;
    imo->colsOut  = imo->colsIn;

    imo->rbufOut = new agg::rendering_buffer;
    imo->bufferOut = buffer;
    imo->rbufOut->attach(imo->bufferOut, imo->colsOut, imo->rowsOut, imo->colsOut * imo->BPP);

  }
  else {
    imo->bufferIn = buffer;
    imo->rbufIn = new agg::rendering_buffer;
    imo->rbufIn->attach(buffer, imo->colsIn, imo->rowsIn, imo->colsIn*imo->BPP);
  }

  return Py::asObject(imo);
}
Ejemplo n.º 5
0
static int __cdecl bprint(BPRINT_BUFFER & bp, LPCTSTR pszNew)
{
   int cchNew = lstrlen(pszNew);

   LPTSTR psz = bp.psz + bp.cch;
   if (bp.cch + cchNew > bp.cchMax)
   {
      DebugBreak();
      cchNew = (bp.cchMax - bp.cch);
   }

   CopyMemory(psz, pszNew, cchNew * NUMBYTES(pszNew[0]));

   if (cchNew > 0)
      bp.cch += cchNew;

   return cchNew;
}
Ejemplo n.º 6
0
HRESULT App_CookArgList (
   HCMDLIST * phlst,
   LPCTSTR    aArgs[],
   UINT       ixFirst,  // first arg to execute
   UINT       cArgs)    // count of args to execute
{
   HRESULT    hr = S_FALSE; // there were no args...
   TCHAR      szTempArg[64]; // temp if we need to copy and arg

   HCMDLIST   hlst;

   *phlst = NULL;
   hr = Vector_Create(&hlst, cArgs, -1);
   if (FAILED(hr))
      return hr;

   // look at args, parsing switches and building up the array of filename pointers
   //
   UINT ixLast = (ixFirst + cArgs);
   for (UINT ii = ixFirst; ii < ixLast; ++ii)
      {
      LPCTSTR pszArg = aArgs[ii];
      if ( ! pszArg)
         break;

      // assume a file open command.
      //
      hr = S_OK;
      CMDSWITCH cmd = {APP_CMD_PATH, 0, 1, NULL};

      // if the first character of the arg is an '@', what follows should be a command file.
      //
      if (pszArg[0] == '@')
         {
         // command will be an argfile command
         //
         cmd.idCmd     = APP_CMD_ARGFILE;
         cmd.cParams   = 1;    // on arg needed
         cmd.pszParams = NULL; // no default

         // if next character is not a 0, it must be the filename
         // otherwise, suck up the next token and use it as the filename.
         //
         pszArg = StrCharNext (pszArg); // skip '@'
         if (0 != pszArg[0])
            {
            cmd.pszParams = pszArg;
            }
         else if (ii+1 < ixLast) // next pszArg belongs to us..
            {
            LPCTSTR pszT = aArgs[ii+1];
            if ('-' != pszT[0] && '/' != pszT[0])
               {
               cmd.pszParams = pszT;
               ++ii;  // advance the loop counter.
               }
            }
         }
      else if ('-' == pszArg[0] || '/' == pszArg[0])
         {
         pszArg = StrCharNext (pszArg);
         if (0 == pszArg[0])
            {
            hr = E_INVALIDARG;
            goto bail;
            }

         // look for a ':' in the arg, and
         //
         LPCTSTR psz = StrCharNext(pszArg);
         LPCTSTR pszParam = NULL;
         while (0 != psz[0])
            {
            // if the arg contains a colon, set pszParam to point to it
            // and extract the stuff before the colon as the actual arg.
            //
            if (':' == psz[0])
               {
               pszParam = StrCharNext (psz);
               UINT cch = (UINT)(((LPARAM)psz - (LPARAM)pszArg) / NUMBYTES(TCHAR));
               StrCopyN (szTempArg, NUMCHARS(szTempArg), pszArg, cch + 1);
               DASSERT(0 == szTempArg[min(NUMCHARS(szTempArg)-1, cch)]);
               pszArg = szTempArg;
               break;
               }

            psz = StrCharNext(psz);
            }

         // lookup the argment
         //
         if ( ! App_LookupCmdLineArg (g_aAppCommands, pszArg, &cmd))
            {
            bprintfl("%s is not a valid argument", pszArg);
            hr = E_INVALIDARG;
            goto bail;
            }

         if (pszParam)
            {
            if (cmd.cParams < 1)
               {
               // if we have a param, but the arg doesn't take any, bail.
               //
               bprintfl("the %s argument is does not take parameters", pszArg);
               hr = E_INVALIDARG;
               goto bail;
               }

            cmd.pszParams = pszParam;
            }
         else
            {
            // if the command needs args, but none have been found so
            // far, try sucking up the next token in the command line
            //
            if (cmd.cParams > 0 && NULL == cmd.pszParams)
               {
               if (ii+1 < ixLast) // next pszArg belongs to us..
                  {
                  LPCTSTR pszT = aArgs[ii+1];
                  if ('-' != pszT[0] && '/' != pszT[0])
                     {
                     cmd.pszParams = pszT;
                     ++ii;  // advance the loop counter.
                     }
                  }
               }
            }
         }
      else
         {
         // not a switch, this is an implied file-open command
         //
         cmd.pszParams = pszArg;
         }

      // if the command needs an arg, but we dont have one.
      // the command line is in error.
      //
      if ((cmd.cParams > 0) && (NULL == cmd.pszParams))
         {
         bprintfl("the %s argument requires parameters", pszArg);
         g_app.fUsage = true;
         hr = E_INVALIDARG;
         goto bail;
         }

      // append the command.
      //
      Vector_AppendItem(hlst, cmd);
      }

   // return the command list
   //
   *phlst = hlst;

bail:
   if (FAILED(hr) || Vector_GetCountSafe(hlst) < 1)
      {
      *phlst = NULL;
      if (hlst)
         Vector_Delete (hlst);
      }
   return hr;
}
Ejemplo n.º 7
0
Py::Object
_image_module::fromarray(const Py::Tuple& args) {
  _VERBOSE("_image_module::fromarray");
  
  args.verify_length(2);
  
  Py::Object x = args[0];
  int isoutput = Py::Int(args[1]);
  PyArrayObject *A = (PyArrayObject *) PyArray_ContiguousFromObject(x.ptr(), PyArray_DOUBLE, 2, 3); 
  
  if (A==NULL) 
    throw Py::ValueError("Array must be rank 2 or 3 of doubles"); 
  
  
  Image* imo = new Image;
  
  imo->rowsIn  = A->dimensions[0];
  imo->colsIn  = A->dimensions[1];
  
  
  size_t NUMBYTES(imo->colsIn * imo->rowsIn * imo->BPP);
  agg::int8u *buffer = new agg::int8u[NUMBYTES];  
  if (buffer==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("_image_module::fromarray could not allocate memory");
  
  imo->bufferIn = buffer;
  imo->rbufIn = new agg::rendering_buffer;
  imo->rbufIn->attach(buffer, imo->colsIn, imo->rowsIn, imo->colsIn*imo->BPP);
  
  
  if   (A->nd == 2) { //assume luminance for now; 
    
    agg::int8u gray;
    int start = 0;    
    for (size_t rownum=0; rownum<imo->rowsIn; rownum++) 
      for (size_t colnum=0; colnum<imo->colsIn; colnum++) {
	
	double val = *(double *)(A->data + rownum*A->strides[0] + colnum*A->strides[1]);
	
	gray = int(255 * val);
	*(buffer+start++) = gray;       // red
	*(buffer+start++) = gray;       // green
	*(buffer+start++) = gray;       // blue
	*(buffer+start++)   = 255;        // alpha
      }
    
  }
  else if   (A->nd == 3) { // assume RGB
    
    if (A->dimensions[2] != 3 && A->dimensions[2] != 4 ) {
      Py_XDECREF(A);  
      throw Py::ValueError(Printf("3rd dimension must be length 3 (RGB) or 4 (RGBA); found %d", A->dimensions[2]).str()); 
      
    }
    
    int rgba = A->dimensions[2]==4;
    
    int start = 0;    
    double r,g,b,alpha;
    int offset =0;
    
    for (size_t rownum=0; rownum<imo->rowsIn; rownum++) 
      for (size_t colnum=0; colnum<imo->colsIn; colnum++) {
	offset = rownum*A->strides[0] + colnum*A->strides[1];
	r = *(double *)(A->data + offset);
	g = *(double *)(A->data + offset + A->strides[2] );
	b = *(double *)(A->data + offset + 2*A->strides[2] );
 	
	if (rgba) 
	  alpha = *(double *)(A->data + offset + 3*A->strides[2] );
	else
	  alpha = 1.0;
	
	*(buffer+start++) = int(255*r);         // red
	*(buffer+start++) = int(255*g);         // green
	*(buffer+start++) = int(255*b);         // blue
	*(buffer+start++) = int(255*alpha);     // alpha
	
      }
  } 
  else   { // error
    Py_XDECREF(A);  
    throw Py::ValueError("Illegal array rank; must be rank; must 2 or 3"); 
  }
  Py_XDECREF(A);  
  
  if (isoutput) {
    // make the output buffer point to the input buffer
    
    imo->rowsOut  = imo->rowsIn;
    imo->colsOut  = imo->colsIn;
    
    imo->bufferOut = new agg::int8u[NUMBYTES];  
    if (buffer == imo->bufferOut) //todo: also handle allocation throw
      throw Py::MemoryError("_image_module::fromarray could not allocate memory");
    
    imo->rbufOut = new agg::rendering_buffer;
    imo->rbufOut->attach(imo->bufferOut, imo->colsOut, imo->rowsOut, imo->colsOut * imo->BPP);
    
    for (size_t i=0; i<NUMBYTES; i++)
      *(imo->bufferOut +i) = *(imo->bufferIn +i);
  }
  return Py::asObject( imo );
}
Ejemplo n.º 8
0
Py::Object
_image_module::from_images(const Py::Tuple& args) {
  _VERBOSE("_image_module::from_images");
  
  args.verify_length(3);
  
  size_t numrows = Py::Int(args[0]);
  size_t numcols = Py::Int(args[1]);
  
  Py::SeqBase<Py::Object> tups = args[2];
  size_t N = tups.length();
  
  if (N==0)
    throw Py::RuntimeError("Empty list of images");
  
  Py::Tuple tup;
  
  size_t ox(0), oy(0), thisx(0), thisy(0);
  
  //copy image 0 output buffer into return images output buffer
  Image* imo = new Image;
  imo->rowsOut  = numrows;
  imo->colsOut  = numcols;
  
  size_t NUMBYTES(numrows * numcols * imo->BPP);    
  imo->bufferOut = new agg::int8u[NUMBYTES];  
  if (imo->bufferOut==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("_image_module::from_images could not allocate memory");
  
  imo->rbufOut = new agg::rendering_buffer;
  imo->rbufOut->attach(imo->bufferOut, imo->colsOut, imo->rowsOut, imo->colsOut * imo->BPP);
   
  pixfmt pixf(*imo->rbufOut);
  renderer_base rb(pixf);
  
  
  for (size_t imnum=0; imnum< N; imnum++) {
    tup = Py::Tuple(tups[imnum]);
    Image* thisim = static_cast<Image*>(tup[0].ptr());    
    if (imnum==0) 
      rb.clear(thisim->bg);
    ox = Py::Int(tup[1]);
    oy = Py::Int(tup[2]);
    
    size_t ind=0;
    for (size_t j=0; j<thisim->rowsOut; j++) {
      for (size_t i=0; i<thisim->colsOut; i++) {
	thisx = i+ox;  
	thisy = j+oy; 
	if (thisx<0 || thisx>=numcols || thisy<0 || thisy>=numrows) {
	  ind +=4;
	  continue;
	}
	
	pixfmt::color_type p;
	p.r = *(thisim->bufferOut+ind++);
	p.g = *(thisim->bufferOut+ind++);
	p.b = *(thisim->bufferOut+ind++);
	p.a = *(thisim->bufferOut+ind++);
	pixf.blend_pixel(thisx, thisy, p, 255);
      }
    }
  }
  
  return Py::asObject(imo);
  
  
  
}
Ejemplo n.º 9
0
Py::Object
Image::resize(const Py::Tuple& args) {
  _VERBOSE("Image::resize");
  
  args.verify_length(2);
  
  if (bufferIn ==NULL) 
    throw Py::RuntimeError("You must first load the image"); 
  
  int numcols = Py::Int(args[0]);
  int numrows = Py::Int(args[1]);
  
  colsOut = numcols;
  rowsOut = numrows;
  
  
  size_t NUMBYTES(numrows * numcols * BPP);
  agg::int8u *buffer = new agg::int8u[NUMBYTES];  
  if (buffer ==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("Image::resize could not allocate memory");
  
  rbufOut = new agg::rendering_buffer;
  rbufOut->attach(buffer, numcols, numrows, numcols * BPP);
  
  // init the output rendering/rasterizing stuff
  pixfmt pixf(*rbufOut);
  renderer_base rb(pixf);
  rb.clear(bg);
  agg::rasterizer_scanline_aa<> ras;
  agg::scanline_u8 sl;

  
  //srcMatrix *= resizingMatrix;
  //imageMatrix *= resizingMatrix;
  imageMatrix.invert();
  interpolator_type interpolator(imageMatrix); 
  
  
  
  
  agg::image_filter_base* filter = 0;  
  agg::span_allocator<agg::rgba8> sa;	
  agg::rgba8 background(agg::rgba8(int(255*bg.r),
				   int(255*bg.g),
				   int(255*bg.b),
				   int(255*bg.a)));




  // the image path
  agg::path_storage path;
  agg::int8u *bufferPad = NULL;
  agg::rendering_buffer rbufPad;

  double x0, y0, x1, y1;
  
  if (interpolation==NEAREST) {
    x0 = 0.0;
    x1 = colsIn;
    y0 = 0.0;
    y1 = rowsIn;
  }
  else {
    // if interpolation != nearest, create a new input buffer with the
    // edges mirrored on all size.  Then new buffer size is colsIn+2 by
    // rowsIn+2

    x0 = 1.0;
    x1 = colsIn+1;
    y0 = 1.0;
    y1 = rowsIn+1;

    bufferPad = new agg::int8u[(rowsIn+2) * (colsIn+2) * BPP];
    if (bufferPad ==NULL) 
      throw Py::MemoryError("Image::resize could not allocate memory");
    //pad the input buffer
    for (size_t rowNum=0; rowNum<rowsIn+2; rowNum++)
      for (size_t colNum=0; colNum<colsIn+2; colNum++) {
	if ( (colNum==0) && (rowNum==1||(rowNum==rowsIn+1))) {
	  //rewind to begining of column
	  bufferIn -= colsIn * BPP; 
	}
	*bufferPad++ = *bufferIn++;       //red
	*bufferPad++ = *bufferIn++;       //green
	*bufferPad++ = *bufferIn++;       //blue
	*bufferPad++ = *bufferIn++;       //alpha

	//rewind one byte on the first and next to last columns
	if ( colNum==0 || colNum==colsIn) bufferIn-=4;
      }
    //rewind the input buffers
    bufferIn  -= rowsIn * colsIn * BPP;
    bufferPad -= (rowsIn+2) * (colsIn+2) * BPP;
    rbufPad.attach(bufferPad, colsIn+2, rowsIn+2, (colsIn+2) * BPP);
  }



    
  if (buffer ==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("Image::resize could not allocate memory");
  
  path.move_to(x0, y0);
  path.line_to(x1, y0);
  path.line_to(x1, y1);
  path.line_to(x0, y1);
  path.close_polygon();
  agg::conv_transform<agg::path_storage> imageBox(path, srcMatrix);
  ras.add_path(imageBox);

  switch(interpolation)
    {
    case NEAREST:
      {
	
	typedef agg::span_image_filter_rgba32_nn<agg::order_rgba32,
	  interpolator_type> span_gen_type;
	typedef agg::renderer_scanline_aa<renderer_base, span_gen_type> renderer_type;
	       
	span_gen_type sg(sa, *rbufIn, background, interpolator);
	renderer_type ri(rb, sg);
	agg::render_scanlines(ras, sl, ri);
	
      }
      break;
      
    case BILINEAR:
      {

       
	typedef agg::span_image_filter_rgba32_bilinear<agg::order_rgba32,
	  interpolator_type> span_gen_type;
	typedef agg::renderer_scanline_aa<renderer_base, span_gen_type> renderer_type;
		
	span_gen_type sg(sa, rbufPad, background, interpolator);
	renderer_type ri(rb, sg);
	agg::render_scanlines(ras, sl, ri);
      }
      break;
      
    case BICUBIC:     filter = new agg::image_filter<agg::image_filter_bicubic>;
    case SPLINE16:    filter = new agg::image_filter<agg::image_filter_spline16>;
    case SPLINE36:    filter = new agg::image_filter<agg::image_filter_spline36>;   
    case SINC64:      filter = new agg::image_filter<agg::image_filter_sinc64>;     
    case SINC144:     filter = new agg::image_filter<agg::image_filter_sinc144>;    
    case SINC256:     filter = new agg::image_filter<agg::image_filter_sinc256>;    
    case BLACKMAN64:  filter = new agg::image_filter<agg::image_filter_blackman64>; 
    case BLACKMAN100: filter = new agg::image_filter<agg::image_filter_blackman100>;
    case BLACKMAN256: filter = new agg::image_filter<agg::image_filter_blackman256>;
      
      typedef agg::span_image_filter_rgba32<agg::order_rgba32,
	interpolator_type> span_gen_type;
      typedef agg::renderer_scanline_aa<renderer_base, span_gen_type> renderer_type;
      span_gen_type sg(sa, rbufPad, background, interpolator, *filter);
      renderer_type ri(rb, sg);
      agg::render_scanlines(ras, sl, ri);
      
    }
  
  /*
    std::ofstream of2( "image_out.raw", std::ios::binary|std::ios::out);
    for (size_t i=0; i<NUMBYTES; ++i)
    of2.write((char*)&buffer[i], sizeof(char));
  */
  
  
  bufferOut = buffer;
  delete [] bufferPad;

  return Py::Object();
  
}
Ejemplo n.º 10
0
Py::Object
Image::resize(const Py::Tuple& args) {
    _VERBOSE("Image::resize");

    args.verify_length(2);

    if (bufferIn ==NULL)
        throw Py::RuntimeError("You must first load the image");

    int numcols = Py::Int(args[0]);
    int numrows = Py::Int(args[1]);

    colsOut = numcols;
    rowsOut = numrows;


    size_t NUMBYTES(numrows * numcols * BPP);
    agg::int8u *buffer = new agg::int8u[NUMBYTES];
    if (buffer ==NULL) //todo: also handle allocation throw
        throw Py::MemoryError("Image::resize could not allocate memory");

    rbufOut = new agg::rendering_buffer;
    rbufOut->attach(buffer, numcols, numrows, numcols * BPP);

    // init the output rendering/rasterizing stuff
    pixfmt pixf(*rbufOut);
    renderer_base rb(pixf);
    rb.clear(bg);
    agg::rasterizer_scanline_aa<> ras;
    agg::scanline_u8 sl;


    //srcMatrix *= resizingMatrix;
    //imageMatrix *= resizingMatrix;
    imageMatrix.invert();
    interpolator_type interpolator(imageMatrix);

    // the image path
    agg::path_storage path;
    path.move_to(0, 0);
    path.line_to(colsIn, 0);
    path.line_to(colsIn, rowsIn);
    path.line_to(0, rowsIn);
    path.close_polygon();
    agg::conv_transform<agg::path_storage> imageBox(path, srcMatrix);
    ras.add_path(imageBox);



    agg::image_filter_base* filter = 0;
    agg::span_allocator<agg::rgba8> sa;
    switch(interpolation)
    {
    case NEAREST:
    {
        typedef agg::span_image_filter_rgba32_nn<agg::order_rgba32,
                interpolator_type> span_gen_type;
        typedef agg::renderer_scanline_u<renderer_base, span_gen_type> renderer_type;

        span_gen_type sg(sa, *rbufIn, agg::rgba(1,1,1,0), interpolator);
        renderer_type ri(rb, sg);
        ras.add_path(imageBox);
        ras.render(sl, ri);
    }
    break;

    case BILINEAR:
    {
        typedef agg::span_image_filter_rgba32_bilinear<agg::order_rgba32,
                interpolator_type> span_gen_type;
        typedef agg::renderer_scanline_u<renderer_base, span_gen_type> renderer_type;

        span_gen_type sg(sa, *rbufIn, agg::rgba(1,1,1,0), interpolator);
        renderer_type ri(rb, sg);
        ras.add_path(imageBox);
        ras.render(sl, ri);
    }
    break;

    case BICUBIC:
        filter = new agg::image_filter<agg::image_filter_bicubic>;
    case SPLINE16:
        filter = new agg::image_filter<agg::image_filter_spline16>;
    case SPLINE36:
        filter = new agg::image_filter<agg::image_filter_spline36>;
    case SINC64:
        filter = new agg::image_filter<agg::image_filter_sinc64>;
    case SINC144:
        filter = new agg::image_filter<agg::image_filter_sinc144>;
    case SINC256:
        filter = new agg::image_filter<agg::image_filter_sinc256>;
    case BLACKMAN64:
        filter = new agg::image_filter<agg::image_filter_blackman64>;
    case BLACKMAN100:
        filter = new agg::image_filter<agg::image_filter_blackman100>;
    case BLACKMAN256:
        filter = new agg::image_filter<agg::image_filter_blackman256>;

        typedef agg::span_image_filter_rgba32<agg::order_rgba32,
                interpolator_type> span_gen_type;
        typedef agg::renderer_scanline_u<renderer_base, span_gen_type> renderer_type;

        span_gen_type sg(sa, *rbufIn, agg::rgba(1,1,1,0), interpolator, *filter);
        renderer_type ri(rb, sg);
        ras.render(sl, ri);

    }

    /*
      std::ofstream of2( "image_out.raw", std::ios::binary|std::ios::out);
      for (size_t i=0; i<NUMBYTES; ++i)
      of2.write((char*)&buffer[i], sizeof(char));
    */


    bufferOut = buffer;


    return Py::Object();

}
Ejemplo n.º 11
0
Py::Object
Image::resize(const Py::Tuple& args, const Py::Dict& kwargs) {
  _VERBOSE("Image::resize");

  args.verify_length(2);

  int norm = 1;
  if ( kwargs.hasKey("norm") ) norm = Py::Int( kwargs["norm"] );

  double radius = 4.0;
  if ( kwargs.hasKey("radius") ) radius = Py::Float( kwargs["radius"] );

  if (bufferIn ==NULL)
    throw Py::RuntimeError("You must first load the image");

  int numcols = Py::Int(args[0]);
  int numrows = Py::Int(args[1]);

  colsOut = numcols;
  rowsOut = numrows;


  size_t NUMBYTES(numrows * numcols * BPP);

  delete [] bufferOut;
  bufferOut = new agg::int8u[NUMBYTES];
  if (bufferOut ==NULL) //todo: also handle allocation throw
    throw Py::MemoryError("Image::resize could not allocate memory");

  delete rbufOut;
  rbufOut = new agg::rendering_buffer;
  rbufOut->attach(bufferOut, numcols, numrows, numcols * BPP);

  // init the output rendering/rasterizing stuff
  pixfmt pixf(*rbufOut);
  renderer_base rb(pixf);
  rb.clear(bg);
  agg::rasterizer_scanline_aa<> ras;
  agg::scanline_u8 sl;


  //srcMatrix *= resizingMatrix;
  //imageMatrix *= resizingMatrix;
  imageMatrix.invert();
  interpolator_type interpolator(imageMatrix);

  typedef agg::span_allocator<agg::rgba8> span_alloc_type;
  span_alloc_type sa;
  agg::rgba8 background(agg::rgba8(int(255*bg.r),
				   int(255*bg.g),
				   int(255*bg.b),
				   int(255*bg.a)));

  // the image path
  agg::path_storage path;
  agg::int8u *bufferPad = NULL;
  agg::rendering_buffer rbufPad;

  double x0, y0, x1, y1;

  x0 = 0.0;
  x1 = colsIn;
  y0 = 0.0;
  y1 = rowsIn;

  path.move_to(x0, y0);
  path.line_to(x1, y0);
  path.line_to(x1, y1);
  path.line_to(x0, y1);
  path.close_polygon();
  agg::conv_transform<agg::path_storage> imageBox(path, srcMatrix);
  ras.add_path(imageBox);

  typedef agg::wrap_mode_reflect reflect_type;
  typedef agg::image_accessor_wrap<pixfmt, reflect_type, reflect_type> img_accessor_type;

  pixfmt pixfmtin(*rbufIn);
  img_accessor_type ia(pixfmtin);
  switch(interpolation)
    {

    case NEAREST:
      {
	typedef agg::span_image_filter_rgba_nn<img_accessor_type, interpolator_type> span_gen_type;
	typedef agg::renderer_scanline_aa<renderer_base, span_alloc_type, span_gen_type> renderer_type;
	span_gen_type sg(ia, interpolator);
	renderer_type ri(rb, sa, sg);
	agg::render_scanlines(ras, sl, ri);
      }
      break;
        case BILINEAR:
        case BICUBIC:
        case SPLINE16:
        case SPLINE36:
        case HANNING:
        case HAMMING:
        case HERMITE:
        case KAISER:
        case QUADRIC:
        case CATROM:
        case GAUSSIAN:
        case BESSEL:
        case MITCHELL:
        case SINC:
        case LANCZOS:
        case BLACKMAN:
            {
                agg::image_filter_lut filter;
                switch(interpolation)
                {
                case BILINEAR:  filter.calculate(agg::image_filter_bilinear(), norm); break;
                case BICUBIC:  filter.calculate(agg::image_filter_bicubic(), norm); break;
                case SPLINE16:  filter.calculate(agg::image_filter_spline16(), norm); break;
                case SPLINE36:  filter.calculate(agg::image_filter_spline36(), norm); break;
                case HANNING:  filter.calculate(agg::image_filter_hanning(), norm); break;
                case HAMMING:  filter.calculate(agg::image_filter_hamming(), norm); break;
                case HERMITE:  filter.calculate(agg::image_filter_hermite(), norm); break;
                case KAISER:  filter.calculate(agg::image_filter_kaiser(), norm); break;
                case QUADRIC:  filter.calculate(agg::image_filter_quadric(), norm); break;
                case CATROM: filter.calculate(agg::image_filter_catrom(), norm); break;
                case GAUSSIAN: filter.calculate(agg::image_filter_gaussian(), norm); break;
                case BESSEL: filter.calculate(agg::image_filter_bessel(), norm); break;
                case MITCHELL: filter.calculate(agg::image_filter_mitchell(), norm); break;
                case SINC: filter.calculate(agg::image_filter_sinc(radius), norm); break;
                case LANCZOS: filter.calculate(agg::image_filter_lanczos(radius), norm); break;
                case BLACKMAN: filter.calculate(agg::image_filter_blackman(radius), norm); break;
                }
	typedef agg::span_image_filter_rgba_2x2<img_accessor_type, interpolator_type> span_gen_type;
	typedef agg::renderer_scanline_aa<renderer_base, span_alloc_type, span_gen_type> renderer_type;
	span_gen_type sg(ia, interpolator, filter);
	renderer_type ri(rb, sa, sg);
	agg::render_scanlines(ras, sl, ri);
      }
      break;

    }

  delete [] bufferPad;
  return Py::Object();

}
Ejemplo n.º 12
0
Py::Object
_image_module::pcolor2(const Py::Tuple& args) {
    _VERBOSE("_image_module::pcolor2");

    if (args.length() != 7)
        throw Py::TypeError("Incorrect number of arguments (6 expected)");

    Py::Object xp = args[0];
    Py::Object yp = args[1];
    Py::Object dp = args[2];
    int rows = Py::Int(args[3]);
    int cols = Py::Int(args[4]);
    Py::Tuple bounds = args[5];
    Py::Object bgp = args[6];

    if (bounds.length() !=4)
        throw Py::TypeError("Incorrect number of bounds (4 expected)");
    double x_left = Py::Float(bounds[0]);
    double x_right = Py::Float(bounds[1]);
    double y_bot = Py::Float(bounds[2]);
    double y_top = Py::Float(bounds[3]);

    // Check we have something to output to
    if (rows == 0 || cols ==0)
        throw Py::ValueError("rows or cols is zero; there are no pixels");

    // Get numpy arrays
    PyArrayObject *x = (PyArrayObject *) PyArray_ContiguousFromObject(xp.ptr(),
                                                          PyArray_DOUBLE, 1, 1);
    if (x == NULL)
        throw Py::ValueError("x is of incorrect type (wanted 1D double)");
    PyArrayObject *y = (PyArrayObject *) PyArray_ContiguousFromObject(yp.ptr(),
                                                          PyArray_DOUBLE, 1, 1);
    if (y == NULL) {
        Py_XDECREF(x);
        throw Py::ValueError("y is of incorrect type (wanted 1D double)");
    }
    PyArrayObject *d = (PyArrayObject *) PyArray_ContiguousFromObject(dp.ptr(),
                                                          PyArray_UBYTE, 3, 3);
    if (d == NULL) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        throw Py::ValueError("data is of incorrect type (wanted 3D uint8)");
    }
    if (d->dimensions[2] != 4) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(d);
        throw Py::ValueError("data must be in RGBA format");
    }

    // Check dimensions match
    int nx = x->dimensions[0];
    int ny = y->dimensions[0];
    if (nx != d->dimensions[1]+1 || ny != d->dimensions[0]+1) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(d);
        throw Py::ValueError("data and axis bin boundary dimensions are incompatible");
    }

    PyArrayObject *bg = (PyArrayObject *) PyArray_ContiguousFromObject(bgp.ptr(),
                                                          PyArray_UBYTE, 1, 1);
    if (bg == NULL) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(d);
        throw Py::ValueError("bg is of incorrect type (wanted 1D uint8)");
    }
    if (bg->dimensions[0] != 4) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(d);
        Py_XDECREF(bg);
        throw Py::ValueError("bg must be in RGBA format");
    }


    // Allocate memory for pointer arrays
    int * irows = reinterpret_cast<int*>(PyMem_Malloc(sizeof(int)*rows));
    if (irows == NULL) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(d);
        Py_XDECREF(bg);
        throw Py::MemoryError("Cannot allocate memory for lookup table");
    }
    int * jcols = reinterpret_cast<int*>(PyMem_Malloc(sizeof(int*)*cols));
    if (jcols == NULL) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(d);
        Py_XDECREF(bg);
        PyMem_Free(irows);
        throw Py::MemoryError("Cannot allocate memory for lookup table");
    }

    // Create output
    Image* imo = new Image;
    imo->rowsIn = rows;
    imo->rowsOut = rows;
    imo->colsIn = cols;
    imo->colsOut = cols;
    size_t NUMBYTES(rows * cols * 4);
    agg::int8u *buffer = new agg::int8u[NUMBYTES];
    if (buffer == NULL) {
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(d);
        Py_XDECREF(bg);
        PyMem_Free(irows);
        PyMem_Free(jcols);
        throw Py::MemoryError("Could not allocate memory for image");
    }

    // Calculate the pointer arrays to map input x to output x
    int i, j;
    double *x0 = reinterpret_cast<double*>(x->data);
    double *y0 = reinterpret_cast<double*>(y->data);
    double sx = cols/(x_right - x_left);
    double sy = rows/(y_top - y_bot);
    _bin_indices(jcols, cols, x0, nx, sx, x_left);
    _bin_indices(irows, rows, y0, ny, sy, y_bot);

    // Copy data to output buffer
    agg::int8u * position = buffer;
    unsigned char *start = reinterpret_cast<unsigned char*>(d->data);
    unsigned char *bgptr = reinterpret_cast<unsigned char*>(bg->data);
    int s0 = d->strides[0];
    int s1 = d->strides[1];

    for (i=0; i<rows; i++)
    {
        for (j=0; j<cols; j++)
        {
            if (irows[i] == -1 || jcols[j] == -1) {
                memcpy(position, bgptr, 4*sizeof(agg::int8u));
            }
            else {
                memcpy(position, (start + s0*irows[i] + s1*jcols[j]),
                                                  4*sizeof(agg::int8u));
            }
            position += 4;
        }
    }

    // Attach output buffer to output buffer
    imo->rbufOut = new agg::rendering_buffer;
    imo->bufferOut = buffer;
    imo->rbufOut->attach(imo->bufferOut, imo->colsOut, imo->rowsOut, imo->colsOut * imo->BPP);

    Py_XDECREF(x);
    Py_XDECREF(y);
    Py_XDECREF(d);
    Py_XDECREF(bg);
    PyMem_Free(irows);
    PyMem_Free(jcols);

    return Py::asObject(imo);
}
Ejemplo n.º 13
0
Py::Object
_image_module::pcolor(const Py::Tuple& args) {
  _VERBOSE("_image_module::pcolor");


  if (args.length() != 6)
      throw Py::TypeError("Incorrect number of arguments (6 expected)");

  Py::Object xp = args[0];
  Py::Object yp = args[1];
  Py::Object dp = args[2];
  unsigned int rows = Py::Int(args[3]);
  unsigned int cols = Py::Int(args[4]);
  Py::Tuple bounds = args[5];

  if (bounds.length() !=4)
      throw Py::TypeError("Incorrect number of bounds (4 expected)");
  float x_min = Py::Float(bounds[0]);
  float x_max = Py::Float(bounds[1]);
  float y_min = Py::Float(bounds[2]);
  float y_max = Py::Float(bounds[3]);
  float width = x_max - x_min;
  float height = y_max - y_min;
  float dx = width / ((float) cols);
  float dy = height / ((float) rows);

  // Check we have something to output to
  if (rows == 0 || cols ==0)
      throw Py::ValueError("Cannot scale to zero size");

  // Get numpy arrays
  PyArrayObject *x = (PyArrayObject *) PyArray_ContiguousFromObject(xp.ptr(), PyArray_FLOAT, 1, 1);
  if (x == NULL)
      throw Py::ValueError("x is of incorrect type (wanted 1D float)");
  PyArrayObject *y = (PyArrayObject *) PyArray_ContiguousFromObject(yp.ptr(), PyArray_FLOAT, 1, 1);
  if (y == NULL) {
      Py_XDECREF(x);
      throw Py::ValueError("y is of incorrect type (wanted 1D float)");
  }
  PyArrayObject *d = (PyArrayObject *) PyArray_ContiguousFromObject(dp.ptr(), PyArray_UBYTE, 3, 3);
  if (d == NULL) {
      Py_XDECREF(x);
      Py_XDECREF(y);
      throw Py::ValueError("data is of incorrect type (wanted 3D UInt8)");
  }
  if (d->dimensions[2] != 4) {
      Py_XDECREF(x);
      Py_XDECREF(y);
      Py_XDECREF(d);
      throw Py::ValueError("data must be in RGBA format");
  }

  // Check dimensions match
  int nx = x->dimensions[0];
  int ny = y->dimensions[0];
  if (nx != d->dimensions[1] || ny != d->dimensions[0]) {
      Py_XDECREF(x);
      Py_XDECREF(y);
      Py_XDECREF(d);
      throw Py::ValueError("data and axis dimensions do not match");
  }

  // Allocate memory for pointer arrays
  unsigned int * rowstarts = reinterpret_cast<unsigned int*>(PyMem_Malloc(sizeof(unsigned int)*rows));
  if (rowstarts == NULL) {
      Py_XDECREF(x);
      Py_XDECREF(y);
      Py_XDECREF(d);
      throw Py::MemoryError("Cannot allocate memory for lookup table");
  }
  unsigned int * colstarts = reinterpret_cast<unsigned int*>(PyMem_Malloc(sizeof(unsigned int*)*cols));
  if (colstarts == NULL) {
      Py_XDECREF(x);
      Py_XDECREF(y);
      Py_XDECREF(d);
      PyMem_Free(rowstarts);
      throw Py::MemoryError("Cannot allocate memory for lookup table");
  }

  // Create output
  Image* imo = new Image;
  imo->rowsIn = rows;
  imo->colsIn = cols;
  imo->rowsOut = rows;
  imo->colsOut = cols;
  size_t NUMBYTES(rows * cols * 4);
  agg::int8u *buffer = new agg::int8u[NUMBYTES];
  if (buffer == NULL) {
      Py_XDECREF(x);
      Py_XDECREF(y);
      Py_XDECREF(d);
      PyMem_Free(rowstarts);
      PyMem_Free(colstarts);
      throw Py::MemoryError("Could not allocate memory for image");
  }

  // Calculate the pointer arrays to map input x to output x
  unsigned int i, j, j_last;
  unsigned int * colstart = colstarts;
  unsigned int * rowstart = rowstarts;
  float *xs1 = reinterpret_cast<float*>(x->data);
  float *ys1 = reinterpret_cast<float*>(y->data);
  float *xs2 = xs1+1;
  float *ys2 = ys1+1;
  float *xl = xs1 + nx - 1;
  float *yl = ys1 + ny - 1;
  float xo = x_min + dx/2.0;
  float yo = y_min + dy/2.0;
  float xm = 0.5*(*xs1 + *xs2);
  float ym = 0.5*(*ys1 + *ys2);
  // x/cols
  j = 0;
  j_last = j;
  for (i=0;i<cols;i++,xo+=dx,colstart++) {
      while(xs2 != xl && xo > xm) {
          xs1 = xs2;
          xs2 = xs1+1;
          xm = 0.5*(*xs1 + *xs2);
          j++;
      }
      *colstart = j - j_last;
      j_last = j;
  }
  // y/rows
  j = 0;
  j_last = j;
  for (i=0;i<rows;i++,yo+=dy,rowstart++) {
      while(ys2 != yl && yo > ym) {
          ys1 = ys2;
          ys2 = ys1+1;
          ym = 0.5*(*ys1 + *ys2);
          j++;
      }
      *rowstart = j - j_last;
      j_last = j;
  }


  // Copy data to output buffer
  unsigned char *start;
  unsigned char *inposition;
  size_t inrowsize(nx*4);
  size_t rowsize(cols*4);
  rowstart = rowstarts;
  agg::int8u * position = buffer;
  agg::int8u * oldposition = NULL;
  start = reinterpret_cast<unsigned char*>(d->data);
  for(i=0;i<rows;i++,rowstart++)
  {
      if (i > 0 && *rowstart == 0) {
          memcpy(position, oldposition, rowsize*sizeof(agg::int8u));
          oldposition = position;
          position += rowsize;
      } else {
          oldposition = position;
          start += *rowstart * inrowsize;
          inposition = start;
          for(j=0,colstart=colstarts;j<cols;j++,position+=4,colstart++) {
              inposition += *colstart * 4;
              memcpy(position, inposition, 4*sizeof(agg::int8u));
          }
      }
  }

  // Attatch output buffer to output buffer
  imo->rbufOut = new agg::rendering_buffer;
  imo->bufferOut = buffer;
  imo->rbufOut->attach(imo->bufferOut, imo->colsOut, imo->rowsOut, imo->colsOut * imo->BPP);

  Py_XDECREF(x);
  Py_XDECREF(y);
  Py_XDECREF(d);
  PyMem_Free(rowstarts);
  PyMem_Free(colstarts);

  return Py::asObject(imo);
}
Ejemplo n.º 14
0
Py::Object
_image_module::frombyte(const Py::Tuple& args) {
  _VERBOSE("_image_module::frombyte");

  args.verify_length(2);

  Py::Object x = args[0];
  int isoutput = Py::Int(args[1]);

  PyArrayObject *A = (PyArrayObject *) PyArray_ContiguousFromObject(x.ptr(), PyArray_UBYTE, 3, 3);
  if (A == NULL)
      throw Py::ValueError("Array must have 3 dimensions");
  if (A->dimensions[2]<3 || A->dimensions[2]>4)
      throw Py::ValueError("Array dimension 3 must have size 3 or 4");

  Image* imo = new Image;

  imo->rowsIn = A->dimensions[0];
  imo->colsIn = A->dimensions[1];

  agg::int8u *arrbuf;
  agg::int8u *buffer;

  arrbuf = reinterpret_cast<agg::int8u *>(A->data);

  size_t NUMBYTES(imo->colsIn * imo->rowsIn * imo->BPP);
  buffer = new agg::int8u[NUMBYTES];

  if (buffer==NULL) //todo: also handle allocation throw
      throw Py::MemoryError("_image_module::frombyte could not allocate memory");

  const size_t N = imo->rowsIn * imo->colsIn * imo->BPP;
  size_t i = 0;
  if (A->dimensions[2] == 4) {
      memmove(buffer, arrbuf, N);
  } else {
      while (i < N) {
          memmove(buffer, arrbuf, 3);
          buffer += 3;
          arrbuf += 3;
          *buffer++ = 255;
          i += 4;
      }
      buffer -= N;
      arrbuf -= imo->rowsIn * imo->colsIn;
  }
  Py_XDECREF(A);

  if (isoutput) {
    // make the output buffer point to the input buffer

    imo->rowsOut  = imo->rowsIn;
    imo->colsOut  = imo->colsIn;

    imo->rbufOut = new agg::rendering_buffer;
    imo->bufferOut = buffer;
    imo->rbufOut->attach(imo->bufferOut, imo->colsOut, imo->rowsOut, imo->colsOut * imo->BPP);

  }
  else {
    imo->bufferIn = buffer;
    imo->rbufIn = new agg::rendering_buffer;
    imo->rbufIn->attach(buffer, imo->colsIn, imo->rowsIn, imo->colsIn*imo->BPP);
  }

  return Py::asObject( imo );
}