/**
* Process the image and return the number of pure red pixels in it.
*/
- (NSUInteger) processImage: (UIImage*) image
{
NSUInteger numberOfRedPixels = 0;
// Allocate a buffer big enough to hold all the pixels
struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
if (pixels != nil)
{
// Create a new bitmap
CGContextRef context = CGBitmapContextCreate(
(void*) pixels,
image.size.width,
image.size.height,
8,
image.size.width * 4,
CGImageGetColorSpace(image.CGImage),
kCGImageAlphaPremultipliedLast
);
if (context != NULL)
{
// Draw the image in the bitmap
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);
// Now that we have the image drawn in our own buffer, we can loop over the pixels to
// process it. This simple case simply counts all pixels that have a pure red component.
// There are probably more efficient and interesting ways to do this. But the important
// part is that the pixels buffer can be read directly.
NSUInteger numberOfPixels = image.size.width * image.size.height;
int cnt = 0;
int width = image.size.width;
//pixels+=2;
while (numberOfPixels > 10+image.size.width) {
if (((pixels-1)->a==0 || (pixels+1)->a==0 || (pixels+width)->a==0 || (pixels+width-1)->a==0 || (pixels+width+1)->a==0 || (pixels-width)->a==0 || (pixels-width-1)->a==0 || (pixels-width+1)->a==0) && (pixels)->a > 0) {
numberOfRedPixels++;
(pixels)->r = 0;
(pixels)->g = 255;
(pixels)->b = 0;
(pixels)->a = 255;
}
cnt++;
pixels++;
numberOfPixels--;
}
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
[imageView setImage:myImage];
if(myImage != nil){
//UIImage *myImage = [UIImage imageWithCGImage:imageRef];
NSData* imageData = UIImageJPEGRepresentation(myImage, 1.0);
NSLog(@"Writing image to file:!");
[imageData writeToFile:@"/Users/lee/playground/resultImage.jpg" atomically:NO];
}
}
//free(pixels);
}
return numberOfRedPixels;
}
- (IBAction) processImage
{
//[self init];
NSUInteger numberOfRedPixels = [self processImage: inputImage];
label_.text = [NSString stringWithFormat: @"There are %d transparent pixels in the image", numberOfRedPixels];
}
This is just a sample code for tracing transparent outlines of images in iphone OS examples, This is just my personal notes. If you happened to stumble on this, feel free to comment, so I can explain this further.
No comments:
Post a Comment