以防万一有人遇到这个问题(并且在散列事物方面不是非常有经验,尤其是像图像这样的东西),这是一个非常简单的解决方案,我用于散列 QPixmap 并将它们输入查找表以供以后比较:
qint32 HashClass::hashPixmap(QPixmap pix)
{
QImage image = pix.toImage();
qint32 hash = 0;
for(int y = 0; y < image.height(); y++)
{
for(int x = 0; x < image.width(); x++)
{
QRgb pixel = image.pixel(x,y);
hash += pixel;
hash += (hash << 10);
hash ^= (hash >> 6);
}
}
return hash;
}
这是散列函数本身(如果您希望减少冲突,可以将其散列到 qint64 中)。如您所见,我将像素图转换为 QImage,并简单地遍历其尺寸并对每个像素执行一次非常简单的哈希并返回最终结果。有很多方法可以改进此实现(请参阅此问题的其他答案),但这是需要做的基本要点。
OP 提到了他将如何使用此散列函数然后构造一个查找表以供以后比较图像。这需要一个非常简单的查找初始化函数——像这样:
void HashClass::initializeImageLookupTable()
{
imageTable.insert(hashPixmap(QPixmap(":/Image_Path1.png")), "ImageKey1");
imageTable.insert(hashPixmap(QPixmap(":/Image_Path2.png")), "ImageKey2");
imageTable.insert(hashPixmap(QPixmap(":/Image_Path3.png")), "ImageKey2");
// Etc...
}
我在这里使用了一个名为 imageTable 的 QMap,它需要在类中声明:
QMap<qint32, QString> imageTable;
然后,最后,当您想要将图像与查找表中的图像进行比较时(即:“在我知道的图像中,这是什么图像,这是特定图像吗?”),您只需调用图像上的散列函数(我假设它也将是一个 QPixmap)并且返回的 QString 值将允许您弄清楚这一点。这样的事情会起作用:
void HashClass::compareImage(const QPixmap& pixmap)
{
QString value = imageTable[hashPixmap(pixmap)];
// Do whatever needs to be done with the QString value and pixmap after this point.
}
就是这样。我希望这对某人有所帮助——它会为我节省一些时间,尽管我很高兴有解决这个问题的经验。