import cv2
import numpy as np
from matplotlib import pyplot as plt
from IPython.display import display, Image
import random
import uuid
import copy
front_list = [cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN, cv2.FONT_HERSHEY_DUPLEX, cv2.FONT_HERSHEY_COMPLEX, cv2.FONT_HERSHEY_TRIPLEX, cv2.FONT_HERSHEY_COMPLEX_SMALL, cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, cv2.FONT_HERSHEY_SCRIPT_COMPLEX, cv2.FONT_ITALIC]
color_list = [(0,0,0),(0,0,255),(0,255,0),(0,255,255),(255,255,0),(255,0,255),(255,255,255)]
front_size_list = [1,2]
front_bond_list = [1,2,3,4]
def create_num(num_str):
font = random.choice(front_list)
font_size = random.choice(front_size_list)
font_bond = random.choice(front_bond_list)
font_color = random.choice(color_list)
back_gound_color = copy.deepcopy(font_color)
while font_color == back_gound_color:
back_gound_color = random.choice(color_list)
obj_img_width = 64
obj_img_height = 64
center_point_x = int(1/2 * obj_img_width)
center_point_y = int(1/2 * obj_img_height)
# Create a blank canvas of size 64x64 with white background
canvas = np.full((obj_img_width, obj_img_height, 3), back_gound_color, dtype=np.uint8)
(font_width, font_height), font_bottom = cv2.getTextSize(num_str, font, fontScale=font_size, thickness=font_bond)
while font_width > obj_img_width or font_height > obj_img_height:
font_size = random.choice(front_size_list)
(font_width, font_height), font_bottom = cv2.getTextSize(num_str, font, fontScale=font_size, thickness=font_bond)
top = int(center_point_y - 1/2 * font_height)
left = int(center_point_x - 1/2 * font_width)
right = left + font_width
x_left_bottom = int(center_point_y - 1/2 * font_width)
y_bottom = int(center_point_y + 1/2 * font_height)
print("------=========---",x_left_bottom,y_bottom)
cv2.putText(canvas,num_str, (x_left_bottom,y_bottom), font, font_size,font_color, font_bond, cv2.LINE_AA)
mean = random.randint(0,255)
std = random.randint(0,255)
mean = 0
std = 25
h, w, c = obj_img_height, obj_img_width, 3
noise = np.random.normal(mean, std, (h, w, c)).astype(np.uint8)
canvas = cv2.add(canvas, noise)
# Display the canvas using OpenCV
# plt.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))
# plt.rcParams['figure.figsize'] = [8, 8]
# plt.axis('off')
# plt.show()
return canvas
# cv2.imwrite('yellow_background.jpg', canvas)
import os
num_list = list(range(0,99))
num_list = num_list + ["00","01","02","03","04","05","06","07","08","09"]
print(num_list)
for num in num_list:
str_num = str(num)
tgt_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"imgs",str_num)
os.makedirs(tgt_dir,exist_ok=True)
for _ in range(50):
img = create_num(str_num)
cv2.imwrite(tgt_dir+"/0805_" + uuid.uuid1().hex + ".jpg",img)
效果图: