#include "gauss.h"

Gauss::Gauss(QImage img, double sgm)
{
    this->img=img;
    this->sgm=sgm;
}

void Gauss::countSize(void)
{
    int i=sgm*10;
    if (i%2==0) i++;
    size=i;
}
void Gauss::countArr(void)
{
    double k=1/(sgm*sqrt(2*M_PI));
    int smesh=(size-1)/2;
    for (int i=0; i<=(size-1); i++)
        arr[i]=k*exp(-(i-smesh)*(i-smesh)/(2*sgm*sgm));

    double sum=0;
    for (int i=0; i<=(size-1); i++) sum+=arr[i];
    for (int i=0; i<=(size-1); i++) arr[i]=arr[i]/sum;

}

QImage Gauss::go(void)
{
    QRgb clr;
    int width = img.width();
    int height = img.height();

    QImage out(img);


    countSize();
    countArr();
    double tmpR[size],tmpG[size],tmpB[size],r,g,b;
    int smesh=(size-1)/2;

    for (int i=smesh;i<width-smesh;i++)
        for (int j=smesh;j<height-smesh;j++)
        {
            for (int k=0; k<=(size-1); k++)
                 tmpR[k]=tmpG[k]=tmpB[k]=0;

             for (int k=0; k<=(size-1); k++)
                 for (int l=0; l<=(size-1); l++)
                 {
                     clr=img.pixel(i-smesh+l,j-smesh+k);
                     tmpR[k]+=qRed(clr)*arr[l];
                     tmpG[k]+=qGreen(clr)*arr[l];
                     tmpB[k]+=qBlue(clr)*arr[l];
                 }
             r=g=b=0;
             for (int k=0; k<=(size-1); k++)
             {
                 r+=tmpR[k]*arr[k];
                 g+=tmpG[k]*arr[k];
                 b+=tmpB[k]*arr[k];
             }

             if (r>255) r=255;
             if (r<0) r=0;
             if (g>255) g=255;
             if (g<0) g=0;
             if (b>255) b=255;
             if (b<0) b=0;
             out.setPixel(i,j,qRgb(r,g,b));
        }
       return out;

}
QImage Gauss::sharp(double alpha)
{
    QImage gau=go();
    QImage out(img);
    QRgb clr,clrg;
    int width = img.width();
    int height = img.height();
    int smesh=(size-1)/2;
    for (int i=smesh;i<width-smesh;i++)
        for (int j=smesh;j<height-smesh;j++)
        {
             clr=img.pixel(i,j);
             clrg=gau.pixel(i,j);
             int r=(1+alpha)*qRed(clr)-alpha*qRed(clrg);
             int g=(1+alpha)*qGreen(clr)-alpha*qGreen(clrg);
             int b=(1+alpha)*qBlue(clr)-alpha*qBlue(clrg);

             if (r>255) r=255;
             if (r<0) r=0;
             if (g>255) g=255;
             if (g<0) g=0;
             if (b>255) b=255;
             if (b<0) b=0;
             out.setPixel(i,j,qRgb(r,g,b));
        }
    return out;
}

