Question

I'm writing an application that requires me to store pixel data from the device's camera and compare the pixels to a previous video frame.

Here is the method that is giving me problems:

-(UIImage *)detectMotion:(CGImageRef)imageRef
{
    UIImage *newImage = nil;

    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = malloc(height * width * 4);
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent,     bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

    // this is the problem loop
    for(int i = 0; i < width * height * 4; i += 4) {

        int gray = 0.216 * rawData[i] + 0.715 * rawData[i + 1] + 0.0722 * rawData[i + 2];

        rawData[i] = gray;
        rawData[i + 1] = gray;
        rawData[i + 2] = gray;
        rawData[i + 3] = 255;

        int grayDelta = abs(gray - prevFrameRawData[i / 4]);

        int newColor = 0;
        if (sqrt(grayDelta * grayDelta * 2) >= 60) {
            newColor = 255;
        }

        rawData[i] = newColor;
        rawData[i + 1] = newColor;
        rawData[i + 2] = newColor;
        rawData[i + 3] = 255;

        prevFrameRawData[i / 4] = gray;
   }

   CGImageRef newCGImage = CGBitmapContextCreateImage(context);
   newImage = [UIImage imageWithCGImage:newCGImage];
   CGImageRelease(newCGImage);

   CGContextRelease(context);

   free(rawData);
}

Note: prevFrameRawData is malloc'd in the class' init method, then freed in the dealloc method.

After doing some testing I figured out that I don't receive the warning if I don't assign any values into the memory blocks.

I thought that when you assign a value like

 rawData[i] = value

that it just overwrites that spot in memory.

All of this low level c stuff is new to me, hope you guys can help.

Was it helpful?

Solution

Turns out we were creating an extra CGImageRef in another method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top