这段代码将生成2-4个大小不同的圆形和1-2个大小不同的椭圆形,并确保它们之间以及与背景边界之间不会发生重叠
限制圆形的半径不超过150,第13行
import cv2
import random
import os
'''
这段代码将生成2-4个大小不同的圆形和1-2个大小不同的椭圆形,并确保它们之间以及与背景边界之间不会发生重叠
限制圆形的半径不超过150,第13行
'''
def generate_non_overlapping_shapes(bg_width, bg_height, min_size, max_size, num_circles, num_ellipses):
shapes = []
# 生成圆形
for _ in range(num_circles):
while True:
radius = random.randint(min_size, min(max_size, 150)) # 确保半径不大于200
center = (random.randint(radius, bg_width - radius), random.randint(radius, bg_height - radius))
overlap = False
for s in shapes:
s_radius = s['size'][0] if 'size' in s else s['radius']
if ((center[0] - s['center'][0]) ** 2 + (center[1] - s['center'][1]) ** 2) < (radius + s_radius) ** 2:
overlap = True
break
if not overlap:
shapes.append({'center': center, 'radius': radius})
break
# 生成椭圆形
for _ in range(num_ellipses):
while True:
size = (random.randint(min_size, max_size), random.randint(min_size, max_size))
center = (random.randint(size[0]//2, bg_width - size[0]//2), random.randint(size[1]//2, bg_height - size[1]//2))
angle = random.randint(0, 360)
overlap = False
for s in shapes:
s_radius = s['size'][0] if 'size' in s else s['radius']
# Simplified check for overlap: consider the ellipse as a circle with radius equal to the maximum of its half-axes
max_radius = max(size) // 2
if ((center[0] - s['center'][0]) ** 2 + (center[1] - s['center'][1]) ** 2) < (max_radius + s_radius) ** 2:
overlap = True
break
if not overlap:
shapes.append({'center': center, 'size': size, 'angle': angle})
break
return shapes
# 新增一个函数来保存生成的图片
def save_image(image, directory, base_filename, image_index):
if not os.path.exists(directory):
os.makedirs(directory)
filename = f"{base_filename}_{image_index:03d}.jpg"
filepath = os.path.join(directory, filename)
cv2.imwrite(filepath, image)
print(f"Saved: {filepath}")
# 定义图片保存路径和基础文件名
output_directory = 'datasets/random_generate_images'
base_filename = 'random_generate_image'
# 指定要生成的图片数量
number_of_images = 1500 # 生成5张图片,可以根据需要修改这个数量
# 加载指定的背景图片模板
background_template = cv2.imread('background.jpg')
# 检查图片是否成功载入
if background_template is None:
raise FileNotFoundError("指定的图片 background.jpg 没有找到。")
# 获取背景图片的尺寸信息
bg_height, bg_width = background_template.shape[:2]
# 生成指定数量的图片
for img_index in range(number_of_images):
background = background_template.copy() # 为每张图片复制一份背景模板
num_circles = random.randint(2, 4)
num_ellipses = random.randint(1, 2)
shapes = generate_non_overlapping_shapes(bg_width, bg_height, 10, 256, num_circles, num_ellipses)
for shape in shapes:
if 'radius' in shape:
cv2.circle(background, shape['center'], shape['radius'], (190, 190, 190), -1)
else:
cv2.ellipse(background, shape['center'], shape['size'], shape['angle'], 0, 360, (190, 190, 190), -1)
# 保存生成的图片
save_image(background, output_directory, base_filename, img_index)
# 如果你想在保存后显示最后一张图片,取消下面的注释
# cv2.imshow('Background with Shapes', background)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
示例: