Vanuan
Vanuan

Reputation: 33412

Opencv draws numpy.zeros as a gray image

I'm struggling with understanding how opencv interprets numpy arrays.

import cv2
import numpy as np

if __name__ == '__main__':
    size = (w, h, channels) = (100, 100, 1)
    img = np.zeros(size, np.int8)
    cv2.imshow('result', img), cv2.waitKey(0)
    cv2.destroyAllWindows()

Grayscale black 100x100 image, right? No, it's showing me gray! Why's that?

Upvotes: 7

Views: 36595

Answers (3)

abhishek prakash
abhishek prakash

Reputation: 11

Your code needs to change 2 things:

  1. size = (w, h, channels) = (100, 100, 3)

since (100, 100, 1) will create a grayscale image, color images (BGR or RGB) require 3 channels, 1 each for Red, Blue and Green

  1. img = np.zeros(size, np.uint8) (int8 will not be able to capture values from 0-255)

Upvotes: 1

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

For a BGR image,

img = np.zeros([height, width, 3], dtype=np.uint8)

Upvotes: 4

Vanuan
Vanuan

Reputation: 33412

Ok, the crucial part is dtype. I've chosen np.int8. When I use np.uint8, it is black.

Suprisingly, when dtype=np.int8, zeros are interpreted as 127(or 128)!

I expected that zero is still zero, no matter if it is signed or unsigned.

Upvotes: 13

Related Questions