-1

I'm generating an image that contains all the possible color values of certain bit depth on RGB (same value on 3 channels, so it looks grayscale), creating an easy to read pattern, this code might be usefull (It generates a uint16 NumPy array):

import cv2
import numpy as np

w = 1824
h= 948

bits = 16
max_color = pow(2,bits)
hbar_size = round((w*h)/(max_color)) 
num_bars =  round(h/hbar_size)

color = 0

image_data = np.zeros((h, w, 3)).astype(np.uint16) 

for x in range(0,num_bars+1):
    if((x+1)*hbar_size < h):
        for j in range(0,w):
            color += 1
            for i in range(x*hbar_size , (x+1)*hbar_size): 
                #print(i)
                image_data[i, j] = color
    else:
        for j in range(0,w):
            color += 1
            for i in range(x*hbar_size , h): 
                #print(i)
                image_data[i, j] = min(color , max_color)

The problem is:

When I save it using cv2.imwrite('allValues.png',image_data) I can see the image, which seems to be right BUT it is actually saved on 8 bits depth (when i read it with img = cv2.imread('allValues.png') I get a uint8 NumPy array).

The Question is:

Is there an apropiate way of write/read 16 bits RGB images on OpenCV for python?

Is the png format the problem?

Ivan
  • 1,352
  • 2
  • 13
  • 31
  • 1
    Does this answer your question? [OpenCV - Reading a 16 bit grayscale image](https://stackoverflow.com/questions/10969585/opencv-reading-a-16-bit-grayscale-image) – Chris Jan 09 '20 at 14:58

1 Answers1

2

It is saving in 16bit, but it converts to 8bit automatically when loaded so that you can view it on your screen. You can bypass that functionality by using

im = cv2.imread('allValues.png',-1)

Chris
  • 15,819
  • 3
  • 24
  • 37
  • 9
    Please, don't encourage bad habits. There's absolutely no reason to use a magic number (the `-1`), when OpenCV provides [named constants](https://docs.opencv.org/3.4/d4/da8/group__imgcodecs.html#gga61d9b0126a3e57d9277ac48327799c80aeddd67043ed0df14f9d9a4e66d2b0708) for this purpose. – Dan Mašek Jan 09 '20 at 15:25
  • -1 maps to: cv::IMREAD_UNCHANGED = -1 – Ari May 24 '20 at 08:32