Question

I need to convert QImage to an array where each pixel is represented by three integers(channels). So I'm trying to achieve this with fillowing code:

void Processor::init(QImage *image){
QColor* c = new QColor();

int i,j;
int local_ind;

x = image->width();
y = image->height();

if(this->img!=NULL)
    delete [] this->img;
this->img = new int[ x * y * 3];

for( i = 0 ; i < y ; i++ )
    for( j = 0 ; j < x ; j++ ){
        c->setRgb(image->pixel(j, i));
        local_ind = i * x + j * 3;
        this->img[local_ind + 0] = c->red();
        this->img[local_ind + 1] = c->green();
        this->img[local_ind + 2] = c->blue();
    }
delete c;
}

void Processor::flush(QImage *image){

QColor* c = new QColor();
QRgb color;

int i, j;
int local_ind;

for( i = 0 ; i < y ; i++ )
    for( j = 0 ; j < x ; j++ ){

        local_ind = i * x + j * 3;
        color = qRgb(this->img[local_ind + 0],
                     this->img[local_ind + 1],
                     this->img[local_ind + 2]);

        image->setPixel(j, i, color);
    }

delete c;
}

Both functions are seem to work fine, as I can see via debugger, but when I call them one after the other (just copy info from QImage to array and backwards), result is a bit wierd. Whole image consists of three repeated images: a third of original image (blue, green and red channels of source image). I guess I just used setPixel in a wrong way so the format of QImage is not observed or smth.

I use QImage RGB32 format, if it really important here.

PS. Sorry for my English, corrections are welcome)

Was it helpful?

Solution

The issue is that you are using

 local_ind = i * x + j * 3;

But in your buffer each pixel take 3 bytes. So the you need to use instead

 ( i * x + j ) * 3

btw: Why are you using x for height and y for width? This is not intuitive.

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