# How to get UV stretching (angle or area colors) with Python without looking at viewport?

I know how to view the UV stretching by angle or area in the viewport. However, I want to write a script by which I can determine if a UV island results in a red, yellow or green stretch to correct it automatically. Any ideas on how these values can be obtained?

Blender documentation of "show_stretch" function in "SpaceUVEditor(bpy_struct)" says that this function "draw faces colored according to the difference in shape between UVs and their 3D coordinates (blue for low distortion, red for high distortion)" here. Is there any way I can make this function to return something for determining stretching colors?

Alternatively, can someone suggest any other good/better way to check UV stretching using python?

Normalized Edge length vectors.

Started writing this answer for How to check if UV distortion exists using Python? and lo and behold when I returned to post it had been closed, hence have added an answer here going only someway to answering this question

For a very rudimentary test could walk around each faces loop, make vectors of edge lengths for both mesh and UV, normalize them, and compare. The big expectation here, i suppose is that the meshes polygon verts are coplanar.

Note in hindsight for this test to be robust would first triangulate then compare lengths, as a quad can be flattened to a diamond to a line.

List vertex colors from a bmesh

import bpy
from bpy import context
from mathutils import Vector

ob = context.object
me = ob.data
uv_layer = me.uv_layers.active

for f in me.polygons:
verts = [me.vertices[me.loops[l].vertex_index].co for l in f.loop_indices]
uvs = [uv_layer.data[l].uv for l in f.loop_indices]
lvs = Vector((v1 - v0).length for v0, v1 in zip(verts, verts[1:])).normalized()
luvs = Vector((v1 - v0).length for v0, v1 in zip(uvs, uvs[1:])).normalized()
print(f"{f.index} :  {(lvs - luvs).length}")


Simple test run.

As a test have done little more than added a cube with default UV, pulled on one of its vertices

Displaying stretching by 'ANGLE'. which correspond to results below, the two lightest faces 0, 5 and third-ish as distorted face 3

0 : 0.19459002803218287
1 : 0.0
2 : 0.0
3 : 0.0722531723959878
4 : 0.0
5 : 0.19134772084616544


Edge angles.

The answer here describes how to find the interior angles of each edge. Similarly to above could calculate for both mesh and UV and compare. At most the angle can differ by 180 degrees in which case would color vertex red.

Areas

TBH little confused re the viewport display when in 'AREA' mode above the most bent out of shape face in relation to its original square UV, displays as blue.

Anyway assume this could be done very similarly by using some arbitrary point (geo center for example) and calculating the area of each triangle.