QIimage收到错误,即使我阻止了它

QImage is getting an error eventhough I'm preventing it

本文关键字:错误 QIimage      更新时间:2023-10-16

我在玩QImages和QGraphics视图。我试图计算两张图像之间的欧氏距离,我知道这很慢,但这无关紧要,我得到了这个错误

ASSERT failure in QVector<T>::at: "index out of range", file c:workbuildqt5_workdirwsqtbaseincludeqtcore../../src/corelib/tools/qvector.h, line 377

每当我通过这些线路

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

它总是在终端上输出"1"并崩溃。我用申报图像

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

我甚至在检查这些点是否在图像的边界内,而且很清楚。

Format_Indexed8使用手动定义的颜色表,其中每个索引表示一种颜色。在操作图像像素之前,您必须设置图像的颜色表:

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

或者您可以手动设置当前颜色表的每个索引:

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)

如您所见,Format_Indexed8像素值表示而不是RGB颜色,而是索引值(进而表示您在颜色表中设置的颜色(。

如果不想处理颜色表,可以简单地使用另一种格式,如format_RGB32

注意,QImage::valid需要(col, row),而不是(row, col)(即第一个参数是X,第二个参数是Y(;然而,对于128x128的图像来说,这不应该有什么不同。

可能是您正在访问的对象已经被销毁(例如,因为您对所有权的处理有缺陷(,但如果没有看到更多的代码,很难判断。