Create a mask from difference between two images (iPhone)

前端 未结 5 1798
臣服心动
臣服心动 2020-12-28 23:06

How can I detect the difference between 2 images, creating a mask of the area that\'s different in order to process the area that\'s common to both images (gaussian blur for

5条回答
  •  遥遥无期
    2020-12-28 23:52

    I think the simplest way to do this would be to use a difference blend mode. The following code is based on code I use in CKImageAdditions.

    + (UIImage *) differenceOfImage:(UIImage *)top withImage:(UIImage *)bottom {
        CGImageRef topRef = [top CGImage];
        CGImageRef bottomRef = [bottom CGImage];
    
        // Dimensions
        CGRect bottomFrame = CGRectMake(0, 0, CGImageGetWidth(bottomRef), CGImageGetHeight(bottomRef));
        CGRect topFrame = CGRectMake(0, 0, CGImageGetWidth(topRef), CGImageGetHeight(topRef));
        CGRect renderFrame = CGRectIntegral(CGRectUnion(bottomFrame, topFrame));
    
        // Create context
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        if(colorSpace == NULL) {
            printf("Error allocating color space.\n");
            return NULL;
        }
    
        CGContextRef context = CGBitmapContextCreate(NULL,
                                                     renderFrame.size.width,
                                                     renderFrame.size.height,
                                                     8,
                                                     renderFrame.size.width * 4,
                                                     colorSpace,
                                                     kCGImageAlphaPremultipliedLast);
        CGColorSpaceRelease(colorSpace);
    
        if(context == NULL) {
            printf("Context not created!\n");
            return NULL;
        }
    
        // Draw images
        CGContextSetBlendMode(context, kCGBlendModeNormal);
        CGContextDrawImage(context, CGRectOffset(bottomFrame, -renderFrame.origin.x, -renderFrame.origin.y), bottomRef);
        CGContextSetBlendMode(context, kCGBlendModeDifference);
        CGContextDrawImage(context, CGRectOffset(topFrame, -renderFrame.origin.x, -renderFrame.origin.y), topRef);
    
        // Create image from context
        CGImageRef imageRef = CGBitmapContextCreateImage(context);
        UIImage * image = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
    
        CGContextRelease(context);
    
        return image;
    }
    

提交回复
热议问题