7/03/2023

Generate simple number text image with black background, white foreground

Code

 .

import cv2
import numpy as np
import random
import os
from tqdm import tqdm

def create_dir(path):
if not os.path.exists(path):
os.makedirs(path)

def generate_image(output_dir, image_name, text, height=100, width=300):
# Create a black image
image = np.zeros((height, width, 3), np.uint8)

# Define the font and text color
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1
color = (255, 255, 255) # white color

# Get the text size
text_size = cv2.getTextSize(text, font, font_scale, 2)[0]

# Set the text position
text_x = (image.shape[1] - text_size[0]) // 2
text_y = (image.shape[0] + text_size[1]) // 2

# Put text into image
cv2.putText(image, text, (text_x, text_y), font, font_scale, color, 2)

# Save the image
cv2.imwrite(os.path.join(output_dir, image_name), image)

if __name__ == "__main__":
# number of images to generate
num_images = 100

# output directory
output_dir = "./number_images"
create_dir(output_dir)

# generate images
for i in tqdm(range(num_images), desc="Generating images"):
number = random.randint(0, 9999999999) # 10 digits
image_name = f"{number}.png"
generate_image(output_dir, image_name, str(number))

..

Image title is same with number text in Image.


Sample images:



Thank you.
๐Ÿ™‡๐Ÿป‍♂️


No comments:

Post a Comment