Nodes/comfyui-AGSoft/🧑✂️AGSoft Crop Face
ComfyUI Node

🧑✂️AGSoft Crop Face

Face crops on autopilot — RetinaFace shipped inside the pack

By Art-xmaster·Created 12 months ago·Updated about 18 hours ago· 23
🧑✂️AGSoft Crop Face
  • image
  • mask
  • face
  • crop_data
number_of_faces5
scale_factor2.0
shift_factor_x0.50
shift_factor_y0.50
start_index0
max_faces_per_image50
aspect_ratio1:1
confidence_threshold0.70
divisible_by8

Cropping faces by hand is a miserable way to spend an afternoon - until you realize the community's answer is usually a face-detection node you have to install separately, with a model you have to download. 🧑✂️ AGSoft Crop Face sidesteps that: it bundles RetinaFace and its weights inside the pack, so you get solid face detection plus cropping the day you install comfyui-AGSoft. No extra pip install, no hunting for a .pth file.

The short pitch: give it an image (or a batch), it finds the faces, crops them with padding, and outputs both the crop and the bounding-box data. This is the node you reach for when you're building face swap, face restorer, or face-LoRA pipelines and you're tired of drawing boxes.

How it works

Detection runs on the RetinaFace MobileNet0.25 model vendored in the pack's Pytorch_Retinaface/ folder - the weights ship with the repo, so it works offline, first run. Two face-related numbers are worth untangling because they sound identical:

  • max_faces_per_image (default 50) - the detection limit. How many faces RetinaFace is allowed to return.
  • number_of_faces (default 5) - how many you actually get, starting from start_index in the confidence-ranked list.

So number_of_faces=3 with start_index=1 hands you the 2nd, 3rd, and 4th most confident faces. That's your "skip the blurry one in the back" control.

confidence_threshold (default 0.7) filters weak detections. scale_factor (default 2) is the crop padding - 2 means the crop is twice the face box, so there's context around the face, not a skin-tight rectangle. shift_factor_x/shift_factor_y (both 0.5) shift the crop's center point horizontally/vertically - handy when faces sit low in the frame or you want the crop biased toward one side. aspect_ratio (default 1:1) forces the crop's shape; divisible_by (default 8) rounds crop dimensions for sampler compatibility.

The optional mask input is the neat one: mask out a region and only faces detected inside that mask are returned - "only the faces in the doorway, not the crowd."

Outputs

face - the cropped image(s) as a batch. crop_data - a CROP_DATA structure with the box and original context. That second output is the enabler: it feeds nodes that expect CROP_DATA to composite the result back into the original frame (the same convention used across the wider face-crop ecosystem), so your swapped/restored face can go home where it started.

Installing it

Pack standard: ComfyUI Manager → search comfyui-AGSoft → install, restart. Or:

cd ComfyUI/custom_nodes
git clone https://github.com/Art-xmaster/comfyui-AGSoft.git

The one real dependency is opencv-python (for image handling) - the pack's pyproject.toml lists it, but the plain requirements.txt doesn't, so if the node is missing after a bare clone, run pip install opencv-python in your ComfyUI environment and restart. RetinaFace weights are already in the folder; nothing to download.

Common issues

  • Node doesn't appear after install - almost always missing cv2. Install opencv-python (above).
  • Fewer faces than expected - raise number_of_faces or lower confidence_threshold; the default 0.7 drops small/partial faces on purpose.
  • Crops too tight or too loose - that's scale_factor, not the detector. Bump it up if you're getting forehead-shaved crops.
  • Face-swap identity drift - remember the crop feeds a face-focused pass (swap or restore) whose result goes back via crop_data; generative models rewriting faces is a pipeline design decision, not a node bug.

One honest note: RetinaFace is a 2019-era detector - great for clean frontal faces, weaker on heavy angles and tiny faces. For those cases, expect to lean on the confidence and scale knobs.

CategoryAGSoft/Crop

Inputs (11)

