[vtkusers] Fast conversion from vtkImageData to QImage?

Jeff Baumes jeff.baumes at kitware.com
Fri Jan 29 08:51:29 EST 2010


On Fri, Jan 29, 2010 at 6:09 AM, Prashanth Udupa
<prashanth.udupa at gmail.com> wrote:
> Hi All,
> I have an application where I need to convert vtkImageData to QImage. I am
> using the following code for this.
> Assumptions: vtkImageData is 2D. dim[0] is width, dim[1] is height. Scalars
> associated with the image is always VTK_UNSIGNED_CHAR type.
> QImage ConvertToQImage(vtkImageData* imageData)
> {
>     int dim[3];
>     imageData->GetDimensions(dim);
>     if(dim[0]*dim[1]*dim[2] == 0)
>         return QImage();
>     vtkUnsignedCharArray* scalars
>         =
> vtkUnsignedCharArray::SafeDownCast(imageData->GetPointData()->GetScalars());
>     if(!scalars)
>         return QImage();
>     QImage qImage(dim[0], dim[1], QImage::Format_ARGB32);
>     vtkIdType tupleIndex=0;
>     unsigned char tuple[] = {0, 0, 0, 0};
>     for(int j=0; j<dim[1]; j++)
>     {
>         for(int i=0; i<dim[0]; i++)
>         {
>             int r=0, g=0, b=0, a=0;
>             scalars->GetTupleValue(tupleIndex++, tuple);
>             switch(scalars->GetNumberOfComponents())
>             {
>             case 1:
>                 r = g = b = tuple[0];
>                 a = 255;
>                 break;
>             case 2:
>                 r = g = b = tuple[0];
>                 a = tuple[1];
>                 break;
>             case 3:
>                 r = tuple[0];
>                 g = tuple[1];
>                 b = tuple[2];
>                 a = 255;
>                 break;
>             case 4:
>                 r = tuple[0];
>                 g = tuple[1];
>                 b = tuple[2];
>                 a = tuple[3];
>                 break;
>             }
>             QRgb color = qRgba(r, g, b, a);
>             qImage.setPixel(i, j, color);
>         }
>     }
>     return qImage;
> }
> I was wondering if there was a faster way to do this. If anyone has hints
> for me, please do share.

Did you take a look at

http://www.vtk.org/doc/nightly/html/classvtkQImageToImageSource.html

It's the reverse process from what you want, but code there may (or
may not) be useful to you. If you get a nice implementation of it, it
could be nice to have an analogous class in VTK (perhaps an algorithm
with no conventional VTK data object as output called
vtkImageToQImage, where GetOutput() returns the QImage).

Jeff



More information about the vtkusers mailing list