-1

I would like to use

import cv2

def adjust_gamma(image, gamma=1.0):
    # build a lookup table mapping the pixel values [0, 255] to
    # their adjusted gamma values
    invGamma = 1.0 / gamma
    table = np.array([((i / 255.0) ** invGamma) * 255
        for i in np.arange(0, 256)]).astype("uint8")

    # apply gamma correction using the lookup table
    return cv2.LUT(image, table)

to make invert gamma correction but my data is in [0,4095] format, so I adapt the code replacing 255 by 4095 and 256 by 4096:

import cv2

def adjust_gamma(image, gamma=1.0):
    # build a lookup table mapping the pixel values [0, 255] to
    # their adjusted gamma values
    invGamma = 1.0 / gamma
    table = np.array([((i / 4095.0) ** invGamma) * 4095
        for i in np.arange(0, 4096)]).astype("uint8")

    # apply gamma correction using the lookup table
    return cv2.LUT(image, table)

But when trying to call the function on a random png image:

adjust_gamma(cv2.imread('myimage.png'), gamma=2.0)

I get the error:

OpenCV(3.4.3) /io/opencv/modules/core/src/lut.cpp:368: error: (-215:Assertion failed) (lutcn == cn || lutcn == 1) && _lut.total() == 256 && _lut.isContinuous() && (depth == CV_8U || depth == CV_8S) in function 'LUT'
gen2
  • 9
  • 1
  • 2
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Without your extended format file, we can't reproduce the error or test a repair. – Prune Nov 01 '18 at 16:13

2 Answers2

0

On a high level, I believe that your problem is simply one of method compatibility: LUT works on the standard 8-bit format. You have to convert your image to that format before feeding it to the method. Alternately, you can write your own 12-bit LUT method, replacing all of the upper limits in the original code with your 4095/4096.

Prune
  • 76,765
  • 14
  • 60
  • 81
0

You can do Gamma Correction without cv2 for data whose bandwidth is not 8bit or not formulated with integer type.

import numpy as np

def gamma_correction(img: np.ndarray, gamma: float=1.0):
  igamma = 1.0 / gamma
  imin, imax = img.min(), img.max()

  img_c = img.copy()
  img_c = ((img_c - imin) / (imax - imin)) ** igamma
  img_c = img_c * (imax - imin) + imin
  return img_c

Example of Usage

import imageio
import matplotlib.pyplot as plt
import numpy as np

test = imageio.imread('test.png')
test_g = gamma_correction(test, gamma=2.2).astype(np.uint8)

plt.subplot(1, 2, 1)
plt.imshow(test)
plt.subplot(1, 2, 2)
plt.imshow(test_g)
plt.show()

Example Result

enter image description here

SHIM
  • 101
  • 1
  • 3