#include "bin_gradient.h"
using namespace std;

BinarizationGradient::BinarizationGradient(PNM* img) :
    Transformation(img)
{
}

BinarizationGradient::BinarizationGradient(PNM* img, ImageViewer* iv) :
    Transformation(img, iv)
{
}

PNM* BinarizationGradient::transform()
{
    int width = image->width();
    int height = image->height();

    PNM* newImage = new PNM(width, height, QImage::Format_Mono);

    // Create variables
    // The pixel value at point (i,j)
    float I=0;

    // The first component of the gradient at point (i,j)
    float Gx=0;

    // The second component of the gradient at point (i,j)
    float Gy=0;


    for (int x=0; x < width; x++)
    {
        for(int y=0; y < height; y++)
        {
            // Get current pixel value
            QRgb pixel = image->pixel(x, y);
            I = qGray(pixel);

            // Calculate Gx
            Gx = Gx + (I * qGray(image->pixel(x+1, y)) - I * qGray(image->pixel(x-1, y)));

            //Calculate Gy
            Gy = Gy + (I * qGray(image->pixel(x, y+1)) - I * qGray(image->pixel(x, y-1)));
        }
    }

    // Calculate T
    float T = (max(Gx, Gy) * I) / max(Gx, Gy);

    // Iterate over pixels
    for (int x=0; x < width; x++)
    {
        for (int y=0; y < height; y++)
        {
            // Get current pixel
            QRgb pixel = image->pixel(x, y);
            if(qGray(pixel) > T)
            {
                newImage->setPixel(x, y, Qt::color1);
            }
            else
            {
                newImage->setPixel(x, y, Qt::color0);
            }
        }
    }

    return newImage;
}