Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert images from [-1; 1] to [0; 255]

I know that question is really simple, but I didn't find how to bypass the issue:

I'm processing images, the output pixels are float32, and values are in range [-1; 1]. The thing is, when saving using openCV, all negative data and float values are lost (I only get images with 0 or 1 values)

So I need to convert those images to [0; 255] (Int8)

I've tried

  • img * 255, but doing this does not help with negative values.
  • (img + 1) * 255, I'm removing the negative values, but I'm creating an overflow

Is there a (clean) way to do it ?

I'm using Python35, OpenCV2 and Numpy, but I think it's more a math problem than a library thing

like image 962
Mael Abgrall Avatar asked Jun 21 '18 10:06

Mael Abgrall


People also ask

How do you normalize an image to 0 255?

For example, if the intensity range of the image is 50 to 180 and the desired range is 0 to 255 the process entails subtracting 50 from each of pixel intensity, making the range 0 to 130. Then each pixel intensity is multiplied by 255/130, making the range 0 to 255.

How do you normalize an image in Python?

Use the normalize() Function of OpenCV to Normalize an Image in Python. Normalization in image processing is used to change the intensity level of pixels. It is used to get better contrast in images with poor contrast due to glare. We can use the normalize() function of OpenCV to normalize an image.


1 Answers

You can use cv2.normalize()

Consider the following array a:

a = np.array([[-0.12547205, -1.        ],
              [ 0.49696118,  0.91790167],
              [ 0.81638017,  1.        ]])

norm_image = cv2.normalize(image, None, alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)

norm_image = norm_image.astype(np.uint8)

norm_image returns the following array:

array([[111,   0],
      [190, 244],
      [231, 255]], dtype=uint8)

In this example:

  • -1 will be mapped to 0
  • 1 will be mpped to 255
  • Everything in between will be mapped accordingly (0, 255)

Points to note:

  1. Ensure the array is of type float
  2. The extreme of values are place in alpha and beta respectively.
like image 192
Jeru Luke Avatar answered Sep 20 '22 14:09

Jeru Luke