White balance and colour converting

Viewed 1108

I am a coding beginner and I have found a code for adjusting the white balance in images. The code works and colours are changing. Actually, all images which I took have a problem with the white balance and I wanted to adjust this with a simple code. The code I have used seemed to work the best (I tried different codes I found on the internet). The problem is that river areas become coloured red after the transformation. I don't know if this is happening because of the white balance or because my colour transformation is wrong. Can someone please help me.

This is the code I have used

import cv2 as cv
# import numpy as np

#
img = cv.imread("C:\\Users\\die5k\\Desktop\\NeuerOrdner\\DJI_0207.jpg")
r, g, b = cv.split(img)
r_avg = cv.mean(r)[0]
g_avg = cv.mean(g)[0]
b_avg = cv.mean(b)[0]

 # Find the gain of each channel
k = (r_avg + g_avg + b_avg) / 3
kr = k / r_avg
kg = k / g_avg
kb = k / b_avg

r = cv.addWeighted(src1=r, alpha=kr, src2=0, beta=0, gamma=0)
g = cv.addWeighted(src1=g, alpha=kg, src2=0, beta=0, gamma=0)
b = cv.addWeighted(src1=b, alpha=kb, src2=0, beta=0, gamma=0)

balance_img = cv.merge([b, g, r])
balance_img = cv.cvtColor(balance_img, cv.COLOR_BGR2RGB)
cv.imwrite('result0207.jpg', balance_img)

This is my input image enter image description here This is my outcome enter image description here

1 Answers

OpenCV uses BGR ordering. Change this:

r, g, b = cv.split(img)

to this:

b, g, r = cv.split(img)

And remove this:

balance_img = cv.cvtColor(balance_img, cv.COLOR_BGR2RGB)

because OpenCV knows to convert to RGB when saving files.

Related