5 import torch, torchvision
8 from torch.nn import functional as F
13 def __init__(self, x, y, w, h, r, g, b):
22 def collision(self, scene):
26 and max(self.x, c.x) <= min(self.x + self.w, c.x + c.w)
27 and max(self.y, c.y) <= min(self.y + self.h, c.y + c.h)
33 def scene2tensor(xh, yh, scene, size=64):
34 width, height = size, size
35 pixel_map = torch.ByteTensor(width, height, 4).fill_(255)
36 data = pixel_map.numpy()
37 surface = cairo.ImageSurface.create_for_data(
38 data, cairo.FORMAT_ARGB32, width, height
41 ctx = cairo.Context(surface)
42 ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
45 ctx.move_to(b.x * size, b.y * size)
46 ctx.rel_line_to(b.w * size, 0)
47 ctx.rel_line_to(0, b.h * size)
48 ctx.rel_line_to(-b.w * size, 0)
50 ctx.set_source_rgba(b.r, b.g, b.b, 1.0)
54 ctx.set_source_rgba(0.0, 0.0, 0.0, 1.0)
55 ctx.move_to(xh * size - hs / 2, yh * size - hs / 2)
56 ctx.rel_line_to(hs, 0)
57 ctx.rel_line_to(0, hs)
58 ctx.rel_line_to(-hs, 0)
62 return pixel_map[None, :, :, :3].flip(-1).permute(0, 3, 1, 2).float() / 255
76 wh = torch.rand(2) * 0.2 + 0.2
77 xy = torch.rand(2) * (1 - wh)
78 c = colors[torch.randint(len(colors), (1,))]
80 xy[0].item(), xy[1].item(), wh[0].item(), wh[1].item(), c[0], c[1], c[2]
82 if not b.collision(scene):
88 def sequence(nb_steps=10, all_frames=False):
106 scene = random_scene()
107 xh, yh = tuple(x.item() for x in torch.rand(2))
109 frames.append(scene2tensor(xh, yh, scene))
111 actions = torch.randint(len(effects), (nb_steps,))
115 g, dx, dy = effects[a]
118 if b.x <= xh and b.x + b.w >= xh and b.y <= yh and b.y + b.h >= yh:
127 or b.collision(scene)
138 if xh < 0 or xh > 1 or yh < 0 or yh > 1:
142 frames.append(scene2tensor(xh, yh, scene))
145 frames.append(scene2tensor(xh, yh, scene))
150 return frames, actions
153 if __name__ == "__main__":
154 frames, actions = sequence(nb_steps=31,all_frames=True)
155 frames = torch.cat(frames,0)
156 print(f"{frames.size()=}")
157 torchvision.utils.save_image(frames, "seq.png", nrow=8)