7
$\begingroup$

Using Python, can one select or find what is selected in the UV Image Editor?

I tried accessing the UV screen itself and found its SpaceUVEditor but got stuck there.

Any thoughts?

$\endgroup$
1
  • $\begingroup$ Note, UV's are stored in face loops, so 'BM_LOOPS_OF_FACE' is the correct iterator to use. Then from each loop you can access the UV customdata layer. However this is a bit odd that you are referencing C iterators in a Python question. $\endgroup$
    – ideasman42
    Commented Oct 27, 2013 at 8:42

2 Answers 2

9
$\begingroup$

The UV map being shown in the UV Image Editor is the active one, accessible through uv_layers.active variable of active object's mesh data.

According to API docs, loops and all UV maps in uv_layers are aligned. Which means, if you have the indices of every selected MeshUVLoop within current mesh's UV map, you'll get the corresponding MeshLoop at the same indices within that mesh's list of loops. From there, you can get their vertices.

To make my explanation above clearer, here's a sample script that will print selected UV loops' vertex coordinates to console. The script won't work if use_uv_select_sync button in UV Image Editor's header is toggled on, in which case MeshUVLoop's select property is ignored.

import bpy

# UV data is accessible only in object mode
prev_mode = bpy.context.object.mode
bpy.ops.object.mode_set(mode='OBJECT')

# Update vertex selection properties, in case the script wasn't run in
# object mode
bpy.context.object.update_from_editmode()

# Active object assumed to be a mesh and already have a UV map
mesh = bpy.context.object.data
uv_map = mesh.uv_layers.active
selected_loops = []
selected_vertices = set()

for index, uv_loop in enumerate(uv_map.data):
    if(uv_loop.select):
        selected_loops.append(index)

for loop_index in selected_loops:
    selected_vertices.add(mesh.loops[loop_index].vertex_index)

for vertex_index in selected_vertices:
    print(mesh.vertices[vertex_index].co)

print('*' * 20)

# Restore whatever mode the object is in previously
bpy.ops.object.mode_set(mode=prev_mode)
$\endgroup$
0
5
$\begingroup$

Blender comes with a template which deals with UV selection, see:

Templates > Python > Operator Mesh UV

The body of this template:

import bpy
import bmesh

obj = context.active_object
me = obj.data
bm = bmesh.from_edit_mesh(me)

uv_layer = bm.loops.layers.uv.verify()
bm.faces.layers.tex.verify()  # currently blender needs both layers.

# adjust UVs
for f in bm.faces:
    for l in f.loops:
        luv = l[uv_layer]
        if luv.select:
            # apply the location of the vertex as a UV
            luv.uv = l.vert.co.xy

bmesh.update_edit_mesh(me)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .