2014年11月16日 星期日

[Java] 圖片像素比對

public static void ImageCompare(String sample, String file)
            throws IOException {
        double total, result = 0;
        int record = 0;

        // ----open file----
        //開啟檔案
        BufferedImage image1 = ImageIO.read(new File(
                "/Users/zhangnaiyuan/Documents/screenshot/" + sample));
        BufferedImage image2 = ImageIO.read(new File(
                "/Users/zhangnaiyuan/Documents/screenshot/" + file));
        // -----------------

        // ----pixel array-----
        //取得圖片的長寬,C是暫存
        // A=sample, B=screenshot, C=result
        int[][] imageA = new int[image1.getWidth()][image1.getHeight()];
        int[][] imageB = new int[image1.getWidth()][image1.getHeight()];
        int[][] imageC = new int[image1.getWidth()][image1.getHeight()];
        // --------------------

        // -----save all sample's pixel to array----
        //把每個像素存進陣列
        for (int x = 0; x < image1.getWidth(); x++) {
            for (int y = 0; y < image1.getHeight(); y++) {
                imageA[x][y] = image1.getRGB(x, y);
            }
        }
        // -----------------------------------------

        // -----save all screenshot's pixel to array----
        //把每個像素存進陣列
        for (int x = 0; x < image2.getWidth(); x++) {
            for (int y = 0; y < image2.getHeight(); y++) {
                imageB[x][y] = image2.getRGB(x, y);
            }
        }
        // -----------------------------------------------

        // ----find the different of 2 images-----
        //比較AB兩陣列,將結果存進C陣列,如果一樣相減會是0
        for (int x = 0; x < image1.getWidth(); x++) {
            for (int y = 0; y < image1.getHeight(); y++) {
                imageC[x][y] = imageA[x][y] - imageB[x][y];
            }
        }
        // ---------------------------------------

        // ----record the different's number----
        //算出結果C陣列有幾個不同的像素(結果不是0)
        for (int x = 0; x < image1.getWidth(); x++) {
            for (int y = 0; y < image1.getHeight(); y++) {
                if (imageC[x][y] != 0)
                    record += 1;
            }
        }
        // --------------------------------------

        // count result
        total = (image1.getWidth()) * (image1.getHeight());
        result = (record / total) * 100;
        // output the result
        System.out.println("The different of 2 images is: " + result + "%");
    }

沒有留言:

張貼留言