how to get the correct UV values to put a texture on a 2D polygon created with the opaque_to_polygon method?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By newold

I have a scene with two sprites like this

so in my script, I create two 2D polygons using this:

var sprite1 = $Sprite1 # My mask (may be rotated and/or scaled)
var sprite2 = $Sprite2
# create a polygon from sprite 1
var b = BitMap.new()
b.create_from_image_alpha(sprite1.texture.get_data(), 0)
var polygons = b.opaque_to_polygons(Rect2(Vector2.ZERO, sprite1.texture.get_size()), 0)
# Create two 2D polygons using the polygon obtained by the previous method.
var polygon2d_back = Polygon2D.new()
polygon2d_back.polygon = polygon
polygon2d_back.position = sprite1.position
var polygon2d_top = Polygon2D.new()
polygon2d_top.polygon = polygon
polygon2d_top.position = sprite1.position

and now I need to know how to get the correct UV to put the textures of sprite1 and sprite2 in both polygons to get this result:

# Set textures and UVs (note that sprite1 (the mask) may be rotated or scaled.)
polygon2d_back.texture = sprite2.texture
polygon2d_back.uv = # ????????????????? <------------ How do I calculate this?

polygon2d_top.texture = sprite1.texture
polygon2d_top.uv = # ????????????????? <------------ How do I calculate this?