DEV Community

maocheng.xia
maocheng.xia

Posted on

Implementation of a simple image quality evaluation method based on Java and code implementation

#ai

Image description

`import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageQualityEvaluation {

    // 
    public static double calculateMSE(BufferedImage original, BufferedImage compressed) {
        int width = original.getWidth();
        int height = original.getHeight();
        double mse = 0.0;

        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                int originalPixel = original.getRGB(i, j);
                int compressedPixel = compressed.getRGB(i, j);

                // 
                int originalRed = (originalPixel >> 16) & 0xff;
                int originalGreen = (originalPixel >> 8) & 0xff;
                int originalBlue = originalPixel & 0xff;

                int compressedRed = (compressedPixel >> 16) & 0xff;
                int compressedGreen = (compressedPixel >> 8) & 0xff;
                int compressedBlue = compressedPixel & 0xff;

                // 
                mse += Math.pow(originalRed - compressedRed, 2);
                mse += Math.pow(originalGreen - compressedGreen, 2);
                mse += Math.pow(originalBlue - compressedBlue, 2);
            }
        }

        // 
        mse /= (width * height * 3);  // 
        return mse;
    }

    // 
    public static double calculatePSNR(double mse) {
        int MAX_PIXEL_VALUE = 255;  // 
        return 10 * Math.log10(Math.pow(MAX_PIXEL_VALUE, 2) / mse);
    }

    public static void main(String[] args) throws IOException {
        // 
        BufferedImage originalImage = ImageIO.read(new File("original_image.png"));
        BufferedImage compressedImage = ImageIO.read(new File("compressed_image.png"));

        // 
        double mse = calculateMSE(originalImage, compressedImage);
        System.out.println("MSE: " + mse);

        //
        double psnr = calculatePSNR(mse);
        System.out.println("PSNR: " + psnr + " dB");
    }
}`
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)