GPUImage icon indicating copy to clipboard operation
GPUImage copied to clipboard

Is there a correct way to switch between filters?

Open jim-rhoades opened this issue 14 years ago • 18 comments

In my app I regularly switch between image filters to take still photos with different effects applied.

When first launching the app there are no problems with taking photos... but after I switch to a different filter, the GPUImageView occasionally blanks out after I take the photo (like it's no longer receiving video data from the camera).

Once I switch filters again, the GPUImageView correctly displays video.

It's possible that I'm just not switching between the filters in a safe way. I do something (sort of) similar to this to switch between image filters... removing all targets from both the filter and stillCamera before adding new ones:

- (void)switchFilters {

    [filter removeAllTargets];
    [stillCamera removeAllTargets];

    // if using the toon filter, switch to black and white
    if (self.currentFilter == kImageFilterToon) {

        self.currentFilter = kImageFilterBlackAndWhite;

        filter = [[GPUImageSaturationFilter alloc] init];
        [(GPUImageSaturationFilter *)filter setSaturation:0.0];
    }

    // if using the black and white filter, switch to sketch
    else if (self.currentFilter == kImageFilterBlackAndWhite) {

        self.currentFilter = kImageFilterSketch;

        filter = [[GPUImageSketchFilter alloc] init];
        [(GPUImageSketchFilter *)filter setTexelHeight:(1.0 / 1024.0)];
        [(GPUImageSketchFilter *)filter setTexelWidth:(1.0 / 768.0)];
    }

    // if using the sketch filter, switch to toon
    else if (self.currentFilter == kImageFilterSketch) {

        self.currentFilter = kImageFilterToon;

        filter = [[GPUImageSmoothToonFilter alloc] init];
    }

    [filter prepareForImageCapture];

    [stillCamera addTarget:filter];
    GPUImageView *filterView = (GPUImageView *)self.view;
    [filter addTarget:filterView];
}

I suppose [filter removeAllTargets] doesn't really matter, since the filter gets replaced anyways... but just setting the filter to nil there doesn't fix anything either.

Am I doing something wrong?

This archive contains a modified version of the SimplePhotoFilter example (in "Examples > SimplePhotoFilter with filter switching"), that adds a "Switch Filters" button if anybody wants to test it out. Again, the problem only happens occasionally, and only after switching from one filter to another (so you might have to switch filters a couple of times and take 10 - 20 photos before the screen blanks out):

http://dl.dropbox.com/u/2349787/gpuimage_filterswitch.zip

Thanks for any help.

jim-rhoades avatar May 14 '12 17:05 jim-rhoades

+1, I've also been noticing that the feed sometimes goes blank when attempting to switch filters on the go. I'm doing very similar things to you although I'm also using the following two methods:

[stillCamera startCameraCapture];
[stillCamera stopCameraCapture];

joshholat avatar May 14 '12 19:05 joshholat

Good to know it's not just me. ;)

I wasn't using startCameraCapture / stopCameraCapture due to the delay it adds in switching... though in my real app I do have:

[stillCamera pauseCameraCapture];
[stillCamera resumeCameraCapture];

... just so it's not in the middle of processing frames when the filter switch happens (though it doesn't seem to really matter).

jim-rhoades avatar May 14 '12 20:05 jim-rhoades

I wasn't aware those methods existed. Nice! They actually speed up changing between filters quite a bit compared to what I was using. They don't fix the black issue, though.

joshholat avatar May 15 '12 02:05 joshholat

Yeah, I haven't done a lot to stabilize filter changes happening on a live stream. My focus was to get things operational first, then fast, then add out capabilities as people needed them. As you've seen, error checking and overall robustness of the framework to changes hasn't been as much of a focus yet.

For the black screen cases, could you insert a little logging into the filter rendering code (inside -renderToTextureWithVertices might be a good place) to see if frame updates indeed weren't being passed along the chain? That might give a clue as to whether a disconnection like that was the cause, or if it was due to a broken framebuffer somewhere along the line.

BradLarson avatar May 15 '12 04:05 BradLarson

Brad, I added the following logging to the method you talked about in GPUImageFilter.m. I got all sorts of logging of the first and last NSLog statement even when seeing the black instead of the filter.

