I want adjust the contrast in Python's OpenCV like in Gimp. I want do this:
In Gimp it is simple. I just use Colors->Brightness & Contrast
, and set contrast to 127
.
But I don't know how to do this in Python and I cannot find any solution to this problem.
Check here. The formula is:
new_value = (old_value - 0.5) × contrast + 0.5 + brightness
In python you can easily apply these as matrix operations. Please note that pixel values here are in [0,1], so 0.5 is equivalent to 127 when the range is in [0,255].
In the same link is reported also the code, with pixel-wise operations (I copy just for completeness):
function transform(value, brightness, contrast)
return (value-0.5)*contrast+0.5+brightness
end
function transform_rgb(r,g,b, brightness, contrast)
return transform(r, brightness, contrast), transform(g, brightness, contrast), transform(b, brightness, contrast)
end
function bcontrast_get_rgb(x,y,brightness, contrast)
r,g,b=get_rgb(x,y)
return transform_rgb(r,g,b, brightness, contrast)
end
function bcontrast(brightness, contrast)
for y=0, height-1 do
for x=0, width-1 do
set_rgb(x,y, bcontrast_get_rgb(x,y,brightness,contrast))
end
end
flush ()
end
bcontrast(0.25, 2.0)