[英]Struggling to set the average brightness of a grayscale image
我在通過 JUnit 測試時遇到問題,我知道該測試已正確實施,但我不確定它失敗的原因。 下面的代碼應該抓取每個像素(像素 = 數組 exe 中的一個點:2dArray[0][0])。 每個像素都有一個亮度值,我的方法的目標是將整個陣列中的每個像素亮度值更改為 127 或至少接近它。
下面是我似乎無法通過的有問題的 JUnit 測試以及 JUnit 測試正在測試的方法的當前代碼。 下面的方法將通過大多數 JUnit 測試,但在運行 JUnit 測試的 assertEquals() 部分時失敗。 現在,當我使用 System.out.println() 和 normalizedImage.averageBrightness() 時,它是正確的,並表示圖像的平均亮度為 127 或接近它。 我覺得這很奇怪,現在已經研究這個問題很長一段時間了,我不確定還能嘗試什么。 任何幫助,將不勝感激。
JUnit 測試:
@Test
void normalized() {
var smallNorm = smallSquare.normalized();
assertEquals(smallNorm.averageBrightness(), 127, 127 * .001);
var scale = 127 / 2.5;
var expectedNorm = new GrayscaleImage(new double[][] { { scale, 2 * scale }, { 3 * scale, 4 * scale } });
for (var row = 0; row < 2; row++) {
for (var col = 0; col < 2; col++) {
assertEquals(smallNorm.getPixel(col, row), expectedNorm.getPixel(col, row), expectedNorm.getPixel(col, row) * .001, "pixel at row: " + row + " col: " + col + " incorrect");
}
}
}
我當前的代碼:
/**
* Return a new GrayScale image where the average new average brightness is 127
* To do this, uniformly scale each pixel (ie, multiply each imageData entry by the same value)
* Due to rounding, the new average brightness will not be 127 exactly, but should be very close
* The original image should not be modified
* @return a GrayScale image with pixel data uniformly rescaled so that its averageBrightness() is 127
*/
public GrayscaleImage normalized() {
// First we make a 2D array that is the same size as the original image.
double[][] normalized2DArray = new double[imageData[0].length][imageData.length];
// Then we figure out what we need to multiple the pixel by to make sure our average brightness is equal to 127
double scaleFactor = 127 / averageBrightness();
// Then we will set the brightness of the specified pixel below.
for (int y = 0; y < imageData[0].length; y++) {
for (int x = 0; x < imageData.length; x++) {
double newPixelValue = getPixel(y, x) * scaleFactor;
normalized2DArray[y][x] = newPixelValue;
}
}
// We will then turn the 2DArray into a GrayscaleImage
GrayscaleImage normalizedImage = new GrayscaleImage(normalized2DArray);
System.out.println(normalizedImage.averageBrightness());
return normalizedImage;
}
我能夠修復我的代碼問題是 normalized2DArray[y][x] = newPixelValue; 實際上應該是 normalized2DArray[x][y] = newPixelValue;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.