- (void)renderToTextureWithVertices:(const GLfloat *)vertices textureCoordinates:(const GLfloat *)textureCoordinates sourceTexture:(GLuint)sourceTexture;
{
    NSLog(@"Begin Rendering To Texture With Vertices");
    if (self.preventRendering)
    {
        NSLog(@"Rendering Prevented!");
        return;
    }

    [GPUImageOpenGLESContext useImageProcessingContext];
    [self setFilterFBO];

    [filterProgram use];

    glClearColor(backgroundColorRed, backgroundColorGreen, backgroundColorBlue, backgroundColorAlpha);
    glClear(GL_COLOR_BUFFER_BIT);

    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D, sourceTexture);

    glUniform1i(filterInputTextureUniform, 2);  

    glVertexAttribPointer(filterPositionAttribute, 2, GL_FLOAT, 0, 0, vertices);
    glVertexAttribPointer(filterTextureCoordinateAttribute, 2, GL_FLOAT, 0, 0, textureCoordinates);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    NSLog(@"End Rendering To Texture With Vertices");
}

joshholat avatar May 15 '12 14:05 joshholat

I tried logging a few different things within -renderToTextureWithVertices:

NSLog(@"vertices: %f, %f, %f, %f, %f, %f, %f, %f", vertices[0], vertices[1], vertices[2], vertices[3], vertices[4], vertices[5], vertices[6], vertices[7]);
NSLog(@"textureCoordinates: %f, %f, %f, %f, %f, %f, %f, %f", textureCoordinates[0], textureCoordinates[1], textureCoordinates[2], textureCoordinates[3], textureCoordinates[4], textureCoordinates[5], textureCoordinates[6], textureCoordinates[7]);

if (!filterFramebuffer) {
    NSLog(@"no frame buffer");
}

if (!filterSourceTexture) {
    NSLog(@"no filterSourceTexture");
}

if (!sourceTexture) {
    NSLog(@"no sourceTexture");
}

NSLog(@"sizeOfFBO: %f, %f", self.sizeOfFBO.width, self.sizeOfFBO.height);

Nothing seemed abnormal with that... nothing was nil, and the sizes/coordinates/etc were the same before and after the GPUImageView went blank (after taking a photo).

When switching filters, the filterFrameBuffer is nil for a moment, but I think that's normal.

I'll see if I can figure out anything else to test later today.

jim-rhoades avatar May 15 '12 18:05 jim-rhoades

After some more playing around today, it appears as if it could have to do with prepareImageForCapture when using a GPUImageFilterGroup.

For instance, when I don't use prepareImageForCapture after setting up a GPUImageFilterGroup, the first image I take (and any other images) comes out fine. However, if I do call prepareImageForCapture, it comes out just black (when saved to device) and also causes the GPUImageStillCamera view to go black.

That being said, when I don't call prepareImageForCapture (the successful case above) but then switch filters and try to take a picture with the second filter, the same black issue is caused.

I call the following methods before and after changing filters:

// Called before changing
- (void)turnOffCamera {
    [stillCamera removeAllTargets];
    [stillCamera pauseCameraCapture];
    [filter removeAllTargets];
    [filter release];
}

// Called after changing
- (void)turnOnCamera {
    //[filter prepareForImageCapture];
    [stillCamera addTarget:filter];
    GPUImageView *filterView = (GPUImageView *)self.view;
    [filter addTarget:filterView];
    [stillCamera resumeCameraCapture];  
}

joshholat avatar May 16 '12 19:05 joshholat

Also, calling stopCameraCapture and startCameraCapture after each photo is taken doesn't appear to fix the problem.

joshholat avatar May 17 '12 02:05 joshholat

A couple more data points after doing further testing, which may or may not help narrow this down:

In the example project I posted, the blanked out GPUImageView actually only ever happens when using the GPUImageSmoothToonFilter. If you take a photo while using the sketch filter, or saturation filter everything is fine.

I also noticed that the GPUImageSmoothToonFilter is the only one of the three that gets passed through -renderToTextureWithVertices more than one time when taking a photo.

When I log this inside of -renderToTextureWithVertices:

if (self.sizeOfFBO.width > 640 || self.sizeOfFBO.height > 852) {
    NSLog(@"sizeOfFBO: %f, %f", self.sizeOfFBO.width, self.sizeOfFBO.height);
}

... it gets output twice due to the way GPUImageSmoothToonFilter is built:

