Get amount of connected geometry within a mesh

Basically, you want to create a list of connected faces, and then sort that list by len(faces) and keep the last index. This code is untested and off the top of my head, but should work given how many times I’ve had to do it:

import bpy, bmesh
from queue import Queue

def get_connected_faces(face):
    return { f for e in face.edges for f in e.link_faces if f != face }

bm = bmesh.from_edit_mesh(bpy.context.edit_object.data)

connected_groups = []
work_list = [f for f in bm.faces]
while work_list:

    frontier = Queue()
    frontier.put( work_list[0] )
    this_group = [work_list[0]]
    work_list.pop(0)
    
    while not frontier.empty():
        for next_face in get_connected_faces(frontier.get()):
            if next_face not in this_group:
                frontier.put(next_face)
                this_group.append(next_face)
                work_list.remove(next_face)

    connected_groups.append(this_group)
    
connected_groups = sorted(connected_groups, key=lambda x: len(x))   

keep_faces = connected_groups[-1]
print([f.index for f in keep_faces]) 

# TODO: bmesh delete everything else, update the mesh, etc.

4 Likes