Stucky dithering as custom CIKernel does not work

271 Views Asked by At

I'm trying to implement Stucky dithering (error diffusion) as a CIKernel but I am a bit lost. I don't find a way to debug the filter (I m new to CIKernel). Here is what I have came up so far, but the kernel does not compile, plus, I wonder how I could store the spreaded error to the destination pixels. Help welcome. Is there a tool/way to trace or debug the code?

   float mDiffCoef = [
        0,    0     0,    8/42, 4/42,
        2/42, 4/42, 8/42, 4/42, 2/42,
        1/42, 2/42, 4/42, 2/42, 1/42
    ];

    kernel vec4 dither(__sample image) {

        vec2 coord = samplerCoord(image);
        vec4 pixel = sample(image, coord);

        // decompress pixel into rgb
        float red   = pixel.r;

        float color = 0;
        if (red >= 127) color = 255;

        float err = red - color;

        // Spread the error according to the matrix
        for (int x = -2; x <= 2; x++) {
            for (int y = 0; y <= 3; y++) {
                vec2 workingSpaceCoordinate = destCoord() + vec2(x,y);
                vec2 imageSpaceCoordinate = samplerTransform(image, workingSpaceCoordinate);
                vec3 color = sample(image, imageSpaceCoordinate).rgb;
                color += err * mDiffCoef[(2+x)+5*y];
            }
        }

        return vec4(color, 1.0);
    }

[Updated code to remove syntax errors]:

kernel vec4 dither(__sample image) {

    float mDiffCoef[3 * 5];
    int i = 0;
    mDiffCoef[i++] = 0.;
    mDiffCoef[i++] = 0.;
    mDiffCoef[i++] = 0.;
    mDiffCoef[i++] = 8./42.;
    mDiffCoef[i++] = 4./42.;
    mDiffCoef[i++] = 2./42.;
    mDiffCoef[i++] = 4./42.;
    mDiffCoef[i++] = 8./42.;
    mDiffCoef[i++] = 4./42.;
    mDiffCoef[i++] = 2./42.;
    mDiffCoef[i++] = 1./42.;
    mDiffCoef[i++] = 2./42.;
    mDiffCoef[i++] = 4./42.;
    mDiffCoef[i++] = 2./42.;
    mDiffCoef[i++] = 1./42.;

    vec2 coord = samplerCoord(image);
    vec4 pixel = sample(image, coord);

    // decompress pixel into rgb
    float red   = pixel.r;

    float c = 0.;
    if (red >= 127.) c = 255.;

    float err = red - c;
    float color = 0.;

    // Spread the error according to the matrix
    for (int x = -2; x <= 2; x++) {
        for (int y = 0; y < 3; y++) {
            vec2 workingSpaceCoordinate = destCoord() + vec2(x,y);
            vec2 imageSpaceCoordinate = samplerTransform(image, workingSpaceCoordinate);

            float c = sample(image, imageSpaceCoordinate).r; //gb;
            color = c + err * mDiffCoef[(2+x)+5*y];
        }
    }


    color = clamp(color, 0., 255.);
    return vec4(255., color, color, 1.);

My main issue is how can I write the outpu pixel buffers by cumulating portion of value from the error diffusion?

0

There are 0 best solutions below