Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to develop 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()

When I am executing the code, I am getting a black image. 

fn='example.jpg'

cv.imwrite(fn, s)

Then I have to replace int with uint8 for getting the correct image. I want to know why I need to use uint8 instead of int?

1 Answer

0 votes
by (108k points)
edited by

Kindly be informed that the OpenCV package in Python will change its behavior according to the type of array you are using in your code:

Thus, if the image is in the format of 8-bit unsigned, then it will get presented as-is.

But, if the picture is in the structure of a 16-bit unsigned or 32-bit integer, then the number of cells of the picture will get divided by 256 that denotes the value range [0,255*256] is composed to [0,255].

And if the picture is in the form of a 32-bit floating-point, then the pixel of the image will get multiplied by 255. That means the value range [0,1] is drafted to [0,255].

Therefore, the below code will all yield the same 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

If you are a beginner and want to know more about Python, then do check out the below Python tutorial video that will help you in understanding the topic in a better way:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 7, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 11, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Mar 21, 2021 in Python by laddulakshana (16.4k points)

Browse Categories

...