Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a black image and a white image using OpenCV Python?
To create a black image, we use the np.zeros() method which creates a numpy array with all elements as 0. When displayed using cv2.imshow(), it appears as a black image since 0 represents black pixels.
To create a white image, we use np.ones() method and multiply by 255 to get maximum pixel intensity. This creates a white image since 255 represents white pixels in 8-bit images.
Note ? We pass dtype = np.uint8 to create 8-bit unsigned integer arrays suitable for image data.
Creating a Black Image
Black images are created using np.zeros() which initializes all pixel values to 0 ?
import cv2
import numpy as np
# Create a 350x700 black image (height, width, channels)
img = np.zeros((350, 700, 3), dtype=np.uint8)
# Display the image
cv2.imshow('Black Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Creating a White Image
White images are created using np.ones() multiplied by 255 to get maximum pixel intensity ?
import cv2
import numpy as np
# Create a 350x700 white image (height, width, channels)
img = np.ones((350, 700, 3), dtype=np.uint8)
img = 255 * img
# Display the image
cv2.imshow('White Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Alternative Method for White Image
You can also create a white image directly by specifying 255 as the fill value ?
import cv2
import numpy as np
# Create white image directly using np.full()
img = np.full((350, 700, 3), 255, dtype=np.uint8)
# Display the image
cv2.imshow('White Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Complete Example
Here's a complete example that creates both black and white images ?
import cv2
import numpy as np
# Create a black image
black_img = np.zeros((350, 700, 3), dtype=np.uint8)
# Create a white image
white_img = np.ones((350, 700, 3), dtype=np.uint8) * 255
# Display both images
cv2.imshow('Black Image', black_img)
cv2.imshow('White Image', white_img)
# Wait for key press and close windows
cv2.waitKey(0)
cv2.destroyAllWindows()
# Print image properties
print(f"Black image shape: {black_img.shape}")
print(f"White image shape: {white_img.shape}")
print(f"Black image dtype: {black_img.dtype}")
print(f"White image dtype: {white_img.dtype}")
Understanding Image Dimensions
The tuple (height, width, channels) defines the image dimensions:
- height ? Number of rows (350 pixels)
- width ? Number of columns (700 pixels)
- channels ? Color channels (3 for BGR color images)
For grayscale images, you can omit the channels parameter and use (height, width) only.
Conclusion
Use np.zeros() to create black images and np.ones() * 255 for white images. Always specify dtype=np.uint8 for proper 8-bit image representation. Remember that OpenCV uses BGR color format by default.
