Monday, 13 November 2023

Create an image with some random colors.

Step 1: Create a blank image using NumPy array with a shape of (height, width, 3) to represent a 3-channel (BGR) image, and the data type as np.uint8.

Step 2: Loop through each pixel in the image and assign a random BGR color to each pixel using the random.randint() function.

# Fill the image with random colors
for y in range(height):
    for x in range(width):
        # Generate a random BGR color
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)

        # Set the pixel color at (x, y)
        random_image[y, x] = [r, g, b]

Find the below working application.

 

blank_image_with_random_colors.py

import cv2 as cv
import numpy as np
import random

# Define the dimensions of the blank image
width, height = 1000, 500

# Create a blank image filled with random colors
random_image = np.zeros((height, width, 3), dtype=np.uint8)

# Fill the image with random colors
for y in range(height):
    for x in range(width):
        # Generate a random BGR color
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)

        # Set the pixel color at (x, y)
        random_image[y, x] = [b, g, r]

# Display the random color image
cv.imshow('Random Color Image', random_image)
cv.waitKey(0)
cv.destroyAllWindows()

Output




 

Previous                                                    Next                                                    Home

No comments:

Post a Comment