Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why datatype has to be 'uint8' in Opencv python wrapper?

Tags:

python

opencv

I'd like to create an image of gray color using the following code:

import numpy as np
import cv2
cv=cv2

s=np.zeros((240, 320, 3), dtype=int)
s[s==0]=128
cv.imshow('3', s)
cv.waitKey()
cv.destroyAllWindows()

but I get a totally black image. When I write the image to a file, it indeed is a gray image:

fn='example.jpg'
cv.imwrite(fn, s)

So I have to change int to uint8, then everything works well. But I'm still curious that why I have to use uint8 instead of int, is there any docs describing this?

like image 548
zhangxaochen Avatar asked May 20 '14 02:05

zhangxaochen


1 Answers

From the documentation, OpenCV changes its behavior according to the type of the array:

  • If the image is 8-bit unsigned, it is displayed as is.
  • If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
  • If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].

Hence, the following will all produce the same image grayscale image:

s = np.zeros((240, 320), dtype=np.uint8)
s[s==0] = 128

int32:

s = np.zeros((240, 320), dtype=np.int32)
s[s==0] = 128 * 256

float32:

s = np.zeros((240, 320), dtype=np.float32)
s[s==0] = 128 / 256.0
like image 139
univerio Avatar answered Sep 28 '22 08:09

univerio