Question

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?

Was it helpful?

Solution

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);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top