曾經有一個圖像可能具有alpha透明度,覆蓋在白色背景和黑色背景上。我可以訪問這兩個結果圖像,但不是原始圖像,我想檢索原始圖像。使用ImageMagick從兩個合成圖像中檢索原始蒙版
我已經寫了一些Ruby代碼來做到這一點,但是,我認爲只是在Ruby中的本質,它並不像它需要的那樣快。這是基本的邏輯,逐個像素迭代:
if pixel_on_black == pixel_on_white
# Matching pixels indicate 100% opacity in the original.
original_pixel = pixel_on_black
elsif color_on_black == BLACK && color_on_white == WHITE
# Black on black and white on white indicate 0% opacity in the original.
original_pixel = TRANSPARENT
else
# Since it's not one of the simple cases, then we'll do some math.
# Fancy algebra tells us the following. (MAX_VALUE is the largest value
# a channel can have. So, in most cases, 255.)
# First, find the alpha value. This equation follows from the equations
# for composing on black and composing on white.
alpha = pixel_on_black.red - pixel_on_white.red + MAX_VALUE
# Now that we know the alpha value, undo its multiplicative effect on the
# pixel on black. By dividing. Ta da.
alpha_ratio = alpha/MAX_VALUE
original_pixel = Pixel.new
original_pixel.red = pixel_on_black.red /alpha_ratio
original_pixel.green = pixel_on_black.green/alpha_ratio
original_pixel.blue = pixel_on_black.blue/alpha_ratio
original_pixel.alpha = alpha
end
所以這很好,它的工作原理和所有。然而,這段代碼最終需要快速運行,並且在Ruby中迭代像素是不可接受的。它看起來像,除非這個函數已經存在某個地方,那麼提出一系列可以做到這一點的ImageMagick選項對我來說是最有利的。
我正在研究ImageMagick的命令行工具,因爲它看起來確實非常強大,它看起來像-fx
或者一系列花哨的-function
參數都會和我上面的代碼做同樣的事情。我也會繼續努力,但是那裏有沒有已經知道如何把所有這些放在一起的ImageMagick專家?
編輯:我現在有一個-fx
版本上運行:)
convert image_on_black.png image_on_white.png -matte -channel alpha -fx "u.r + 1 - v.r" -channel RGB -fx "(u.a == 0) ? 1 : (u/u.a)" output.png
的原代碼幾乎確切的翻譯,分爲渠道。遍歷Alpha通道,並設置正確的alpha值。然後遍歷RGB通道,並將通道除以alpha值(除非它爲零,在這種情況下,我們可以將其設置爲任何值,因爲除以零會引發錯誤 - 在這種情況下,我選擇1代表白色)。
現在可以將這些轉換爲更明確的參數,因爲-fx
表達式針對每個像素進行了重新評估,這並不是很好。