4

I have an array 10X10 with values between 1 to 10. Now say I want to give each value a unique color (Say 1 gets blue 2 gets red etc). I'm using qt qimage to represent the image. Here's what I'm doing

read array from disk. store in a[10][10]
generate a hash table in which each value in the array has a corresponding qRGB
for entire array
    get value (say a[0][0])
    search hashtable, get equivalent qRGB
    image.setPixel(coord,qRGB)

Is this the fastest way I can do this? I have a big image, scanning each pixel, searching its value in a hash table, setting pixel is a bit slow. Is there a faster way?

nabulke
  • 11,025
  • 13
  • 65
  • 114
sleeping.ninja
  • 607
  • 1
  • 10
  • 21

2 Answers2

10

There is indeed a faster way: Create an array of unsigned chars and modify the pixels values directly. Then create a QImage from this array. Calling setPixel() is very expensive.

unsigned char* buffer_;
buffer_ = new unsigned char[4 * w * h];
//...


for(int i = 0; i < h; i++){
 for(int j = 0; j < w; j++){

  unsigned char r, g, b;
  //...

  buffer_[4 * (i * w + j)    ] = r;
  buffer_[4 * (i * w + j) + 1] = g;
  buffer_[4 * (i * w + j) + 2] = b;
 }
}

That's for QImage::format_RGB32 and your paintEvent() would look something like this:

void paintEvent(QPaintEvent* event){
//...
QImage image(buffer_, w, h, QImage::Format_RGB32);
painter.drawImage(QPoint(0, 0), image);
}
Arlen
  • 6,641
  • 4
  • 29
  • 61
  • 2
    Thanks. A second approach would be to use the QImage scanLine function which returns a pointer to QImage pixel data. Once you have this pointer you can directly edit the pixel values which are in QRgb format -> 0xAARRGGBB – sleeping.ninja May 24 '11 at 11:11
4

If you have only 10 different colors you don't need to use hash table. Simple array would be sufficient. You don't need a[10][10] array either. Just call image.setPixel as you are reading it from disk.

If you have many different colors store them as RGB values instead of indexes. You can read all data at once and create your image with QImage ( uchar * data, int width, int height, Format format ). It will be much faster than setting each pixel individually.

Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65
  • Unfortunately I can't replace the existing indexes with rgb values. And I can't predict the number of colors being used. It can range anywhere from 1 color to 2^32 colors. A better solution? – sleeping.ninja May 22 '11 at 04:40
  • @sleeping.ninja it's hard to tell without knowing what exactly are you doing. If you just need different colors, map indexes directly to RGB. If you need them to be visually different use some hash function. If you need to map them in some specific way and it's slower than getting them from hash table, I don't know what can you do. – Piotr Praszmo May 22 '11 at 10:20