Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast image manipulation

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?

like image 425
sleeping.ninja Avatar asked Dec 10 '22 08:12

sleeping.ninja


1 Answers

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);
}
like image 156
Arlen Avatar answered Dec 26 '22 00:12

Arlen