Victor
Victor

Reputation: 327

QImage is getting an error eventhough I'm preventing it

I'm playing around with QImage and QGraphics view. I was trying to calculate the euclidean distance between two images, I know it's slow but it doesn't matter, and i'm getting this error

ASSERT failure in QVector<T>::at: "index out of range", file c:\work\build\qt5_workdir\w\s\qtbase\include\qtcore\../../src/corelib/tools/qvector.h, line 377

whenever I got through these lines

for(int row = 0; row < 128 ; row++){
    for(int col = 0; col < 128; col++){
        if(this->Imagem->valid(row, col)){
            qDebug() << "1";
            this->Imagem->pixel(row, col);
        }
        else
            qDebug() << "2";
    }
}

It always outputs "1" on terminal and crashes. I'm declaring the image with

this->Imagem = new QImage(128, 128, QImage::Format_Indexed8);
this->Imagem->fill(QColor(Qt::black).rgb());

and i'm even checking if the points are within the boundaries of the image and it clearly is.

Upvotes: 1

Views: 1066

Answers (2)

kefir500
kefir500

Reputation: 4414

Format_Indexed8 uses the manually defined color table where each index represents a color. You have to set the color table for your image before manipulating its pixels:

QVector<QRgb> color_table;
for (int i = 0; i < 256; ++i) {
    color_table.push_back(qRgb(i, i, i)); // Fill the color table with B&W shades
}
Imagem->setColorTable(color_table);

Or you can manually set each index for the current color table:

Imagem->setColorCount(4); // How many colors will be used for this image
Imagem->setColor(0, qRgb(255, 0, 0));   // Set index #0 to red
Imagem->setColor(1, qRgb(0, 0, 255));   // Set index #1 to blue
Imagem->setColor(2, qRgb(0, 0, 0));     // Set index #2 to black
Imagem->setColor(3, qRgb(255, 255, 0)); // Set index #3 to yellow
Imagem->fill(1); // Fill the image with color at index #1 (blue)

As you can see, Format_Indexed8 pixel values represent not RGB colors but the index values (which in turn represent the colors you set in the color table).

If you don't want to deal with color tables, you can simply use another format such as Format_RGB32.

Upvotes: 2

6502
6502

Reputation: 114579

Note that QImage::valid expects (col, row), not (row, col) (i.e. the first parameter is X, the second Y); this shouldn't however make a difference for a 128x128 image.

May be the object you are accessing has already been destroyed (for example because your handling of ownership is buggy), but it's hard to tell without seeing more code.

Upvotes: 0

Related Questions