2012-05-19 00:20:09.450 SimplePhotoFilter[12193:707] sizeOfFBO: 2448.000000, 3264.000000
2012-05-19 00:20:09.792 SimplePhotoFilter[12193:707] sizeOfFBO: 2448.000000, 3264.000000

I added a couple more filters to be sure, and the GPUImageView never blanks out on filters that only pass through -renderToTextureWithVertices once.

That may also help explain why the problem happens when chaining filters, or using filter groups - as the large photo sized texture is passed through multiple times.

Out of curiosity, I modified GPUImageStillCamera to force it to process at a maximum size of 1024 pixels, (similar to shrinking images for the iPhone 4), but the problem still occurs.

EDIT: An updated version of that project: http://dl.dropbox.com/u/2349787/gpuimage_filterswitch2.zip

jim-rhoades avatar May 19 '12 04:05 jim-rhoades

i get the same issue, how to fix it?

vinxu avatar May 25 '12 10:05 vinxu

Hi first ,thanks BradLarson , you done a very awesome project !! , it is GPUImage !!!

about this ,I found a resolve ,you must send prepareImageCapture selector on all filters which

you want to change.

like this :

@"lomo_mask_1.png"] smoothlyScaleOutput:YES];

        [filter prepareForImageCapture];
        [soft prepareForImageCapture];
        [filter addTarget:soft];
        [source addTarget:soft];
        [source prepareForImageCapture];
        [source processImage];

        array = [NSArray arrayWithObjects:filter, soft,nil];

        [filter release];
        [soft release];
        [source release];

I am a chinese so ,my English is poor ,sorry about that.

fangyuxi avatar May 25 '12 18:05 fangyuxi

another , if someone want to achieve curve tools (like photoshop ), you could use above code

this program need one to ten control point ,and it can output an array,you can use this array

fill the "ToneCurve"'s toneCurveByteArray ,then ,you can see the same effect with ps.

and with a "SoftLightBlend" and an image ,i can achieve path and instagram 's all filter effect.

fangyuxi avatar May 25 '12 18:05 fangyuxi

@fangyuxi's fix worked for me! Close this?

joshholat avatar May 29 '12 14:05 joshholat

Calling "prepareForImageCapture" on all filters in a chain clears up the issue for me too.

For filters that are built on top of others, like the GPUImageSmoothToonFilter filter, I think something more may need to be done... though I guess you could probably just build a custom filter based on that, and use "prepareForImageCapture" inside the filters init method?

- (id)init;
{
    if (!(self = [super init]))
    {
        return nil;
    }

    // First pass: apply a variable Gaussian blur
    blurFilter = [[GPUImageGaussianBlurFilter alloc] init];
    [blurFilter prepareForImageCapture];
    [self addFilter:blurFilter];

    // Second pass: run the Sobel edge detection on this blurred image, along with a posterization effect
    toonFilter = [[GPUImageToonFilter alloc] init];
    [toonFilter prepareForImageCapture];
    [self addFilter:toonFilter];

    // Texture location 0 needs to be the sharp image for both the blur and the second stage processing
    [blurFilter addTarget:toonFilter];

    self.initialFilters = [NSArray arrayWithObject:blurFilter];
    self.terminalFilter = toonFilter;

    self.blurSize = 0.5;
    self.threshold = 0.2;
    self.quantizationLevels = 10.0;

    return self;
}

I'm not actually using that filter anyways (other than in that test app). The issue is fixed as far as I'm concerned - I'll go ahead and close it.

jim-rhoades avatar May 29 '12 15:05 jim-rhoades

The black image issue should finally be fixed in the latest code in the repository. There was an internal issue with not updating the output textures appropriately. This seems to have fixed things for everybody, without having to resort to the -prepareForImageCapture hack.

BradLarson avatar Jul 25 '12 16:07 BradLarson

" The black image issue should finally be fixed " I get last code from repository. But this problem still exists. I change the filter. but the picture in 70/100% of trials, appear black. :(

imodeveloper avatar Aug 13 '12 12:08 imodeveloper

@imodveloper Make sure you're removing targets on both ends of the filter before re-adding it. I have dynamic switching that works 100% of the time after the patch (was 50/50 before).

iamcam avatar Aug 13 '12 16:08 iamcam

thanks , this things realy work

imodeveloper avatar Aug 13 '12 17:08 imodeveloper