NameTypeDefaultDescription
imageIMAGEEN: Input image containing one or more faces to detect and crop. Supports batch processing (multiple images at once). RU: 📷 Входное изображение, содержащее одно или несколько лиц для обнаружения и кадрирования. Поддерживает пакетную обработку (несколько изображений сразу).
number_of_facesINT51–100EN: 🔢 How many faces to return. Faces are sorted by size (largest first). • If more faces found → returns only this number (largest ones) • If fewer faces found → returns all found (no duplicates) RU: Сколько лиц вернуть. Лица сортируются по размеру (большие первыми). • Если найдено больше → вернет только указанное количество (самые большие) • Если найдено меньше → вернет все найденные (без дубликатов)
scale_factorFLOAT2.01–5EN: How much to enlarge the crop around the face. • 1.0 = Tight crop (face fills almost entire image) • 2.0 = Comfortable crop (face + some background, recommended) • 3.0+ = Wide crop (face + lots of surrounding context) RU: 📏 Насколько увеличить область кадрирования вокруг лица. • 1.0 = Плотный кроп (лицо занимает почти всё изображение) • 2.0 = Комфортный кроп (лицо + немного фона, рекомендуется) • 3.0+ = Широкий кроп (лицо + много окружающего контекста)
shift_factor_xFLOAT0.500–1EN: ↔️ Horizontal position of the face within the cropped image. Controls where the face sits horizontally in the final crop. • 0.00 = Face at the far LEFT (more space on right) • 0.50 = Face in the CENTER (balanced, default) • 1.00 = Face at the far RIGHT (more space on left) RU: ↔️ Горизонтальная позиция лица в кадрированном изображении. Контролирует, где лицо располагается по горизонтали в финальном кадре. • 0.00 = Лицо слева (больше места справа) • 0.50 = Лицо в ЦЕНТРЕ (сбалансировано, по умолчанию) • 1.00 = Лицо справа (больше места слева)
shift_factor_yFLOAT0.500–1EN: ⬆️⬇️ Vertical position of the face within the cropped image. Controls where the face sits vertically in the final crop. • 0.00 = Face at the very TOP (more space below) • 0.50 = Face in the CENTER (balanced, default) • 1.00 = Face at the very BOTTOM (more space above) RU: ⬆️⬇️ Вертикальная позиция лица в кадрированном изображении. Контролирует, где лицо располагается по вертикали в финальном кадре. • 0.00 = Лицо в самом ВЕРХУ (больше места снизу) • 0.50 = Лицо в ЦЕНТРЕ (сбалансировано, по умолчанию) • 1.00 = Лицо в самом НИЗУ (больше места сверху)
start_indexINT00–999EN: 🔀 Which face to start from. Faces sorted by size (0=largest, 1=2nd, etc.) • Index 0 = Start from largest face (main subject) • Index 1 = Skip largest, start from 2nd largest Selection wraps cyclically if more faces requested than found. RU: 🔀 С какого лица начать. Лица отсортированы по размеру (0=самое большое, 1=2-е и т.д.) • Индекс 0 = Начать с самого большого лица (главный объект) • Индекс 1 = Пропустить самое большое, начать со 2-го Выбор циклический, если запрошено больше лиц, чем найдено.
max_faces_per_imageINT501–1000EN: 🔍 Maximum faces detector will look for (safety limit). Different from 'number_of_faces': • max_faces_per_image = How many to DETECT (technical limit) • number_of_faces = How many to RETURN (your choice) RU: 🔍 Максимум лиц, которые детектор будет искать (предел безопасности). Отличается от 'number_of_faces': • max_faces_per_image = Сколько ОБНАРУЖИТЬ (технический лимит) • number_of_faces = Сколько ВЕРНУТЬ (ваш выбор)
aspect_ratioCOMBO1:1EN: 📐 Width-to-height ratio of the final crop. • 1:1 = Square (Instagram, avatars, face swaps) • 3:4 = Portrait (classic portrait orientation) • 16:9 = Widescreen (YouTube/video format) • 9:16 = Vertical (TikTok/Reels/Stories) RU: 📐 Соотношение ширины к высоте финального кропа. • 1:1 = Квадрат (Instagram, аватарки, замена лиц) • 3:4 = Портрет (классическая портретная ориентация) • 16:9 = Широкоформатный (YouTube/видео) • 9:16 = Вертикальный (TikTok/Reels/Stories)
confidence_thresholdFLOAT0.700.1–1EN: 🎯 Minimum confidence to accept a detected face (0.0-1.0). • 0.90-1.0 = Very strict (only 100% certain faces) • 0.70-0.85 = Balanced (recommended default) • 0.50-0.65 = Lenient (more faces, possible false positives) RU: 🎯 Минимальная уверенность для принятия обнаруженного лица (0.0-1.0). • 0.90-1.0 = Очень строго (только 100% уверенные лица) • 0.70-0.85 = Сбалансировано (рекомендуется по умолчанию) • 0.50-0.65 = Мягко (больше лиц, возможны ложные срабатывания)
divisible_byINT81–64EN: 🔢 Round output dimensions to multiples of N. Important for VAE/KSampler compatibility (they need dims divisible by 8/16/32). • 8 = Standard (works with most nodes, recommended) • 16 = Stricter (some VAE models) • 1 = No rounding (use only if you know why) RU: 🔢 Округлить размеры выхода до кратных N. Важно для совместимости с VAE/KSampler (требуют размеры кратные 8/16/32). • 8 = Стандарт (работает с большинством нод, рекомендуется) • 16 = Строже (некоторые модели VAE) • 1 = Без округления (используйте только если знаете зачем)
maskoptMASKEN: 🎭 Optional mask to limit where faces are detected. Only faces whose CENTER is in WHITE (bright) areas will be detected. • White (1.0) = Detector searches here • Black (0.0) = Detector ignores this area RU: 🎭 Опциональная маска для ограничения области поиска лиц. Будут обнаружены только лица, чей ЦЕНТР в БЕЛЫХ (ярких) областях. • Белый (1.0) = Детектор ищет здесь • Черный (0.0) = Детектор игнорирует эту область

Outputs (2)

NameTypeDescription
faceIMAGE
crop_dataCROP_DATA