#include "imageoperationbeauty.h"
#include "../include/common.h"
#include <QDebug>


ImageOperationBeauty::ImageOperationBeauty(QImage *origin, QStack<QImage> *stackImage)
{
    m_origin = origin;
    m_stackImage = stackImage;
    isInterupt = false;
}

void ImageOperationBeauty::ImageOP(){
    QImage res = imageCopy(m_origin, m_stackImage);
    beauty(res);
    emit finished();
}

void ImageOperationBeauty::beauty(const QImage inputImage)
{
    // 将图像转换为灰度图
    QImage grayImage = inputImage.convertToFormat(QImage::Format_Grayscale8);

    // 创建输出图像
    QImage outputImage = grayImage;

    int width = grayImage.width();
    int height = grayImage.height();

    // 计算图像的平均亮度
    int sum = 0;
    for (int y = 0; y < height; ++y)
    {
        for (int x = 0; x < width; ++x)
        {
            QRgb pixel = grayImage.pixel(x, y);
            sum += qGray(pixel);
        }
    }
    int averageBrightness = sum / (width * height);

    // 提高图像的对比度和锐度，并根据平均亮度调整亮度
    for (int y = 1; y < height - 1; ++y)
    {
        for (int x = 1; x < width - 1; ++x)
        {
            // 获取中心像素值
            QRgb centerPixel = grayImage.pixel(x, y);
            int centerGray = qGray(centerPixel);

            // 计算邻近像素的平均灰度值
            sum = 0;
            for (int j = -1; j <= 1; ++j)
            {
                for (int i = -1; i <= 1; ++i)
                {
                    QRgb pixel = grayImage.pixel(x + i, y + j);
                    sum += qGray(pixel);
                }
            }
            int averageGray = sum / 9;

            // 计算高反差保留滤波后的像素值
            int newGray = qBound(0, centerGray + (centerGray - averageGray), 255);

            // 根据平均亮度调整亮度
            int brightness = qBound(0, newGray + (newGray - averageBrightness) * 2, 255);

            // 猜想补全模糊的字体内容
            if (centerGray < averageGray)
            {
                // 补全模糊的字体内容
                brightness = qBound(0, centerGray + qAbs(centerGray - averageGray) * 2, 255);
            }

            // USM锐化
            float usmAmount = 0.8; // USM锐化的强度，可以调整此值
            int usmGray = centerGray + static_cast<int>((centerGray - brightness) * usmAmount);
            brightness = qBound(0, usmGray, 255);

            // 增强对比度
            float contrastAmount = 1.5;
            brightness = qBound(0, static_cast<int>((brightness -128) * contrastAmount) + 128, 255);

            // 更新像素值
            outputImage.setPixel(x, y, qRgb(brightness, brightness, brightness));
        }
    }

    outputImage.save(ScanningPicture);
}


