2017-09-24 32 views
-1

我一直在努力實現所提供的白平衡算法: https://pippin.gimp.org/image-processing/chapter-automaticadjustments.html自動白平衡與Grayworld假設

我用蟒蛇和OpenCV實現它們。我無法產生與網站相同的結果。

在grayworld假設,例如,我使用下面的代碼:

import cv2 as cv 
import numpy as np 

def show(final): 
    print 'display' 
    cv.imshow("Temple", final) 
    cv.waitKey(0) 
    cv.destroyAllWindows() 

def saveimg(final): 
    print 'saving' 
    cv.imwrite("result.jpg", final) 

# Insert any filename with path 
img = cv.imread("grayworld_assumption_0.png") 
res = img 
final = cv.cvtColor(res, cv.COLOR_BGR2LAB) 

avg_a = -np.average(final[:,:,1]) 
avg_b = -np.average(final[:,:,2]) 

for x in range(final.shape[0]): 
    for y in range(final.shape[1]): 
     l,a,b = final[x][y] 
     shift_a = avg_a * (l/100.0) * 1.1 
     shift_b = avg_b * (l/100.0) * 1.1 
     final[x][y][1] = a + shift_a 
     final[x][y][2] = b + shift_b 

final = cv.cvtColor(final, cv.COLOR_LAB2BGR) 
final = np.hstack((res, final)) 
show(final) 
saveimg(final) 

我得到的結果

,而不是

我要去哪裏錯誤?

+0

'cv.imread()'默認爲BGR嗎?我以爲它使用RGB,但我現在找不到文檔。這可能是問題嗎? ... NVM找到了這些文檔,並默認使用BGR。 – norok2

+0

@norok它在http://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html中說,「在彩色圖像的情況下,解碼圖像將以BGR順序存儲信道「。 – Saptarshi

回答

3

如果是8位顏色深度,您正在執行的文檔不知道LAB definition的CV內部約定。

特別是:

L: L/100 * 255 
A: A + 128 
B: B + 128 

我相信這是爲提高準確度做了,因爲那麼可以在充分使用unsigned int8精度的亮度,同時保持了一致的無符號的數據類型爲整個陣列。

下面的代碼,改編自你的應該工作。 請注意,這裏和那裏有一些小的修復,但嵌套for循環內的實際醬。

from __future__ import (
    division, absolute_import, print_function, unicode_literals) 

import cv2 as cv 
import numpy as np 


def show(final): 
    print('display') 
    cv.imshow('Temple', final) 
    cv.waitKey(0) 
    cv.destroyAllWindows() 

# Insert any filename with path 
img = cv.imread('grayworld_assumption_0.png') 
final = cv.cvtColor(img, cv.COLOR_BGR2LAB) 

avg_a = np.average(final[:, :, 1]) 
avg_b = np.average(final[:, :, 2]) 

for x in range(final.shape[0]): 
    for y in range(final.shape[1]): 
     l, a, b = final[x, y, :] 
     # fix for CV correction 
     l *= 100/255.0 
     final[x, y, 1] = a - ((avg_a - 128) * (l/100.0) * 1.1) 
     final[x, y, 2] = b - ((avg_b - 128) * (l/100.0) * 1.1) 

final = cv.cvtColor(final, cv.COLOR_LAB2BGR) 
final = np.hstack((img, final)) 

show(final) 
cv.imwrite('result.jpg', final)