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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay