TensorFlow 2 implementation of the Yahoo Open-NSFW model

Overview

ci License MIT 1.0

Introduction

Detecting Not-Suitable-For-Work (NSFW) images is a high demand task in computer vision. While there are many types of NSFW images, here we focus on the pornographic images.

The Yahoo Open-NSFW model originally developed with the Caffe framework has been a favourite choice, but the work is now discontinued and Caffe is also becoming less popular. Please see the description on the Yahoo project page for the context, definitions, and model training details.

This Open-NSFW 2 project provides a TensorFlow 2 implementation of the Yahoo model, with references to its previous third-party TensorFlow 1 implementation.

Installation

Python 3.7 or above is required. Tested for 3.7, 3.8, and 3.9.

The best way to install Open-NSFW 2 with its dependencies is from PyPI:

python3 -m pip install --upgrade opennsfw2

Alternatively, to obtain the latest version from this repository:

git clone [email protected]:bhky/opennsfw2.git
cd opennsfw2
python3 -m pip install .

Usage

import numpy as np
import opennsfw2 as n2
from PIL import Image

# Load and preprocess image.
image_path = "path/to/your/image.jpg"
pil_image = Image.open(image_path)
image = n2.preprocess_image(pil_image, n2.Preprocessing.YAHOO)
# The preprocessed image is a NumPy array of shape (224, 224, 3).

# Create the model.
# By default, this call will search for the pre-trained weights file from path:
# $HOME/.opennsfw2/weights/open_nsfw_weights.h5
# If not exists, the file will be downloaded from this repository.
# The model is a `tf.keras.Model` object.
model = n2.make_open_nsfw_model()

# Make predictions.
inputs = np.expand_dims(image, axis=0)  # Add batch axis (for single image).
predictions = model.predict(inputs)

# The shape of predictions is (batch_size, 2).
# Each row gives [sfw_probability, nsfw_probability] of an input image, e.g.:
sfw_probability, nsfw_probability = predictions[0]

Alternatively, the end-to-end pipeline function can be used:

import opennsfw2 as n2

image_paths = [
    "path/to/your/image1.jpg",
    "path/to/your/image2.jpg",
    # ...
]

predictions = n2.predict(
    image_paths, batch_size=4, preprocessing=n2.Preprocessing.YAHOO
)

API

preprocess_image

Apply necessary preprocessing to the input image.

  • Parameters:
    • pil_image (PIL.Image): Input as a Pillow image.
    • preprocessing (Preprocessing enum, default Preprocessing.YAHOO): See preprocessing details.
  • Return:
    • NumPy array of shape (224, 224, 3).

Preprocessing

Enum class for preprocessing options.

  • Preprocessing.YAHOO
  • Preprocessing.SIMPLE

make_open_nsfw_model

Create an instance of the NSFW model, optionally with pre-trained weights from Yahoo.

  • Parameters:
    • input_shape (Tuple[int, int, int], default (224, 224, 3)): Input shape of the model, this should not be changed.
    • weights_path (Optional[str], default $HOME/.opennsfw/weights/open_nsfw_weights.h5): Path to the weights in HDF5 format to be loaded by the model. The weights file will be downloaded if not exists. Users can provide path if the default is not preferred. If None, no weights will be downloaded nor loaded to the model.
  • Return:
    • tf.keras.Model object.

predict

End-to-end pipeline function from input image paths to predictions.

  • Parameters:
    • image_paths (Sequence[str]): List of paths to input image files.
    • batch_size (int, default 32): Batch size to be used for model inference.
    • preprocessing: Same as that in preprocess_image.
    • weights_path: Same as that in make_open_nsfw_model.
  • Return:
    • NumPy array of shape (batch_size, 2), each row gives [sfw_probability, nsfw_probability] of an input image.

Preprocessing details

Options

This implementation provides the following preprocessing options.

  • YAHOO: The default option which was used in the original Yahoo's Caffe and the later TensorFlow 1 implementations. The key steps are:
    • Resize the input Pillow image to (256, 256).
    • Save the image as JPEG bytes and reload again to a NumPy image (this step is mysterious, but somehow it really makes a difference).
    • Crop the centre part of the NumPy image with size (224, 224).
    • Swap the colour channels to BGR.
    • Subtract the training dataset mean value of each channel: [104, 117, 123].
  • SIMPLE: A simpler and probably more intuitive preprocessing option is also provided, but note that the model output probabilities will be different. The key steps are:
    • Resize the input Pillow image to (224, 224).
    • Convert to a NumPy image.
    • Swap the colour channels to BGR.
    • Subtract the training dataset mean value of each channel: [104, 117, 123].

Comparison

Using 521 private images, the NSFW probabilities given by three different settings are compared:

  • TensorFlow 1 implementation with YAHOO preprocessing.
  • TensorFlow 2 implementation with YAHOO preprocessing.
  • TensorFlow 2 implementation with SIMPLE preprocessing.

The following figure shows the result:

NSFW probabilities comparison

The current TensorFlow 2 implementation with YAHOO preprocessing can totally reproduce the well-tested TensorFlow 1 result, with small floating point errors only.

With SIMPLE preprocessing the results are different, where the model tends to give lower probabilities.

You might also like...
Deploy tensorflow graphs for fast evaluation and export to tensorflow-less environments running numpy.
Deploy tensorflow graphs for fast evaluation and export to tensorflow-less environments running numpy.

Deploy tensorflow graphs for fast evaluation and export to tensorflow-less environments running numpy. Now with tensorflow 1.0 support. Evaluation usa

TensorFlow Ranking is a library for Learning-to-Rank (LTR) techniques on the TensorFlow platform
TensorFlow Ranking is a library for Learning-to-Rank (LTR) techniques on the TensorFlow platform

TensorFlow Ranking is a library for Learning-to-Rank (LTR) techniques on the TensorFlow platform

Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!
Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!

Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!

Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!
Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!

Robust Video Matting (RVM) English | 中文 Official repository for the paper Robust High-Resolution Video Matting with Temporal Guidance. RVM is specific

Open-AI's DALL-E for large scale training in mesh-tensorflow.

DALL-E in Mesh-Tensorflow [WIP] Open-AI's DALL-E in Mesh-Tensorflow. If this is similarly efficient to GPT-Neo, this repo should be able to train mode

Using Tensorflow Object Detection API to detect Waymo open dataset
Using Tensorflow Object Detection API to detect Waymo open dataset

Waymo-2D-Object-Detection Using Tensorflow Object Detection API to detect Waymo open dataset Result CenterNet Training Loss SSD ResNet Training Loss C

Implementation of STAM (Space Time Attention Model), a pure and simple attention model that reaches SOTA for video classification
Implementation of STAM (Space Time Attention Model), a pure and simple attention model that reaches SOTA for video classification

STAM - Pytorch Implementation of STAM (Space Time Attention Model), yet another pure and simple SOTA attention model that bests all previous models in

😇A pyTorch implementation of the DeepMoji model: state-of-the-art deep learning model for analyzing sentiment, emotion, sarcasm etc

------ Update September 2018 ------ It's been a year since TorchMoji and DeepMoji were released. We're trying to understand how it's being used such t

Mesh TensorFlow: Model Parallelism Made Easier

Mesh TensorFlow - Model Parallelism Made Easier Introduction Mesh TensorFlow (mtf) is a language for distributed deep learning, capable of specifying

Comments
  • ERROR WITH NO ERROR

    ERROR WITH NO ERROR

    Hi, I don't understand what happened with opennsfw2 code. My installation is OK. I install Keras and Tensorflow 2.0 with CUDA but nothing, Any idea ? I attached a screenshot. Thank you to help me 0008_2022-09-10_17_heures_18

    opened by fog88 7
  • Which NSFW Area is this AI covering?

    Which NSFW Area is this AI covering?

    Hi,

    very cool project, I am looking for an AI, which can cover on the one side nudity, but doesn't judge sexy images and also bans traumatic images, like horror and the crazy things, like NSFW 4 things, is it possible with this AI?

    nsfw-chart

    I found this image online, which is your AI covering?

    Thanks!

    opened by Flori00123 5
  • small demo website

    small demo website

    would be nice to have a small website that allows users to demo the model instead of having to run it all, such as https://maybeshewill-cv.github.io/nsfw_classification/

    opened by DankMemeGuy 1
Releases(v0.10.2)
Owner
Bosco Yung
Machine Learning Engineer, Lecturer, Astrophysicist
Bosco Yung
Implicit Deep Adaptive Design (iDAD)

Implicit Deep Adaptive Design (iDAD) This code supports the NeurIPS paper 'Implicit Deep Adaptive Design: Policy-Based Experimental Design without Lik

Desi 12 Aug 14, 2022
Find the Heart simple Python Game

This is a simple Python game for finding a heart emoji. There is a 3 x 3 matrix in which a heart emoji resides. The location of the heart is randomized and is not revealed. The player must guess the

p.katekomol 1 Jan 24, 2022
Pip-package for trajectory benchmarking from "Be your own Benchmark: No-Reference Trajectory Metric on Registered Point Clouds", ECMR'21

