detectNSFWFromImage method

Future<NsfwResult?> detectNSFWFromImage(
  1. Image image
)

Detects NSFW content from an image

Inference runs synchronously on the calling isolate. Use compute() or another background isolate if you need to keep the UI responsive.

Implementation

Future<NsfwResult?> detectNSFWFromImage(img.Image image) async {
  if (_isClosed) throw StateError('NsfwDetector has been closed.');
  if (_isRunning) {
    throw StateError(
      'NsfwDetector is already running an inference. Concurrent calls are not supported.',
    );
  }
  _isRunning = true;
  try {
    final resizedImage = img.copyResize(
      image,
      width: _kInputWidth,
      height: _kInputHeight,
    );

    final inputBuffer = _imageToInputBuffer(resizedImage);
    final output = <List<double>>[List<double>.filled(2, 0.0)];

    _interpreter.run(inputBuffer, output);

    final result = output.first;
    if (result.length < 2) {
      throw NsfwDetectorException(
        'Model output has unexpected shape: expected at least 2 values.',
      );
    }

    final score = result[1];
    return NsfwResult(isNsfw: score > _threshold, score: score, safeScore: result[0]);
  } catch (error, stackTrace) {
    if (error is NsfwDetectorException) {
      rethrow;
    }
    throw NsfwDetectorException(
      'Failed to detect NSFW content from image.',
      cause: error,
      stackTrace: stackTrace,
    );
  } finally {
    _isRunning = false;
  }
}