pythonnumpyopencvimage-processingimage-enhancement

Color problem with Log transform to brighten dark area. Why and how to fix?


So I try to enhance this image by applying log transform on it original image The area where there are bright white color turns into color blue on the enhanced image. enhanced image

path = '...JPG'
image = cv2.imread(path)
c = 255 / np.log(1 + np.max(image))    
log_image = c * (np.log(image + 1))

# Specify the data type so that
# float value will be converted to int
log_image = np.array(log_image, dtype = np.uint8)
cv2.imwrite('img.JPG', log_image)

There's also a warning: RuntimeWarning: divide by zero encountered in log

I tried using other type of log (e.g log2, log10...) but it still show the same result. I tried changing dtype = np.uint32 but it causes error.


Solution

  • Same cause for the two problems

    Namely this line

    log_image = c * (np.log(image + 1))
    

    image+1 is an array of np.uint8, as image is. But if there are 255 components in image, then image+1 overflows. 256 are turned into 0. Which lead to np.log(imag+1) to be log(0) at this points. Hence the error. And hence the fact that brightest parts have strange colors, since they are the ones containing 255

    So, since log will have to work with floats anyway, just convert to float yourself before calling log

    path = '...JPG'
    image = cv2.imread(path)
    c = 255 / np.log(1 + np.max(image))    
    log_image = c * (np.log(image.astype(float) + 1))
    
    # Specify the data type so that
    # float value will be converted to int
    log_image = np.array(log_image, dtype = np.uint8)
    cv2.imwrite('img.JPG', log_image)
    

    enter image description here