Skip to content

Instantly share code, notes, and snippets.

@jacobsapps
Created April 15, 2026 16:01
Show Gist options
  • Select an option

  • Save jacobsapps/270d79661cf0bff49cb1e330c1d35f5a to your computer and use it in GitHub Desktop.

Select an option

Save jacobsapps/270d79661cf0bff49cb1e330c1d35f5a to your computer and use it in GitHub Desktop.
Graph-based face clustering
func clusterFaces(_ embeddings: [[Float]], threshold: Float) -> [[Int]] {
var graph = Array(repeating: [Int](), count: embeddings.count)
for i in embeddings.indices {
for j in (i + 1)..<embeddings.count {
if dot(embeddings[i], embeddings[j]) >= threshold {
graph[i].append(j)
graph[j].append(i)
}
}
}
return connectedComponents(in: graph)
}
func connectedComponents(in graph: [[Int]]) -> [[Int]] {
var visited = Set<Int>()
var components: [[Int]] = []
for start in graph.indices where !visited.contains(start) {
var stack = [start]
var component: [Int] = []
visited.insert(start)
while let face = stack.popLast() {
component.append(face)
for neighbor in graph[face] where !visited.contains(neighbor) {
visited.insert(neighbor)
stack.append(neighbor)
}
}
components.append(component)
}
return components
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment