示例#1
0
void getImage(){
   db = QSqlDatabase::addDatabase("QSQLITE");
   db.setDatabaseName("/home/seven7up/ImageData.sqlite");

   if(!db.open()){
       cout<< "connect to database fail";
   }
   else{
       QList<ImageObject> myList;
       ImageObject object;
       QSqlQuery q(db);
       int r;
       q.exec("select * from (LinkImage join Alphabet) where (LinkImage.idLetter = Alphabet.id)");
       for (r = 0, q.first(); q.isValid(); q.next(),++r) {

           object.SetId(q.value(0).toInt());
           object.SetLink(q.value(1).toString());
           object.SetLetterId(q.value(4).toString());
           myList.append(object);
       }

       foreach (const ImageObject &o, myList) {
               cout<< itos(o.GetId())+ "---" + o.GetLink().toStdString() + "--- "+ o.GetLetterId().toStdString() << endl;
       }
   }
示例#2
0
void View::ReferenceTransformChanged()
{
    // We update transform only if it is a 2D view or if Manager says we follow 3D views as well
    if( this->Manager && ( this->GetType() != THREED_VIEW_TYPE || this->Manager->Is3DViewFollowingReferenceVolume() ) )
    {
        ImageObject * obj = this->Manager->GetReferenceDataObject();
        vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New();
        vtkCamera * cam = this->Renderer->GetActiveCamera();
        if( obj && this->Renderer )
        {
            vtkTransform * refTransform = obj->GetWorldTransform();
            t->SetInput( refTransform );
            t->Concatenate( this->PrevViewingTransform );

            cam->ApplyTransform( t );

            // backup inverted current transform
            this->PrevViewingTransform->DeepCopy( refTransform->GetMatrix() );
            this->PrevViewingTransform->Invert();

            NotifyNeedRender();
        }
        else
        {
            t->Identity();
            t->Concatenate( this->PrevViewingTransform );
            cam->ApplyTransform( t );
            // backup inverted current transform
            this->PrevViewingTransform->Identity();
        }
    }
}
示例#3
0
void GraphData::render( ImageObject& img, const Rect& r )
{
	int pixel = 0;
	int old_pixel = 0;

	for(int i = 0; i < values-1; i++)
	{
		if(pInterpolation == GRAPH_INTERPOLATION_NONE)
		{
			img.putPixel(data_pixels[i][0], (int)getValue(i, 1), lineColor);
		}
		else
		{
			int spacing = (data_pixels[i+1][0]-data_pixels[i][0]);
			for(int i2 = 0; i2 < spacing; i2++)
			{
				float pos = ((float)i2/(float)(data_pixels[i+1][0]-data_pixels[i][0]));

				//TODO: Select interpolation type
				if(pInterpolation == GRAPH_INTERPOLATION_SPLINE)
				{
					pixel = (int)splineInterpolation(pos, getValue(i-2,1), getValue(i-1, 1), getValue(i, 1), getValue(i+1, 1), getValue(i+2, 1), getValue(i+3, 1));
				}
				else if(pInterpolation == GRAPH_INTERPOLATION_CUBIC)
				{
					pixel = (int)linearInterpolation(pos, getValue(i, 1), getValue(i+1, 1)) + 10;
				}
				else
				{
					pixel = (int)linearInterpolation(pos, getValue(i, 1), getValue(i+1, 1));
				}

				// Going up
				if(pixel > old_pixel)
				{
					for(int apa = abs(pixel-old_pixel); apa >= 0; apa--)
					{
						img.putPixel(data_pixels[i][0]+i2, pixel-apa, lineColor);
					}
				}
				// Going down
				else if(old_pixel > pixel)
				{
					for(int apa = abs(pixel-old_pixel); apa >= 0; apa--)
					{
						img.putPixel(data_pixels[i][0]+i2, pixel+apa-1, lineColor);
					}
				}
				// Same value as previous sample
				else
				{
					img.putPixel(data_pixels[i][0]+i2, pixel, lineColor);
					img.putPixel(data_pixels[i][0]+i2, pixel-1, lineColor);
				}
				old_pixel = pixel;
			}
		}
	}
}
bool ImageWriter::WritePNG(const std::string& sFilename, ImageObject& image)
{
   if (image.GetNumChannels() != 4)
   {
      return false;
   }

   return WritePNG(sFilename, image.GetRawData().get(), image.GetWidth(), image.GetHeight());
}
bool LabelVolumeToSurfacesPluginInterface::CanRun()
{
    IbisAPI *ibisAPI = GetIbisAPI();
    Q_ASSERT(ibisAPI);
    ImageObject * image = ImageObject::SafeDownCast( ibisAPI->GetCurrentObject() );
    if( image && image->IsLabelImage() )
        return true;
    return false;
}
Variable loadImageExpression::evaluate()
{
	Variable var(new ImageObject());
	std::shared_ptr<TerminalExpression> t = std::dynamic_pointer_cast<TerminalExpression>(arguments[0]);
	if (t)
	{
		ImageObject* im = var.get<ImageObject>();
		im->loadImage(t->getString());
	}
	else
		throw new Exception(Exception::ErrorType::TYPE_MISMATCH);
	return var;
}
示例#7
0
文件: uiknob.cpp 项目: chille/GameUI
void Knob::render( ImageObject& img, const Rect& r )
{
  if ( !visible() ) return;
  if ( pImage != NULL ) {
    img.drawImage( *pImage, Rect( 0, 0, pImage->sectionWidth(), pImage->sectionHeight() ), pImage->sectionRect( pValue ) );
  } else if ( pImages != NULL ) {
    ImageObject* tmp = pImages->get( pValue );
    if ( tmp != NULL ) {
      img.drawImage( *tmp, Rect( 0, 0, tmp->width(), tmp->height()), pImage->sectionRect( pValue ) );
    }
  } else {
    Widget::render( img, r );
  }
}
void ImageModel::updateRows(const QModelIndex &, int start, int end)
{
    for (int row = start; row <= end; ++row) {
        QJsonValue rowData = EnginioModel::data(index(row)).value<QJsonValue>();
        QString id = rowData.toObject().value("id").toString();
        if (id.isEmpty() || m_images.contains(id))
            continue;
        ImageObject *image = new ImageObject(client());
        connect(image, SIGNAL(imageChanged(QString)), this, SLOT(imageChanged(QString)));
        m_images.insert(id, image);
        image->setObject(rowData.toObject());
        QModelIndex changedIndex = index(row);
        emit dataChanged(changedIndex, changedIndex);
    }
}
示例#9
0
void SDLImageObject::drawImage( ImageObject &image, const Rect& dr, const Rect &sr )
{
  Rect dr2 = dr;
  dr2.left += pRelX;
  dr2.top += pRelY;
  visDebug( dr2 );
  updated = true;
  SDLImageObject *i = (SDLImageObject*)&image;

//  cout << "* Ui::SDLDrawInterface::drawImage(  )" << endl;
  pushClipRect( dr2 );
  if ( clipRect().area() <= 0 ) {
    popClipRect();
    return;
  }

  SDL_Rect *sdldr = new SDL_Rect;

  sdldr->x = dr2.left;
  sdldr->y = dr2.top;
  if ( dr2.width == 0 ) {
    sdldr->w = image.width();
  } else {
    sdldr->w = dr2.width;
  }
  if ( dr2.height == 0 ) {
    sdldr->h = image.height();
  } else {
    sdldr->h = dr2.height;
  }

  SDL_Rect *sdlsr = NULL;
  if ( sr != NULL_RECT ) {
    sdlsr = new SDL_Rect;
    sdlsr->x = sr.left;
    sdlsr->y = sr.top;
    sdlsr->w = sr.width;
    sdlsr->h = sr.height;
  }

  SDL_BlitSurface( i->getSurface(), sdlsr, s, sdldr );

  popClipRect();
  delete sdldr;

}
示例#10
0
bool ImageWriter::WriteJPG(const std::string& sFilename, ImageObject& image, int quality)
{
   unsigned char* pInput = 0;
   ImageObject rgbimage;

   if (image.GetPixelFormat() != Img::PixelFormat_RGB)
   {
      image.Convert(Img::PixelFormat_RGB, rgbimage);
      pInput = rgbimage.GetRawData().get();
   }
   else
   {
      pInput = image.GetRawData().get();
   }

   boost::shared_array<unsigned char> outjpg;
   int len;
   if (JPEGHandler::RGBToJpeg(pInput, image.GetWidth(), image.GetHeight(), quality, outjpg, len))
   {
      std::fstream off(sFilename.c_str(), std::ios::out | std::ios::binary);
      if (off.good())
      {
         off.write((char*)outjpg.get(), (std::streamsize)len);
         off.close();
         return true;
      }
   }

   return false;

}
示例#11
0
Variable blendExpression::evaluate()
{
	ImageObject* bottom = store->getImage();
	Variable topVar = arguments[0]->getResult();
	ImageObject* top = topVar.get<ImageObject>();

	setLocalVariable("x", &x);
	setLocalVariable("y", &y);
	setLocalVariable("r1", &r1);
	setLocalVariable("g1", &g1);
	setLocalVariable("b1", &b1);
	setLocalVariable("h1", &h1);
	setLocalVariable("s1", &s1);
	setLocalVariable("v1", &v1);
	setLocalVariable("a1", &a1);
	setLocalVariable("r2", &r2);
	setLocalVariable("g2", &g2);
	setLocalVariable("b2", &b2);
	setLocalVariable("h2", &h2);
	setLocalVariable("s2", &s2);
	setLocalVariable("v2", &v2);
	setLocalVariable("a2", &a2);

	for (int cx = 0; cx < std::min(top->getWidth(),bottom->getWidth()); cx++)
		for (int cy = 0; cy < std::min(top->getHeight(), bottom->getHeight()); cy++)
		{
			x = cx;
			y = cy;
			if (store->mask->getValue(cx, cy) > 0)
			{
				Colour b = bottom->getPixel(cx, cy);
				r1 = (float)b.r();
				g1 = (float)b.g();
				b1 = (float)b.b();
				h1 = (float)b.h();
				s1 = (float)b.s();
				v1 = (float)b.v();
				a1 = (float)b.a();
				Colour t = top->getPixel(cx, cy);
				r2 = (float)t.r();
				g2 = (float)t.g();
				b2 = (float)t.b();
				h2 = (float)t.h();
				s2 = (float)t.s();
				v2 = (float)t.v();
				a2 = (float)t.a();
				Variable col = arguments[1]->getResult();
				buffer->setPixel(cx, cy, *col.get<Colour>());
			}

		}
	commitBuffer();
	return Variable();
}
SceneObject *ContourSurfacePluginInterface::CreateObject()
{
    IbisAPI *ibisAPI = GetIbisAPI();
    Q_ASSERT(ibisAPI);
    m_generatedSurface = vtkSmartPointer<GeneratedSurface>::New();
    m_generatedSurface->SetPluginInterface( this );
    if( ibisAPI->IsLoadingScene() )
    {
        ibisAPI->AddObject(m_generatedSurface);
        return m_generatedSurface;
    }
    // If we have a current object we build surface now
    SceneObject *obj = ibisAPI->GetCurrentObject();
    if (obj->IsA("ImageObject"))
    {
        ImageObject *image = ImageObject::SafeDownCast(obj);
        double imageRange[2];
        image->GetImageScalarRange(imageRange);
        double contourValue = imageRange[0]+(imageRange[1]-imageRange[0])/5.0; //the best seems to be 20% of max, tested on Colin27
        m_generatedSurface->SetImageObjectID( image->GetObjectID() );
        m_generatedSurface->SetContourValue(contourValue);
        m_generatedSurface->SetGaussianSmoothingFlag(true);
        if ( m_generatedSurface->GenerateSurface() )
        {
            QString surfaceName(image->GetName());
            int n = surfaceName.lastIndexOf('.');
            if (n < 0)
                surfaceName.append("_surface");
            else
            {
                surfaceName.replace(n, surfaceName.size()-n, "_surface");
            }
            surfaceName.append(QString::number(image->GetNumberOfChildren()));
            m_generatedSurface->SetName(surfaceName);
            m_generatedSurface->SetScalarsVisible(0);
            ibisAPI->AddObject(m_generatedSurface, image);
            ibisAPI->SetCurrentObject( m_generatedSurface );
        }
        return m_generatedSurface;
    }
    QMessageBox::warning( 0, "Error!", "Current object should be an ImageObject" );
    return NULL;
}
示例#13
0
void PushButton::render( ImageObject& img, const Rect& r )
{
  if ( !visible() ) return;

	Rect r2 = Rect( 0, 0, clientVisibleWidth(), clientVisibleHeight() );
  int theight = 0;
  int twidth = 0;
  if ( (font() != NULL) && ( text() != L"" ) ) {
    theight = font()->textHeight();
    twidth = font()->textWidth( pText ) + 2;
  }
  if ( pImage != NULL ) {

    twidth += pImage->width();
    r2.top = ( r2.height / 2 - pImage->height() / 2 );
    r2.left = ( r2.width / 2 - twidth / 2 );
    r2.width = pImage->width();
    r2.height = pImage->height();
    if ( pressed() ) {
      r2.top += 1;
      r2.left += 1;
    }
    img.drawImage( *pImage, r2 );
    r2.left += pImage->width() + 2;
		r2.width = clientVisibleWidth();
		r2.height = clientVisibleHeight();

  } else {
    r2.left = ( r2.width / 2 - (twidth-2) / 2 );
  }
  r2.top = ( r2.height / 2 - theight / 2 );
  if ( font() != NULL ) {
    if ( pressed() ) {
      img.outText( pText, *font(), (int)r2.left+1, (int)r2.top+1, fontColor() );
    } else {
      img.outText( pText, *font(), (int)r2.left, (int)r2.top, fontColor() );
    }
  }
}
示例#14
0
ImageObject *
CreateDropShadowMask(const ViewportInfo *vpInfo, int offx, int offy, int r)
{
    int rx2 = r * 2;
    int img_w = vpInfo->file->Width();
    int img_h = vpInfo->file->Height();

    ImageObject *mask = new ImageObject(
        offx + r + img_w, offy + r + img_h, 1);

    // Create the blur image
    float *blur = new float[rx2 * rx2];
    //float root2 = sqrt(2.);
    float blurSum = 0.;
    for (int i=0; i<rx2; i++)
    {
        for (int j=0; j<rx2; j++)
        {
            float u = float(i)/float(rx2-1);
            float v = float(j)/float(rx2-1);

            float gu = exp(-pow((4*(u - .5)), 2));
            float gv = exp(-pow((4*(v - .5)), 2));
            float a = gu * gv;
            blur[i*rx2+j] = a;
            blurSum += a;
        }
    }
    for(int j = 0; j < rx2; ++j)
        for(int i = 0; i < rx2; ++i)
            blur[j*rx2 + i] /= blurSum;

    if(vpInfo->opaqueMode == M_OPAQUE)
    {
        int white = 255;
        mask->SetBlockToColor(offx, offy, offx + img_w, offy + img_h, &white);
    }
    else if(vpInfo->opaqueMode == M_TRANSPARENT)
    {
        int gray = int(vpInfo->opacity * 255.);
        mask->SetBlockToColor(offx, offy, offx + img_w, offy + img_h, &gray);
    }
    else
    {
        unsigned char rr, rg, rb;
        rr = vpInfo->transparentColor[0];
        rg = vpInfo->transparentColor[1];
        rb = vpInfo->transparentColor[2];

        // Everywhere that does not match the bg color, color white.
        for(int y = 0; y < img_h; ++y)
        {
            for(int x = 0; x < img_w; ++x)
            {
                unsigned char *src = vpInfo->file->Pixel(x, y);
                unsigned char *dest = mask->Pixel(x+offx, y+offy);

                if(src[0] != rr || src[1] != rg || src[2] != rb)
                    *dest = 255;
            }
        }
    }

    // Blur the mask by convolving it with the blur kernel.
    for(int y = offy; y < offy + img_h; ++y)
    {
        for(int x = offx; x < offx + img_w; ++x)
        {
            int ksrcx = x - r;
            int ksrcy = y - r;
            float channelSum = 0.;
            for(int ky = 0; ky < rx2; ++ky)
            {
                for(int kx = 0; kx < rx2; ++kx)
                {
                    unsigned char *mask_ptr = mask->Pixel(ksrcx + kx, ksrcy + ky);
                    channelSum += float(*mask_ptr) * blur[ky*rx2+kx];
                }
            }
            unsigned char *dest = mask->Pixel(x, y);
            *dest = (unsigned char)(int)(channelSum);
        }
    }

    if(vpInfo->opaqueMode == M_TRANSPARENT)
    {
        int black = 0;
        mask->SetBlockToColor(0, 0, img_w, img_h, &black);
    }
    delete [] blur;

    return mask;
}
void LabelVolumeToSurfacesPluginInterface::Run()
{
    IbisAPI *ibisAPI = GetIbisAPI();
    Q_ASSERT(ibisAPI);
    ImageObject * image = ImageObject::SafeDownCast( ibisAPI->GetCurrentObject() );
    if( image && image->IsLabelImage() )
    {  
        // Get the range of labels
        double imageRange[2];
        image->GetImageScalarRange( imageRange );
        int minLabel = (int)floor( imageRange[ 0 ] );
        if( minLabel == 0 )
            minLabel = 1;  // Usually, label 0 is a mask in minc files
        int maxLabel = (int)floor( imageRange[ 1 ] );
        int numberOfLabels = maxLabel - minLabel + 1;

        // Compute the histogram to find out which labels really exist in the volume
        vtkImageAccumulate * histogram = vtkImageAccumulate::New();
        histogram->SetInputData( image->GetImage() );
        histogram->SetComponentExtent( 0, maxLabel, 0, 0, 0, 0 );
        histogram->SetComponentOrigin( 0, 0, 0 );
        histogram->SetComponentSpacing( 1, 1, 1 );
        histogram->Update();

        // Setup filters
        vtkDiscreteMarchingCubes * contourExtractor = vtkDiscreteMarchingCubes::New();
        contourExtractor->SetInputData( image->GetImage() );
        vtkTriangleFilter * triangleFilter = vtkTriangleFilter::New();
        triangleFilter->SetInputConnection( contourExtractor->GetOutputPort() );
        vtkStripper * stripper = vtkStripper::New();
        stripper->SetInputConnection( triangleFilter->GetOutputPort() );

        unsigned int smoothingIterations = 15;
        double passBand = 0.001;
        double featureAngle = 120.0;
        vtkWindowedSincPolyDataFilter * smoother = vtkWindowedSincPolyDataFilter::New();
        smoother->SetInputConnection( stripper->GetOutputPort() );
        smoother->SetNumberOfIterations(smoothingIterations);
        smoother->BoundarySmoothingOff();
        smoother->FeatureEdgeSmoothingOff();
        smoother->SetFeatureAngle(featureAngle);
        smoother->SetPassBand(passBand);
        smoother->NonManifoldSmoothingOn();
        smoother->NormalizeCoordinatesOn();

        IbisAPI *ibisAPI = GetIbisAPI();
        Q_ASSERT(ibisAPI);
        QProgressDialog * pd = ibisAPI->StartProgress( 100, "Extracting surfaces..." );
        QApplication::processEvents();

        for( int i = minLabel; i <= maxLabel; ++i )
        {
            // skip label if there is no voxel from this label
            double frequency = histogram->GetOutput()->GetPointData()->GetScalars()->GetTuple1(i);
            if( frequency == 0.0 )
                continue;

            contourExtractor->SetValue( 0, i );

            // Do the processing
            smoother->Update();

            // Setup a PolyDataObject with output and add it to the scene
            vtkPolyData * outCopy = vtkPolyData::New();
            outCopy->DeepCopy( smoother->GetOutput() );
            PolyDataObject * polyDataObj = PolyDataObject::New();
            QString objName = QString("Label %1").arg( i );
            polyDataObj->SetName( objName );
            polyDataObj->SetPolyData( outCopy );
            if( i < 256 )
                polyDataObj->SetColor( labelColors[i] );
            ibisAPI->AddObject( polyDataObj, image );

            // cleanup
            outCopy->Delete();
            polyDataObj->Delete();

            int progress = (int)( 100 * i / (double) numberOfLabels );
            ibisAPI->UpdateProgress( pd, progress );
            QApplication::processEvents();
        }

        ibisAPI->StopProgress( pd );

        // Cleanup
        contourExtractor->Delete();
        triangleFilter->Delete();
        stripper->Delete();
        smoother->Delete();
        histogram->Delete();
    }
    else
        QMessageBox::warning( 0, "Error!", "Current object should be a label volume" );
}
示例#16
0
int
CreateCompositeImage(CompositeParameters &params, const char *outName)
{
    // Try to read in all of the inputs.
    bool noError = true;
    int i;
    for(i = 0; i < params.nViewports && noError; ++i)
    {
        params.viewports[i]->file = new ImageObject;
        noError = params.viewports[i]->file->Read(
            params.viewports[i]->imageName);
    }
    if(!noError)
    {
        fprintf(stderr, "The following files could not be read:\n");
        for(i = 0; i < params.nViewports; ++i)
            fprintf(stderr, "\t%s\n", params.viewports[i]->imageName);
        return -3;
    }

    int startViewport = 0;
    ImageObject *output = 0;
    int width, height;
    if(strcmp(params.backgroundFile, params.viewports[0]->imageName) == 0)
    {
        startViewport = 1;
        width = params.viewports[0]->file->Width();
        height = params.viewports[0]->file->Height();
        output = params.viewports[0]->file;
    }
    else
    {
        width = params.outputSize[0];
        height = params.outputSize[1];
        output = new ImageObject(width, height);

        // Set the image's background color.
        unsigned char *cptr = output->Pixel(0,0);
        unsigned int sz = width * height;
        for(unsigned int s = 0; s < sz; ++s)
        {
            *cptr++ = params.outputBackground[0];
            *cptr++ = params.outputBackground[1];
            *cptr++ = params.outputBackground[2];
        }
    }

    // Calculate some shadow parameters based on the image size.
    int offx = int(params.shadowOffsetX * width);
    int offy = int(params.shadowOffsetY * height);
    if (offx > offy)
        offy = offx;
    else
        offx = offy;
    int blurRad = int(params.shadowBlurRadius * width);

    // Now that we have all of the images in memory and we've decided
    // which one is the background image, we should begin compositing.
    for(i = startViewport; i < params.nViewports; ++i)
    {
        int start_x = int(params.viewports[i]->coordinates[0] * width);
        int start_y = int(height - params.viewports[i]->coordinates[1] * height);

        int img_w = params.viewports[i]->file->Width();
        int img_h = params.viewports[i]->file->Height();

        if(params.viewports[i]->hasDropShadow)
        {
            ImageObject *mask = CreateDropShadowMask(params.viewports[i], 
                offx, offy, blurRad);

            if(mask != 0)
            {
                // Now that we have a drop shadow mask, let's use it to blend
                // the destination pixels with black. Values in the mask that
                // are white should be more black in the destination image.
                // Of course, we should limit the amount of black that we can
                // make a shadow.
                for(int masky = 0; masky < mask->Height(); ++masky)
                {
                    int real_y = start_y - img_h + masky;
                    for(int maskx = 0; maskx < mask->Width(); ++maskx)
                    {
                        int real_x = start_x + maskx;
                        if(real_x >= 0 && real_x < width &&
                           real_y >= 0 && real_y < height)
                        {
                            unsigned char *mask_value = mask->Pixel(maskx, masky);
                            unsigned char *dest = output->Pixel(real_x, real_y);
                            float t = (float(*mask_value) / 255.f) * 0.5;
                            float r = float(dest[0]);
                            float g = float(dest[1]);
                            float b = float(dest[2]);
                            float new_r = (1. - t) * r + t * 0.2;
                            float new_g = (1. - t) * g + t * 0.2;
                            float new_b = (1. - t) * b + t * 0.2;
                            dest[0] = (unsigned char)((int)(new_r));
                            dest[1] = (unsigned char)((int)(new_g));
                            dest[2] = (unsigned char)((int)(new_b));
                        }
                    }
                }
                delete mask;
            }
        }

        // Now that we've drawn a drop shadow, if needed, draw the image.
        if(params.viewports[i]->opaqueMode == M_OPAQUE)
        {
            for(int y = 0; y < img_h; ++y)
            {
                int real_y = start_y - img_h + y;
                for(int x = 0; x < img_w; ++x)
                {
                    int real_x = start_x + x;
                    if(real_x >= 0 && real_x < width &&
                       real_y >= 0 && real_y < height)
                    {
                        unsigned char *src = params.viewports[i]->file->Pixel(x, y);
                        unsigned char *dest = output->Pixel(real_x, real_y);

                        *dest++ = *src++;
                        *dest++ = *src++;
                        *dest = *src;
                    }
                }
            }
        }
        else if(params.viewports[i]->opaqueMode == M_TRANSPARENT)
        {
            for(int y = 0; y < img_h; ++y)
            {
                int real_y = start_y - img_h + y;
                for(int x = 0; x < img_w; ++x)
                {
                    int real_x = start_x + x;
                    if(real_x >= 0 && real_x < width &&
                       real_y >= 0 && real_y < height)
                    {
                        unsigned char *src = params.viewports[i]->file->Pixel(x, y);
                        unsigned char *dest = output->Pixel(real_x, real_y);

                        float dest_r = float(dest[0]);
                        float dest_g = float(dest[1]);
                        float dest_b = float(dest[2]);
                        float src_r = float(src[0]);
                        float src_g = float(src[1]);
                        float src_b = float(src[2]);

                        float t = params.viewports[i]->opacity;
                        float r = (1. - t) * dest_r + t * src_r;
                        float g = (1. - t) * dest_g + t * src_g;
                        float b = (1. - t) * dest_b + t * src_b;

                        *dest++ = (unsigned char)((int)r);
                        *dest++ = (unsigned char)((int)g);
                        *dest++ = (unsigned char)((int)b);
                    }
                }
            }
        }
        else if(params.viewports[i]->opaqueMode == M_COLORREPLACE)
        {
            unsigned char rr, rg, rb;
            rr = params.viewports[i]->transparentColor[0];
            rg = params.viewports[i]->transparentColor[1];
            rb = params.viewports[i]->transparentColor[2];

            for(int y = 0; y < img_h; ++y)
            {
                int real_y = start_y - img_h + y;
                for(int x = 0; x < img_w; ++x)
                {
                    int real_x = start_x + x;
                    if(real_x >= 0 && real_x < width &&
                       real_y >= 0 && real_y < height)
                    {
                        unsigned char *src = params.viewports[i]->file->Pixel(x, y);
                        unsigned char *dest = output->Pixel(real_x, real_y);

                        if(src[0] != rr || src[1] != rg || src[2] != rb)
                        {
                            *dest++ = *src++;
                            *dest++ = *src++;
                            *dest = *src;
                        }
                    }
                }
            }
        }
    }

    // Write the output image.
    output->Write(outName);

    if(startViewport == 0)
        delete output;

    return 0;
}
示例#17
0
   int process( boost::shared_ptr<Logger> qLogger, boost::shared_ptr<ProcessingSettings> qSettings, std::string sLayer, bool bVerbose, bool bLock, int epsg, std::string sImagefile, bool bFill, int& out_lod, int64& out_x0, int64& out_y0, int64& out_x1, int64& out_y1)
   {
      DataSetInfo oInfo;

      if (!ProcessingUtils::init_gdal())
      {
         qLogger->Error("gdal-data directory not found!");
         return ERROR_GDAL;
      }      

      //---------------------------------------------------------------------------
      // Retrieve ImageLayerSettings:
      std::ostringstream oss;

      std::string sImageLayerDir = FilenameUtils::DelimitPath(qSettings->GetPath()) + sLayer;
      std::string sTileDir = FilenameUtils::DelimitPath(FilenameUtils::DelimitPath(sImageLayerDir) + "tiles");

      boost::shared_ptr<ImageLayerSettings> qImageLayerSettings = ImageLayerSettings::Load(sImageLayerDir);
      if (!qImageLayerSettings)
      {
         qLogger->Error("Failed retrieving image layer settings! Make sure to create it using 'createlayer'.");
         ProcessingUtils::exit_gdal();
         return ERROR_IMAGELAYERSETTINGS;
      }

      int lod = qImageLayerSettings->GetMaxLod();
      out_lod = lod;
      int64 layerTileX0, layerTileY0, layerTileX1, layerTileY1;
      qImageLayerSettings->GetTileExtent(layerTileX0, layerTileY0, layerTileX1, layerTileY1);

      if (bVerbose)
      {
         oss << "\nImage Layer:\n";
         oss << "     name = " << qImageLayerSettings->GetLayerName() << "\n";
         oss << "   maxlod = " << lod << "\n";
         oss << "   extent = " << layerTileX0 << ", " << layerTileY0 << ", " << layerTileX1 << ", " << layerTileY1 << "\n";
      }


      //---------------------------------------------------------------------------
      boost::shared_ptr<CoordinateTransformation> qCT;
      qCT = boost::shared_ptr<CoordinateTransformation>(new CoordinateTransformation(epsg, 3785));
   
      clock_t t0,t1;
      t0 = clock();

      ProcessingUtils::RetrieveDatasetInfo(sImagefile, qCT.get(), &oInfo, bVerbose);

      if (!oInfo.bGood)
      {
         qLogger->Error("Failed retrieving info!");
      }

      if (bVerbose)
      {
         oss << "Loaded image info:\n   Image Size: w= " << oInfo.nSizeX << ", h= " << oInfo.nSizeY << "\n";
         oss << "   dest: " << oInfo.dest_lrx << ", " << oInfo.dest_lry << ", " << oInfo.dest_ulx << ", " << oInfo.dest_uly << "\n";
         qLogger->Info(oss.str());
         oss.str("");
      }

      boost::shared_ptr<MercatorQuadtree> qQuadtree = boost::shared_ptr<MercatorQuadtree>(new MercatorQuadtree());

      int64 px0, py0, px1, py1;
      qQuadtree->MercatorToPixel(oInfo.dest_ulx, oInfo.dest_uly, lod, px0, py0);
      qQuadtree->MercatorToPixel(oInfo.dest_lrx, oInfo.dest_lry, lod, px1, py1);

      int64 imageTileX0, imageTileY0, imageTileX1, imageTileY1;
      qQuadtree->PixelToTileCoord(px0, py0, imageTileX0, imageTileY0);
      qQuadtree->PixelToTileCoord(px1, py1, imageTileX1, imageTileY1);

      if (bVerbose)
      {
         oss << "\nTile Coords (image):";
         oss << "   (" << imageTileX0 << ", " << imageTileY0 << ")-(" << imageTileX1 << ", " << imageTileY1 << ")\n";
         qLogger->Info(oss.str());
         oss.str("");
      }

      // check if image is outside layer
      if (imageTileX0 > layerTileX1 || 
         imageTileY0 > layerTileY1 ||
         imageTileX1 < layerTileX0 ||
         imageTileY1 < layerTileY0)
      {
         qLogger->Info("The dataset is outside of the layer and not being added!");
         ProcessingUtils::exit_gdal();
         return 0;
      }

      // clip tiles to layer extent
      imageTileX0 = math::Max<int64>(imageTileX0, layerTileX0);
      imageTileY0 = math::Max<int64>(imageTileY0, layerTileY0);
      imageTileX1 = math::Min<int64>(imageTileX1, layerTileX1);
      imageTileY1 = math::Min<int64>(imageTileY1, layerTileY1);

      out_x0 = imageTileX0;
      out_y0 = imageTileY0;
      out_x1 = imageTileX1;
      out_y1 = imageTileY1;

      // Load image 
      boost::shared_array<unsigned char> vImage = ProcessingUtils::ImageToMemoryRGB(oInfo);
      unsigned char* pImage = vImage.get();

      if (!vImage)
      {
         qLogger->Error("Can't load image into memory!\n");
         return ERROR_NOMEMORY;
      }

      //########################################################################
      // Beacuse proj4 is not thread safe at this time, 
      // the target extents are precalculate.
      // unfortunately this can't be fixed by using OpenMP locks / critical sections

      int64 numTiles = (imageTileX1-imageTileX0+1)*(imageTileY1-imageTileY0+1);
      boost::shared_array<Anchor> vAnchor = boost::shared_array<Anchor>(new Anchor[numTiles]);
      Anchor* pAnchor = vAnchor.get();

      if (!vAnchor)
      {
         qLogger->Error("Not enough memory for target tile structure! (This is a known issue and will be fixed soon!)\n");
         return ERROR_NOMEMORY;
      }


      if (bVerbose)
      {
         oss << "\nCalculating Destination Coordinates (transformation)...";
         qLogger->Info(oss.str());
         oss.str("");
      }

      
      for (int64 xx = imageTileX0; xx <= imageTileX1; ++xx)
      {
         for (int64 yy = imageTileY0; yy <= imageTileY1; ++yy)
         {
            int64 cnt = (xx-imageTileX0)*(imageTileY1-imageTileY0+1)+yy-imageTileY0;

            std::string sQuadcode = qQuadtree->TileCoordToQuadkey(xx,yy,lod);
             double px0m, py0m, px1m, py1m;
            qQuadtree->QuadKeyToMercatorCoord(sQuadcode, px0m, py0m, px1m, py1m);

            double ulx = px0m;
            double uly = py1m;
            double lrx = px1m;
            double lry = py0m;

            double anchor_Ax = ulx; 
            double anchor_Ay = lry;
            double anchor_Bx = lrx; 
            double anchor_By = lry;
            double anchor_Cx = lrx; 
            double anchor_Cy = uly;
            double anchor_Dx = ulx; 
            double anchor_Dy = uly;

            qCT->TransformBackwards(&anchor_Ax, &anchor_Ay);
            qCT->TransformBackwards(&anchor_Bx, &anchor_By);
            qCT->TransformBackwards(&anchor_Cx, &anchor_Cy);
            qCT->TransformBackwards(&anchor_Dx, &anchor_Dy);

            pAnchor[cnt].anchor_Ax = anchor_Ax;
            pAnchor[cnt].anchor_Ay = anchor_Ay;
            pAnchor[cnt].anchor_Bx = anchor_Bx;
            pAnchor[cnt].anchor_By = anchor_By;
            pAnchor[cnt].anchor_Cx = anchor_Cx;
            pAnchor[cnt].anchor_Cy = anchor_Cy;
            pAnchor[cnt].anchor_Dx = anchor_Dx;
            pAnchor[cnt].anchor_Dy = anchor_Dy;

            cnt++;
         }
      }
      //########################################################################

      if (bVerbose)
      {
         oss << "\nCalculating Tiles";
         qLogger->Info(oss.str());
         oss.str("");
      }

      // iterate through all tiles and create them
      #pragma omp parallel for
      for (int64 xx = imageTileX0; xx <= imageTileX1; ++xx)
      {
         for (int64 yy = imageTileY0; yy <= imageTileY1; ++yy)
         {
            int64 cnt = (xx-imageTileX0)*(imageTileY1-imageTileY0+1)+yy-imageTileY0;

            boost::shared_array<unsigned char> vTile;

            std::string sQuadcode = qQuadtree->TileCoordToQuadkey(xx,yy,lod);
            std::string sTilefile = ProcessingUtils::GetTilePath(sTileDir, ".png" , lod, xx, yy);

            if (bVerbose)
            {
               std::stringstream sst;
               sst << "processing " << sQuadcode << " (" << xx << ", " << yy << ")";
               qLogger->Info(sst.str());
            }

            //---------------------------------------------------------------------
            // LOCK this tile. If this tile is currently locked 
            //     -> wait until lock is removed.

            int lockhandle = -1;
            if (bLock)
            {
               lockhandle = FileSystem::Lock(sTilefile);
            }
            else
            {
               std::cout << "WARNING: locking disabled\n";
            }

            //---------------------------------------------------------------------
            // if mode is --fill: (bFill)
            //      * load possibly existing tile into vTile
            // ...  * if there is none, clear vTile (memset 0)
            // if mode is --overwrite (bOverwrite)
            //      * load possibly existing tile into vTile
            //      * if there is none, clear vTile (memset 0)
            //      * overwrite
            //_--------------------------------------------------------------------

            // load tile:

            // tile already exists ?
            bool bCreateNew = true;

            if (FileSystem::FileExists(sTilefile))
            {
               qLogger->Info(sTilefile + " already exists, updating");
               ImageObject outputimage;
               if (ImageLoader::LoadFromDisk(Img::Format_PNG, sTilefile, Img::PixelFormat_RGBA, outputimage))
               {
                  if (outputimage.GetHeight() == tilesize && outputimage.GetWidth() == tilesize)
                  {
                     vTile = outputimage.GetRawData();
                     bCreateNew = false;
                  }
               }
            }

            if (bCreateNew)
            {
               // create new tile memory and clear to fully transparent
               vTile = boost::shared_array<unsigned char>(new unsigned char[tilesize*tilesize*4]);
               memset(vTile.get(),0,tilesize*tilesize*4);
            }

            unsigned char* pTile = vTile.get();

            // Copy image to tile:
            /*double px0m, py0m, px1m, py1m;
            qQuadtree->QuadKeyToMercatorCoord(sQuadcode, px0m, py0m, px1m, py1m);

            double ulx = px0m;
            double uly = py1m;
            double lrx = px1m;
            double lry = py0m;

            double anchor_Ax = ulx; 
            double anchor_Ay = lry;
            double anchor_Bx = lrx; 
            double anchor_By = lry;
            double anchor_Cx = lrx; 
            double anchor_Cy = uly;
            double anchor_Dx = ulx; 
            double anchor_Dy = uly;

            // avoid calculating transformation per pixel. This is done using anchor point method
           
            qCT->TransformBackwards(&anchor_Ax, &anchor_Ay);
            qCT->TransformBackwards(&anchor_Bx, &anchor_By);
            qCT->TransformBackwards(&anchor_Cx, &anchor_Cy);
            qCT->TransformBackwards(&anchor_Dx, &anchor_Dy);
            */


            double anchor_Ax = pAnchor[cnt].anchor_Ax;
            double anchor_Ay = pAnchor[cnt].anchor_Ay;
            double anchor_Bx = pAnchor[cnt].anchor_Bx;
            double anchor_By = pAnchor[cnt].anchor_By;
            double anchor_Cx = pAnchor[cnt].anchor_Cx;
            double anchor_Cy = pAnchor[cnt].anchor_Cy;
            double anchor_Dx = pAnchor[cnt].anchor_Dx;
            double anchor_Dy = pAnchor[cnt].anchor_Dy;
   
            // write current tile
            for (int ty=0;ty<tilesize;++ty)
            {
               for (int tx=0;tx<tilesize;++tx)
               {
                  double dx = (double)tx*dWanc;
                  double dy = (double)ty*dHanc;
                  double xd = (anchor_Ax*(1.0-dx)*(1.0-dy)+anchor_Bx*dx*(1.0-dy)+anchor_Dx*(1.0-dx)*dy+anchor_Cx*dx*dy);
                  double yd = (anchor_Ay*(1.0-dx)*(1.0-dy)+anchor_By*dx*(1.0-dy)+anchor_Dy*(1.0-dx)*dy+anchor_Cy*dx*dy);

                  // pixel coordinate in original image
                  double dPixelX = (oInfo.affineTransformation_inverse[0] + xd * oInfo.affineTransformation_inverse[1] + yd * oInfo.affineTransformation_inverse[2]);
                  double dPixelY = (oInfo.affineTransformation_inverse[3] + xd * oInfo.affineTransformation_inverse[4] + yd * oInfo.affineTransformation_inverse[5]);
                  unsigned char r,g,b,a;

                  // out of image -> set transparent
                  if (dPixelX<0 || dPixelX>oInfo.nSizeX ||
                     dPixelY<0 || dPixelY>oInfo.nSizeY)
                  {
                     r = g = b = a = 0;
                  }
                  else
                  {
                     // read pixel in image pImage[dPixelX, dPixelY] (biliear, bicubic or nearest neighbour)
                     // and store as r,g,b
                     _ReadImageValueBilinear(pImage, oInfo.nSizeX, oInfo.nSizeY, dPixelX, dPixelY, &r, &g, &b, &a);
                  }

                  size_t adr=4*ty*tilesize+4*tx;

                  if (a>0)
                  {
                     if (bFill)
                     {
                        if (pTile[adr+3] == 0)
                        {
                           pTile[adr+0] = r;  
                           pTile[adr+1] = g;  
                           pTile[adr+2] = b; 
                           pTile[adr+3] = a;
                        }
                     }
                     else // if (bOverwrite)
                     {
                        // currently RGB for testing purposes!
                        pTile[adr+0] = r;  
                        pTile[adr+1] = g;  
                        pTile[adr+2] = b; 
                        pTile[adr+3] = a;
                     }
                  }
               }
            }

            // save tile (pTile)
            if (bVerbose)
            {
               qLogger->Info("Storing tile: " + sTilefile);
            }

            ImageWriter::WritePNG(sTilefile, pTile, tilesize, tilesize);

            // unlock file. Other computers/processes/threads can access it again.
            FileSystem::Unlock(sTilefile, lockhandle);
         }
      }


      //---------------------------------------------------------------------------


      //---------------------------------------------------------------------------
      t1=clock();

      std::ostringstream out;
      out << "calculated in: " << double(t1-t0)/double(CLOCKS_PER_SEC) << " s \n";
      qLogger->Info(out.str());

      ProcessingUtils::exit_gdal();

      return 0;
   }
示例#18
0
void TileRenderer::Compose(std::string compositionLayerPath, std::string compositionMode, double compositionAlpha, int width, int height, mapnik::image_32* buf,int zz, int xx, int yy)
#endif
{
	std::string compositionTilePath = "";
	 // COMPOSITION MODE
	if(compositionLayerPath != "")
	{
		//std::stringstream str;
		//str<< compositionLayerPath << "/tiles/" << zoom << "/" << x << "/" << y << ".png";
		ImageObject compImg;

		// find possible composition
		  int compositionLevel = 1;
		  double modX = 1;
		  double modY = 1;
		  if(compositionLayerPath != "")
		  {
			for(size_t h = zz; h > 0; h--)
			{
				std::stringstream ss;
				ss << compositionLayerPath <<  h << "/" << (math::Floor((double)xx/(compositionLevel > 0? compositionLevel:1))) << "/" << (math::Floor((double)yy/(compositionLevel > 0? compositionLevel:1))) << ".png";
				if(FileSystem::FileExists(ss.str()))
				{
					compositionTilePath = ss.str();
					double dx = ((double)xx/compositionLevel);
					double dy = ((double)yy/compositionLevel);
					int ix = int(math::Floor(dx));
					int iy = int(math::Floor(dy));
					modX =  dx - ix;
					modY =  dy - iy;
					break;
				}
				compositionLevel *= 2;
			}
		  }
		
		if(ImageLoader::LoadFromDisk(Img::Format_PNG, compositionTilePath, Img::PixelFormat_RGBA,compImg))
		{
			if(compositionMode == "unify" || compositionMode == "unifyopaque")
			{
				for(size_t y = 0; y < height; y++)
				{
					for(size_t x = 0; x < width; x++)
					{
						unsigned char comp[4];
						int adr = 4*y*width+4*x;
						if(compositionLevel > 0)
						{
							double pX = ((double)x/compositionLevel)+(modX*width);
							double pY = ((double)y/compositionLevel)+(modY*height);
							compImg.ReadPixelBilinear4(pX,pY,comp[0],comp[1],comp[2],comp[3]);
						}
						else
						{
							compImg.ReadPixel4(x,y,comp[0],comp[1],comp[2],comp[3]);
						}
						
						unsigned int compInt = 0x00000000;
						compInt = compInt | comp[3];
						compInt = (compInt << 8) | comp[2];
						compInt = (compInt << 8) | comp[1];
						compInt = (compInt << 8) | comp[0];
						unsigned char alpha;
						if(compositionMode == "unifyopaque")
						{
							alpha = buf->raw_data()[adr+3] > 0 ? 255 : 0;
						}
						else
						{
							alpha = buf->raw_data()[adr+3];
						}
						//buf.setPixel(x,y,compInt);
						buf->blendPixel(x,y,compInt,(int)alpha);
					}
				}
			}
			else if(compositionMode == "overlay")
			{
				for(size_t y = 0; y < height; y++)
				{
					for(size_t x = 0; x < width; x++)
					{
						unsigned char comp[4];
						int adr = 4*y*width+4*x;
						if(compositionLevel > 0)
						{
							int pX = (x/compositionLevel)+(modX*width);
							int pY = (y/compositionLevel)+(modY*height);
							compImg.ReadPixelBilinear4(pX,pY,comp[0],comp[1],comp[2],comp[3]);
						}
						else
						{
							compImg.ReadPixel4(x,y,comp[0],comp[1],comp[2],comp[3]);
						}
						unsigned int compInt = 0x00000000;
						compInt = compInt | comp[3];
						compInt = (compInt << 8) | comp[2];
						compInt = (compInt << 8) | comp[1];
						compInt = (compInt << 8) | comp[0];
						unsigned char alpha = buf->raw_data()[adr+3];
						//buf.setPixel(x,y,compInt);
						buf->blendPixel(x,y,compInt,(int)comp[3]);
					}
				}
			}
		}
	}
}
示例#19
0
void SDLMouseCursor::load( ImageObject& img, const int& hotspotX, const int& hotspotY, const Color& transparentColor, const Color& invertColor )
{
	if ( imageIsSystemCursor( &img ) ) {

		Uint8* data = new Uint8[ (int)ceil( (double)(img.width() * img.height()) / 8 ) ];
		Uint8* mask = new Uint8[ (int)ceil( (double)(img.width() * img.height()) / 8 ) ];

		int bit = 1;
		int i = -1;

		Color black( 0, 0, 0 );
		Color white( 255, 255, 255 );
		//cout << "Cursor:" << endl;
		for( int y = 0; y < img.height(); y++ ) {
			for( int x = 0; x < img.width(); x++ ) {
				Color c = img.getPixel( x, y );

				if ( bit == 128 ) {
					bit = 64;
				}
				else if ( bit == 64 )
					bit = 32;
				else if ( bit == 32 )
					bit = 16;
				else if ( bit == 16 )
					bit = 8;
				else if ( bit == 8 )
					bit = 4;
				else if ( bit == 4 )
					bit = 2;
				else if ( bit == 2 )
					bit = 1;
				else if ( bit == 1 ) {
					bit = 128;
					i++;
					data[i] = 0;
					mask[i] = 0;
				}

				if ( c == white ) {
					//cout << ".";
					mask[i] |= bit;
				} else if ( c == black ) {
					//cout << "X";
					data[i] |= bit;
					mask[i] |= bit;
				} else if ( c == invertColor ) {
					//cout << "0";
					data[i] |= bit;
				} else {
					//cout << " ";
				}
			}
			//cout << endl;
		}
		pCursor = SDL_CreateCursor( data, mask, img.width(), img.height(), hotspotX, hotspotY );

		delete[] mask;
		delete[] data;

	} else {
	}
}