我基本上想要从iPhone或iPad 2相机中获取两张图片并将它们相互比较,以查看它们是否非常相似。显然由于光照等因素,图像永远不会完全相同,所以我希望检查大约90%的兼容性。
我在这里看到的所有类似问题都不是针对iOS的,或者是用于在图像中定位对象。我只想看看两张图片是否相似。
谢谢。
float numDifferences = 0.0f;
float totalCompares = width * height / 100.0f;
for (int yCoord = 0; yCoord < height; yCoord += 10) {
for (int xCoord = 0; xCoord < width; xCoord += 10) {
int img1RGB[] = [image1 getRGBForX:xCoord andY: yCoord];
int img2RGB[] = [image2 getRGBForX:xCoord andY: yCoord];
if (abs(img1RGB[0] - img2RGB[0]) > 25 || abs(img1RGB[1] - img2RGB[1]) > 25 || abs(img1RGB[2] - img2RGB[2]) > 25) {
//one or more pixel components differs by 10% or more
numDifferences++;
}
}
}
if (numDifferences / totalCompares <= 0.1f) {
//images are at least 90% identical 90% of the time
}
else {
//images are less than 90% identical 90% of the time
}
基于aroth的想法,这是我的完整实现。它检查一些随机像素是否相同。对于我所需要的功能来说,它运行得非常流畅。
- (bool)isTheImage:(UIImage *)image1 apparentlyEqualToImage:(UIImage *)image2 accordingToRandomPixelsPer1:(float)pixelsPer1
{
if (!CGSizeEqualToSize(image1.size, image2.size))
{
return false;
}
int pixelsWidth = CGImageGetWidth(image1.CGImage);
int pixelsHeight = CGImageGetHeight(image1.CGImage);
int pixelsToCompare = pixelsWidth * pixelsHeight * pixelsPer1;
uint32_t pixel1;
CGContextRef context1 = CGBitmapContextCreate(&pixel1, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
uint32_t pixel2;
CGContextRef context2 = CGBitmapContextCreate(&pixel2, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
bool isEqual = true;
for (int i = 0; i < pixelsToCompare; i++)
{
int pixelX = arc4random() % pixelsWidth;
int pixelY = arc4random() % pixelsHeight;
CGContextDrawImage(context1, CGRectMake(-pixelX, -pixelY, pixelsWidth, pixelsHeight), image1.CGImage);
CGContextDrawImage(context2, CGRectMake(-pixelX, -pixelY, pixelsWidth, pixelsHeight), image2.CGImage);
if (pixel1 != pixel2)
{
isEqual = false;
break;
}
}
CGContextRelease(context1);
CGContextRelease(context2);
return isEqual;
}
用法:
[self isTheImage:image1 apparentlyEqualToImage:image2
accordingToRandomPixelsPer1:0.001]; // Use a value between 0.0001 and 0.005
getRGBForX:andY:
的调用填充。它们将包含给定坐标处像素通道值(即红色分量的int,绿色的int和蓝色的int)。在比较中使用数组索引只是为了简洁起见。如果您喜欢,您可以轻松地执行类似于int img1Red = img1RGB [0];
和int img1Green = img1RGB [1];
等操作。 - arothgetRGBForX
的? - Jesse Onolemen