下面我有一个功能,需要两个图像imageOne
和imageTwo
。这些图像将逐个像素地扫描,以确定它们的“百分比匹配”我想知道以下功能是否对此有效。它是手工编写的,所以可能存在一些问题,但总的来说我认为它是可靠的。感谢您的任何和所有输入。
添加了getColorSimilarity()
功能。
double MainWindow::imageMatchPercent(QImage imageOne, QImage imageTwo)
{
QImage compOne = imageOne;
QImage compTwo = imageTwo;
if (imageOne.isNull())
{
QMessageBox::warning(this, "Image Loading Error", "Image One is empty.");
return (double)999.999;
}
if (imageTwo.isNull())
{
QMessageBox::warning(this, "Image Loading Error: ", "Image Two is empty.");
return (double)999.999;
}
if (imageOne.size() != imageTwo.size())
{
QSize imageOneSize = imageOne.size();
QSize imageTwoSize = imageTwo.size();
averageSize = getAverageSize(imageOneSize, imageTwoSize);
}
else
averageSize = imageOne.size();
int correctValues = 0;
int currentValue = 0;
int totalPixels = averageSize.width() * averageSize.height();
for (int x = 0; x < averageSize.width(); x++)
{
for (int y = 0; y < averageSize.height(); y++)
{
QColor pixelOneColor = compOne.pixel(x, y);
QColor pixelTwoColor = compTwo.pixel(x, y);
double colorDifference = getColorSimilarity(pixelOneColor, pixelTwoColor);
if (pixelOneColor.alpha() == 255 && pixelTwoColor.alpha() == 255)
{
if (colorDifference >= 75)
correctValues += 1;
currentValue += 1;
}
}
}
double percent = ((double)correctValues / (double)totalPixels) * (double)100.00;
return percent;
}
double MainWindow::getColorSimilarity(QColor colorOne, QColor colorTwo)
{
int redOne = colorOne.red();
int greenOne = colorOne.green();
int blueOne = colorOne.blue();
int redTwo = colorTwo.red();
int greenTwo = colorTwo.green();
int blueTwo = colorTwo.blue();
int redDif = abs(redOne - redTwo);
int greenDif = abs(greenOne - greenTwo);
int blueDif = abs(blueOne - blueTwo);
double percentRedDiff = (double)redDif / 255;
double percentGreenDiff = (double)greenDif / 255;
double percentBlueDiff = (double)blueDif / 255;
return 100 - (((percentRedDiff + percentGreenDiff + percentBlueDiff) / 3) * 100);
}
请注意用于迭代图像的averageSize对象,现在设置的方式,如果两个图像的大小不同,那么你的averageSize.height或.width将大于其中一个维度。你的一个图像,如果图像存储为数组,你可能会出现分段错误,我对QImage不太熟悉所以它可能没问题,但如果它将你的图像存储为一个数组,它可能会超出界限你写的。
这似乎是比较两个图像的最有效方式。我不确定Qt是否具有多线程支持,但是如果你想让处理速度更快,你可以将图像划分为象限并让每个线程按顺序处理每个像素。