gpt4 book ai didi

javascript - 色彩平衡公式添加过多的白色

转载 作者:行者123 更新时间:2023-11-29 18:50:57 25 4
gpt4 key购买 nike

我正在尝试编写色彩平衡,但我在数学方面遇到了一些困难。我在 Wikipedia 上找到了这个公式

Color Balance Formula

我所做的如下:

  1. 获取所有红色、绿色和蓝色的单独总和
  2. 获取每个红色、绿色和蓝色 channel 的平均值
  3. 最后,我将公式应用于每个像素的每个 channel ,并将其设置回 Canvas 上的 ImageData
    • (255/col.red) * avgRed
    • (255/col.green) * avgGreen
    • (255/col.blue) * avgBlue

看起来像这样:

function averageColor() {

let sumRed = 0, sumGreen = 0, sumBlue = 0
let pixels = 0

// Get the sum of each color
this.eachColor((col, idx) => {
sumRed += col.red
sumBlue += col.blue
sumGreen += col.green
pixels++
})

// Get the averages of each channel
let avgRed = sumRed / pixels
let avgGreen = sumGreen / pixels
let avgBlue = sumBlue / pixels

// Replace each color in the image
this.eachColor((col, idx) => {
this.setColorAtIndex(idx, color.rgb(
(255 / col.red) * avgRed,
(255 / col.green) * avgGreen,
(255 / col.blue) * avgBlue
))
})

}

这是上面看到的两个函数(this._dta 是来自 ImageData.dataUint8ClampedArray):

function eachColor(callback) {
for (let i = 0, n = this._dta.length; i < n; i += 4) {
callback(this.getColorAtIndex(i), i)
}
}

function setColorAtIndex(index, color) {
this._dta[index] = color.red
this._dta[index + 1] = color.green
this._dta[index + 2] = color.blue
this._dta[index + 3] = color.alpha
}

function getColorAtIndex(index) {
return color.rgb(this._dta[index], this._dta[index + 1], this._dta[index + 2], this._dta[index + 3])
}

当我应用过滤器时,这是之前和之后的样子,你可以看到有太多的白色。我的公式有什么问题?

之前的例子

Color Balance Before

之后的例子

Color Balance After

最佳答案

您不想乘以平均值。您想要缩放平均值,以便最大值为 255。这实质上是假装平均颜色应该是灰色,然后缩放。因此,如果您的平均值是 [133.54055621951161, 133.85785501369506, 95.50769969447687] 那么白色可能是:

let avg = [133.54055621951161, 133.85785501369506, 95.50769969447687]
let max = Math.max(...avg)
let white = avg.map(c => 255 * c / max)
console.log(white)

一旦你有了它,你就可以用它通过公式来缩放它(在实践中你应该 Gamma 校正这个变换(srgb Gamma 大约是 2.2,倒数大约是 .45:

 data[i]     = (255/white[0]) ** .45 *  data[i] ;     // red
data[i + 1] = (255/white[1]) ** .45 * data[i+1]; // green
data[i + 2] = (255/white[2]) ** .45 * data[i+2] // blue

您可以看到,所有这一切都按照 [255, 255, 255]/whitepoint 的比率缩放所有内容,这取决于接近灰色的平均值。在这种情况下,它可以很好地去除黄色色偏。

这是我在转换后的样子:

之前

enter image description here

之后

enter image description here

关于javascript - 色彩平衡公式添加过多的白色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51372779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com