Last active
August 29, 2015 13:58
-
-
Save unixpickle/10203741 to your computer and use it in GitHub Desktop.
Bitmap Average using Accelerate.framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.m | |
// BitmapAverage | |
// | |
// Created by Alex Nichol on 4/8/14. | |
// Copyright (c) 2014 Alex Nichol. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#import <Accelerate/Accelerate.h> | |
#import "ANImageBitmapRep.h" | |
int main(int argc, const char * argv[]) { | |
@autoreleasepool { | |
NSLog(@"start"); | |
// load our images | |
NSImage * img1 = [[NSImage alloc] initWithContentsOfFile:@"/Users/alex/Desktop/foobar.png"]; | |
NSImage * img2 = [[NSImage alloc] initWithContentsOfFile:@"/Users/alex/Desktop/foobar.jpg"]; | |
ANImageBitmapRep * irep1 = [[ANImageBitmapRep alloc] initWithImage:img1]; | |
ANImageBitmapRep * irep2 = [[ANImageBitmapRep alloc] initWithImage:img2]; | |
// the output bitmap rep is created using a size because we will be outputting raw pixels to it | |
ANImageBitmapRep * dest = [[ANImageBitmapRep alloc] initWithSize:irep1.bitmapSize]; | |
long pixelCount = irep1.bitmapSize.x * irep1.bitmapSize.y; | |
// our input buffer needs to have the ARGB (in float from) of BOTH images (thus 8 components per pixel) | |
float * buffer = malloc(sizeof(float) * (pixelCount * 8)); | |
// our output buffer is an image, so only 4 components per pixel needed | |
float * result = malloc(sizeof(float) * (pixelCount * 4)); | |
// cast the first bitmap into floats | |
vDSP_vfltu8(irep1.bitmapData, 1, buffer, 1, pixelCount * 4); | |
// same for the second | |
vDSP_vfltu8(irep2.bitmapData, 1, &buffer[pixelCount * 4], 1, pixelCount * 4); | |
// matrix to average the two vectors | |
float leftMatrix[] = { | |
0.5f, 0.5f | |
}; | |
vDSP_mmul(leftMatrix, 1, buffer, 1, result, 1, 1, pixelCount * 4, 2); | |
free(buffer); | |
// use another vectorized cast to get our output back into bytes | |
vDSP_vfixu8(result, 1, dest.bitmapData, 1, pixelCount * 4); | |
free(result); | |
NSLog(@"done averaging"); | |
// tell the output we modified its buffer | |
[dest setNeedsUpdate:YES]; | |
[[dest.image TIFFRepresentation] writeToFile:@"/Users/alex/Desktop/merged.tiff" atomically:YES]; | |
NSLog(@"done write to TIFF"); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment