I want to understand what is the difference between np.zeros
and np.ones
. In my bellow code both create a black images. But what is the use of np.zeros
and np.ones
. When should i use them. What is the purpose. I know np.ones
fill matrix with 1 but what is the purpose. What i want to create a white image
img = np.ones((512,512,3), np.uint8)
cv2.imshow('IMG', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = np.zeros((512,512,3), np.uint8)
cv2.imshow('IMG', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Initialize your array as float
data type. Only then 0 will mean black and 1 will mean white:
img = np.ones((512,512,3), np.float)
Explanation : When imshow
receives an array of ints, it will assume, that 0 is the minimum and 255 the maximum value, representing black and white in a greyscale image. However if it receives an array of floats it sets these values to 0.0 and 1.0, because it assumes a scaled input.
np.zeros
"Return a new array of given shape and type, filled with zeros."
np.ones
"Return a new array of given shape and type, filled with ones."
np.zeros(10)
Out: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
np.ones(10)
Out:array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
You need to scale by the number of bits you have in a pixel. For example,
img = 255*np.ones((512, 512, 3), uint8)
will produce a white image for 8-bit pixels.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.