Here is a script I made to split by vertex color. It uses the bpy.ops.mesh.seperate() method as described in another answer. The bulk of it is figuring out what to seperate, but you asked for an example script, so here is one from my toolbox.
'''SPLIT MESH BY VERTEX COLOUR
Script written by sdfgeoff, Jan 2016
Licensed under GPL, share what you make.'''
import bpy
import mathutils
def splitNextColor(obj, threshold=0.01):
def getPolyColor(p):
'''Returns the average colour of a face'''
colors = obj.data.vertex_colors.active.data
r = g = b = 0
for i in p.loop_indices:
c = colors[i].color
r += c.r
g += c.g
b += c.b
r /= p.loop_total
g /= p.loop_total
b /= p.loop_total
return mathutils.Vector((r, g, b)) #So we can compare colors using the .length operator
#Pick the first polygon
p = obj.data.polygons[0]
target = getPolyColor(p)
for p in obj.data.polygons:
source = getPolyColor(p)
#Select any polygons that are similar in colour
if (source - target).length < threshold:
p.select = True
else:
p.select = False
#Seperate the selected faces
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.separate(type='SELECTED')
bpy.ops.object.editmode_toggle()
#Get the current object
obj = bpy.context.active_object
selectList = []
if obj.data.vertex_colors.active == None:
print("Object does not have vertex colors")
else:
#Split of colours until there are no face left
while(len(obj.data.polygons) > 0):
splitNextColor(obj)
#Delete the no-polygon object that:
for ob in bpy.context.selected_objects:
if ob != obj:
ob.select = False
selectList.append(ob)
else:
ob.select = True
bpy.ops.object.delete()
for ob in selectList:
ob.select = True