首页 > 解决方案 > iOS GPUImage - 如何替换图像中 R、G 和 B 值超过某个值的所有像素?

问题描述

请多多包涵,因为我对 iOS 和 GPUImage 也很陌生。我试图弄清楚如何用另一个 R、G、B 值替换图像中 R、G 和 B 值超过某个值的所有像素。

因此,假设我需要替换所有具有以下特征的像素:

R value of over 20 with 100, 
G value of over 100 with 200,
B value of over 40 with 0

我可以用老派的方式做到这一点,但速度很慢,我需要尽快做到:

- (CGImageRef)processImageOldSchoolWay:(CGImageRef)image
{
    uint8_t *bufptr;

    int width  = (int)CGImageGetWidth( image );
    int height = (int)CGImageGetHeight( image );

    // allocate memory for pixels
    uint32_t *pixels = calloc( width * height, sizeof(uint32_t) );

    // create a context with RGBA pixels
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate( pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast );

    // draw the image into the context
    CGContextDrawImage( context, CGRectMake( 0, 0, width, height ), image );

    // manipulate the pixels
    bufptr = (uint8_t *)pixels;
    for (NSInteger y = 0; y < height; y++){
        for (NSInteger x = 0; x < width; x++ )
        {

            if (bufptr[3]>=(int)self.redslider.value) {
                bufptr[3]=100;
            }
            if (bufptr[2]>=(int)self.greenslider.value) {
                bufptr[2]=200;
            }
            if (bufptr[1]>=(int)self.blueslider.value) {
                bufptr[1]=0;
            }


            bufptr += 4;
        }
    }


    // create a new CGImage from the context with modified pixels
    CGImageRef resultImage = CGBitmapContextCreateImage(context);

    // release resources to free up memory
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    free(pixels);

    return resultImage;
}

所以我遇到了 GPUImage,它似乎具有非常好的性能。我想我需要使用GPUImageColorMatrixFilter,但我似乎无法理解它们是如何colorMatrix形成的。

例如,对于棕褐色,我可以通过查看示例来使其工作:

GPUImagePicture *gpuImage = [[GPUImagePicture alloc] initWithImage:image];

GPUImageColorMatrixFilter *conversionFilter = [[GPUImageColorMatrixFilter alloc] init];
conversionFilter.colorMatrix = (GPUMatrix4x4){
    {0.3588, 0.7044, 0.1368, 0.0},
    {0.2990, 0.5870, 0.1140, 0.0},
    {0.2392, 0.4696, 0.0912 ,0.0},
    {0,0,0,1.0},
};

[gpuImage addTarget:conversionFilter];
[conversionFilter useNextFrameForImageCapture];
[gpuImage processImage];
UIImage *toReturn = [conversionFilter imageFromCurrentFramebufferWithOrientation:0];
return toReturn;

我似乎无法理解conversionFilter.colorMatrix线的形成。为什么在该矩阵中使用这些值?在需要用其他值替换阈值的情况下,如何获得满足我需要的值?

标签: iosiphoneimage-processinguiimagegpuimage

解决方案


推荐阅读