NudeNet

repository·main·Indexed 18 days ago

https://github.com/vladmandic/nudenet

An NSFW object detection library for TensorFlow.js (TFJS) and NodeJS designed to detect people and specific exposed body parts in images and videos. Version 0.3.0 provides tools for high-level classifications (person, sexy, nude) and detailed body part detection with bounding boxes and confidence scores. It supports NodeJS CLI usage, browser-based TypeScript implementation, and video processing via ffmpeg.

Tokens
1.6K
Snippets
4
Records
7
Agent score
13%

What's inside nudenet

  1. Implementation examples for different environments

    main

    NudeNet provides different implementation examples depending on your target runtime:

    • NodeJS Image Processing: See src/nudenet.js.
    • NodeJS Video Processing: See src/node-video.js. Note that this requires additional dependencies: @tensorflow/tfjs-node-gpu, pipe2jpeg, and a functional installation of ffmpeg.
    • Browser (TypeScript): See src/index.html and src/index.ts. The TypeScript code is transpiled to dist/index.js for browser use.
  2. Understand NudeNet detection results and composite categories

    main

    The detection process returns a result object containing raw parts and high-level composite classifications.

    Result Structure

    • input: Object containing { width, height } of the processed input.
    • parts: An array of detected objects. Each object contains:
      • score: Confidence score (0-1).
      • id: The integer class ID.
      • class: The human-readable label (e.g., 'breast', 'vagina').
      • box: The bounding box in [x, y, width, height] format.
    • person: Boolean, true if any part belonging to the person composite is detected.
    • sexy: Boolean, true if any part belonging to the sexy composite is detected.
    • nude: Boolean, true if any part belonging to the nude composite is detected.

    Composite Definitions

    NudeNet categorizes specific class IDs into three main groups:

    • person: Includes IDs like female face and male face.
    • sexy: Includes IDs like exposed armpits, belly, and feet.
    • nude: Includes IDs like exposed anus, buttocks, and vagina.
  3. Implement the NudeNet detection loop in the browser

    main

    To run NudeNet on a video stream in the browser, follow these steps:

    1. Initialize TensorFlow.js: Set the backend to webgpu (if available) or webgl. Enable WEBGL_USE_SHAPES_UNIFORMS for performance.
    2. Load the Model: Use tf.loadGraphModel(options.modelPath) to load the NudeNet graph model.
    3. Process Frames:
      • Convert the video frame to a tensor using tf.browser.fromPixelsAsync(video).
      • Resize the tensor to the desired options.resolution.
      • Execute the model using model.executeAsync(t.batch, options.outputNodes).
      • Process the resulting tensors (boxes, scores, classes) through Non-Max Suppression (NMS).
    4. Cleanup: Always use tf.dispose() on tensors to prevent memory leaks.
    // Simplified logic flow for a detection loop
    [t.boxes, t.scores, t.classes] = await model.executeAsync(t.batch, options.outputNodes);
    const res = await processPrediction(t.boxes, t.scores, t.classes, t.cast);
    
    // Cleanup tensors
    Object.keys(t).forEach((tensor) => tf.dispose(t[tensor]));
  4. Run NudeNet via NodeJS CLI

    main

    You can run the NudeNet detection via the command line in a NodeJS environment. Use the -i flag to specify the input image and the -o flag to specify the output image path (which will include any applied blurring).

    Example command: node src/nudenet.js -i samples/nude.jpg -o samples/nude-out.jpg

    node src/nudenet.js -i samples/nude.jpg -o samples/nude-out.jpg
  5. Configure NudeNet detection options

    main

    When using NudeNet in a browser environment, you can control the detection behavior using an options object. Key configuration parameters include:

    • modelPath: Path to the model.json file.
    • minScore: Minimum confidence threshold for a detection (e.g., 0.38).
    • maxResults: Maximum number of detections to return.
    • iouThreshold: Intersection over Union threshold for Non-Max Suppression (NMS).
    • outputNodes: Array of strings representing the model's output node names (e.g., ['output1', 'output2', 'output3']).
    • resolution: A [number, number] tuple defining the input resolution for the model (e.g., [1280, 720]).
    • blurRadius: Controls the intensity of the blur effect when applying redaction.
    const options = {
      modelPath: '../models/default-f16/model.json',
      videoPath: '../samples/video.webm',
      minScore: 0.38,
      maxResults: 50,
      iouThreshold: 0.5,
      outputNodes: ['output1', 'output2', 'output3'],
      blurRadius: 25,
      resolution: [1280, 720] as [number, number],
    };
  6. Understand the NudeNet detection output format

    main

    NudeNet returns a structured object containing metadata about the input image and detection results. The results include boolean flags for high-level classifications (person, sexy, nude) and a detailed parts array for specific body part detections.

    Output Object Schema:

    • input: Object containing file (String), width (Number), and height (Number).
    • person: Boolean indicating if a person was detected.
    • sexy: Boolean indicating if the person is considered sexy.
    • nude: Boolean indicating if the person is considered nude.
    • parts: Array of detected body parts, where each part contains:
      • score: Confidence score (Number).
      • id: Detection ID (Number).
      • class: Label for the body part (String).
      • box: Bounding box coordinates as [x, y, width, height] (Number[]).
    {
      input: {
        file: String,
        width: Number,
        height: Number,
      },
      person: Boolean,
      sexy: Boolean,
      nude: Boolean,
      parts: Array<{ 
        score: Number,
        id: Number,
        class: String,
        box: Number[],
      }],
    }
  7. Reference the available body part classes

    main

    The labels returned in the class field of the parts array depend on which model variation is being used (base or default).

    Base Model Classes:

    • exposed belly
    • exposed buttocks
    • exposed breasts
    • exposed vagina
    • exposed penis
    • male breast

    Default Model Classes:

    • exposed anus
    • exposed armpits
    • belly
    • exposed belly
    • buttocks
    • exposed buttocks
    • female face
    • male face
    • feet
    • exposed feet
    • breast
    • exposed breast
    • vagina
    • exposed vagina
    • male breast
    • exposed penis