Map Metrics for Trajectory Quality Map metrics toolkit provides a set of metrics to quantitatively evaluate trajectory quality via estimating consiste

Mobile Robotics Lab. at Skoltech 31 Oct 28, 2022
A TensorFlow implementation of Neural Program Synthesis from Diverse Demonstration Videos

ViZDoom http://vizdoom.cs.put.edu.pl ViZDoom allows developing AI bots that play Doom using only the visual information (the screen buffer). It is pri

Hyeonwoo Noh 1 Aug 19, 2020
Numerical differential equation solvers in JAX. Autodifferentiable and GPU-capable.

Diffrax Numerical differential equation solvers in JAX. Autodifferentiable and GPU-capable. Diffrax is a JAX-based library providing numerical differe

Patrick Kidger 717 Jan 09, 2023
Walk with fastai

Shield: This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Walk with fastai What is this p

Walk with fastai 124 Dec 10, 2022
A Bayesian cognition approach for belief updating of correlation judgement through uncertainty visualizations

Overview Code and supplemental materials for Karduni et al., 2020 IEEE Vis. "A Bayesian cognition approach for belief updating of correlation judgemen

Ryan Wesslen 1 Feb 08, 2022
Neural Radiance Fields Using PyTorch

This project is a PyTorch implementation of Neural Radiance Fields (NeRF) for reproduction of results whilst running at a faster speed.

Vedant Ghodke 1 Feb 11, 2022
Defense-GAN: Protecting Classifiers Against Adversarial Attacks Using Generative Models (published in ICLR2018)

Defense-GAN: Protecting Classifiers Against Adversarial Attacks Using Generative Models Pouya Samangouei*, Maya Kabkab*, Rama Chellappa [*: authors co

Maya Kabkab 212 Dec 07, 2022
Styled text-to-drawing synthesis method. Featured at the 2021 NeurIPS Workshop on Machine Learning for Creativity and Design

Styled text-to-drawing synthesis method. Featured at the 2021 NeurIPS Workshop on Machine Learning for Creativity and Design

Peter Schaldenbrand 247 Dec 23, 2022
Hypersearch weight debugging and losses tutorial

tutorial Activate tensorboard option Running TensorBoard remotely When working on a remote server, you can use SSH tunneling to forward the port of th

1 Dec 11, 2021
Custom TensorFlow2 implementations of forward and backward computation of soft-DTW algorithm in batch mode.

Batch Soft-DTW(Dynamic Time Warping) in TensorFlow2 including forward and backward computation Custom TensorFlow2 implementations of forward and backw

19 Aug 30, 2022
Gif-caption - A straightforward GIF Captioner written in Python

Broksy's GIF Captioner Have you ever wanted to easily caption a GIF without havi

3 Apr 09, 2022
OBBDetection is a oriented object detection library, which is based on MMdetection.

OBBDetection news: We are now updating OBBDetection to new vision based on MMdetection v2.10, which has more advanced models and more efficient featur

jbwang1997 401 Jan 02, 2023
Framework to build and train RL algorithms

RayLink RayLink is a RL framework used to build and train RL algorithms. RayLink was used to build a RL framework, and tested in a large-scale multi-a

Bytedance Inc. 32 Oct 07, 2022
Implementation of Pooling by Sliced-Wasserstein Embedding (NeurIPS 2021)

PSWE: Pooling by Sliced-Wasserstein Embedding (NeurIPS 2021) PSWE is a permutation-invariant feature aggregation/pooling method based on sliced-Wasser

Navid Naderializadeh 3 May 06, 2022
This is the official implementation of our proposed SwinMR

SwinMR This is the official implementation of our proposed SwinMR: Swin Transformer for Fast MRI Please cite: @article{huang2022swin, title={Swi

A Yang Lab (led by Dr Guang Yang) 27 Nov 17, 2022
ROS Basics and TurtleSim

Waypoint Follower Anna Garverick This package draws given waypoints, then waits for a service call with a start position to send the turtle to each wa

Anna Garverick 1 Dec 13, 2021
JAXMAPP: JAX-based Library for Multi-Agent Path Planning in Continuous Spaces

JAXMAPP: JAX-based Library for Multi-Agent Path Planning in Continuous Spaces JAXMAPP is a JAX-based library for multi-agent path planning (MAPP) in c

OMRON SINIC X 24 Dec 28, 2022
QMagFace: Simple and Accurate Quality-Aware Face Recognition

Quality-Aware Face Recognition 26.11.2021 start readme QMagFace: Simple and Accurate Quality-Aware Face Recognition Research Paper Implementation - To

Philipp Terhörst 59 Jan 04, 2023