2
0

More than 3 years have passed since last update.

JavaでBufferdImageのRGB誤差が指定割合以内か確認する静的関数

Posted at

背景

  • 画像の変換処理がうまくいっているかのテストで、RGB値が多少変わってしまう現象と遭遇した
  • 等価判定ができなかったので、どのくらいの誤差を割合で許容するか。という作りにした。
  • ニッチなニーズかもしれないが、誰かの一助になることを願ってます。

動作確認環境

  • Java8
  • JUnit4

Code

    /**
     * ピクセルごとのRed,Green,Blueの色の要素値をAssertします。
     * 
     * 要素値の差(±)は 増減 5% まで許容してます。
     */
    static void assertImages(BufferedImage actual, BufferedImage expected) {
        assertThat("比較している画像サイズが異なります(縦)", actual.getHeight(), is(expected.getHeight()));
        assertThat("比較している画像サイズが異なります(横)", actual.getWidth(), is(expected.getWidth()));

        // 誤差を許容するパーセント
        final int ACCEPTABLE_PERCENTAGE = 5;
        // 誤差を許容する数値(±)
        final int ACCEPTABLE_DIFFERENCE = 255 * ACCEPTABLE_PERCENTAGE / 100 / 2;

        int width = actual.getWidth();
        int height = actual.getHeight();
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                Color actualColor = new Color(actual.getRGB(x, y));
                Color expectedColor = new Color(expected.getRGB(x, y));

                assertThat("色の要素値が許容範囲(±" + ACCEPTABLE_PERCENTAGE + "%)を超えてます:Red",
                        (double) actualColor.getRed(),
                        is(closeTo((double) expectedColor.getRed(), ACCEPTABLE_DIFFERENCE)));

                assertThat("色の要素値が許容範囲(±" + ACCEPTABLE_PERCENTAGE + "%)を超えてます:Green",
                        (double) actualColor.getGreen(),
                        is(closeTo((double) expectedColor.getGreen(), ACCEPTABLE_DIFFERENCE)));

                assertThat("色の要素値が許容範囲(±" + ACCEPTABLE_PERCENTAGE + "%)を超えてます:Blue",
                        (double) actualColor.getBlue(),
                        is(closeTo((double) expectedColor.getBlue(), ACCEPTABLE_DIFFERENCE)));
            }
        }
    }
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0