 # Rebuilding vertex count with python?

I am trying to rebuild the number of vertices with a target count.

How do I come about doing this with python? Determine the total length of your existing edges, divide that distance by your target vert count, then use basic linear algebra to interpolate the new points along the existing path.

1 Like

Haha, I wish I had the brains to do that. Unfortunately I am not experienced for that since I am a beginner with python. Have been taking courses for a while.

Something like this?

``````import bpy
import bmesh

me = bpy.context.object.data
bm = bmesh.from_edit_mesh(me)
#list to populate with lengths
edge_lengths = []
#if edge is selected, get its length
for e in bm.edges:
#if e.select:
edge_lengths = e.calc_length()
#print(edge_lengths)

count = 10

target = edge_lenths / count
``````

No luck…

basic example:

imagine that you have an existing “spline” consisting of 10 verts (9 segments/edges) and a total length of 9cm. For simplicity’s sake, also imagine that each edge is the same length: 1cm.

if your new target vert count is 20 (19 segments/edges), it needs to travel the same total length, which means your target segment length is 0.5cm. It’s just a matter at starting at the first vert position and moving along the existing ‘spline’ creating new verts every N units.

since mathutils already has code for interpolating vector positions, you can use that and save yourself some time:

``````# "t" needs to be between 0 and 1, in our case it will be 0.5
t = target_segment_length / segment_length
new_vert_pos = vertA.lerp(vertB, t)
``````
1 Like

What does vertA/vertB represent?

depends on where you are in your loop. for example:

``````for i, v in enumerate(my_verts):
if i == len(my_verts) - 1:
break
vertA = v.co
vertB = my_verts[i + 1].co
``````
1 Like

Okay, I have this, but not too sure about the v.co part, do I assign that as “new_vert_pos” ? Also would be nice to decrease and increase target count

``````import bpy

import mathutils

import bmesh

obj = bpy.context.object

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

edge_lengths = []

for e in bm.edges:
#if e.select:
edge_lengths = e.calc_length()

my_verts = [v for v in bm.verts ]#if v.select]

for i, v in enumerate(my_verts):
if i == len(my_verts) - 1:
break
vertA = v.co
vertB = my_verts[i + 1].co

count = 20

t = count / edge_lengths

new_vert_pos = vertA.lerp(vertB, t)

``````

I was thinking merging by distance until the vertex count is at target count
Would the while loop work for this?