{"id":13901200,"url":"https://github.com/bhky/opennsfw2","last_synced_at":"2025-05-16T08:04:44.642Z","repository":{"id":40263542,"uuid":"423429898","full_name":"bhky/opennsfw2","owner":"bhky","description":"Keras implementation of the Yahoo Open-NSFW model","archived":false,"fork":false,"pushed_at":"2025-01-24T00:02:16.000Z","size":49775,"stargazers_count":423,"open_issues_count":1,"forks_count":58,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-05-15T01:19:49.827Z","etag":null,"topics":["image-classification","image-preprocessing","jax","keras","nsfw-classifier","tensorflow2"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bhky.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["bhky"]}},"created_at":"2021-11-01T10:51:43.000Z","updated_at":"2025-05-13T03:29:12.000Z","dependencies_parsed_at":"2024-01-16T12:47:08.483Z","dependency_job_id":"c313496b-3690-4cd0-ba73-73d3eb020eca","html_url":"https://github.com/bhky/opennsfw2","commit_stats":{"total_commits":217,"total_committers":1,"mean_commits":217.0,"dds":0.0,"last_synced_commit":"4ac0ebcdcb3ea9ef9c014466577ce4f338c2ffac"},"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bhky%2Fopennsfw2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bhky%2Fopennsfw2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bhky%2Fopennsfw2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bhky%2Fopennsfw2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bhky","download_url":"https://codeload.github.com/bhky/opennsfw2/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254493378,"owners_count":22080126,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["image-classification","image-preprocessing","jax","keras","nsfw-classifier","tensorflow2"],"created_at":"2024-08-06T21:00:59.698Z","updated_at":"2025-05-16T08:04:39.635Z","avatar_url":"https://github.com/bhky.png","language":"Python","funding_links":["https://github.com/sponsors/bhky"],"categories":["Python"],"sub_categories":[],"readme":"![logo](logo/opennsfw2_logo.png)\n\n[![ci](https://github.com/bhky/opennsfw2/actions/workflows/ci.yml/badge.svg)](https://github.com/bhky/opennsfw2/actions)\n[![License MIT 1.0](https://img.shields.io/badge/license-MIT%201.0-blue.svg)](LICENSE)\n\n# Introduction\n\nDetecting Not-Suitable-For-Work (NSFW) content is a high demand task in \ncomputer vision. While there are many types of NSFW content, here we focus on\nthe pornographic images and videos.\n\nThe [Yahoo Open-NSFW model](https://github.com/yahoo/open_nsfw) originally\ndeveloped with the Caffe framework has been a favourite choice, but the work \nis now discontinued and Caffe is also becoming less popular.\nPlease see the description on the Yahoo project page for\nthe context, definitions, and model training details.\n\nThis **Open-NSFW 2** project provides a Keras implementation of the\nYahoo model, with references to its previous third-party \n[TensorFlow 1 implementation](https://github.com/mdietrichstein/tensorflow-open_nsfw).\nNote that **Keras 3** is compatible with \nTensorFlow, JAX, and PyTorch. However, currently this model is\nonly guaranteed to work with TensorFlow and JAX.\n\nA simple API is provided for making predictions on images and videos.\n\n# Installation\n\nTested with TensorFlow and JAX, for Python 3.9 to 3.12.\n\nA note on PyTorch:\n\nThe OpenNSFW 2 model can in fact be run on PyTorch, but the biggest issue is \nthat the inference output on PyTorch is quite different from \nthat on TensorFlow and JAX. The reason is still unknown. In addition, \ninference is much slower on PyTorch probably because of the issues \ndiscussed [here](https://keras.io/keras_core/announcement/),\ni.e., PyTorch uses `channels_first` for its image data format, but this model\nuses `channels_last` (as in TensorFLow and JAX), hence Keras has to \nconvert the channel order back and forth at each layer.\nTherefore, at the moment it is not recommended to use PyTorch for this model.\n\nThe best way to install Open-NSFW 2 with its dependencies is from PyPI:\n```shell\npython3 -m pip install --upgrade opennsfw2\n```\nAlternatively, to obtain the latest version from this repository:\n```shell\ngit clone git@github.com:bhky/opennsfw2.git\ncd opennsfw2\npython3 -m pip install .\n```\n\n# Usage\n\nQuick examples for getting started are given below.\nFor more details, please refer to the [API](#api) section.\n\n## Images\n\n```python\nimport opennsfw2 as n2\n\n# To get the NSFW probability of a single image, provide your image file path,\n# or a `PIL.Image.Image` object.\nimage_handle = \"path/to/your/image.jpg\"\n\nnsfw_probability = n2.predict_image(image_handle)\n\n# To get the NSFW probabilities of a list of images, provide a list of file paths,\n# or a list of `PIL.Image.Image` objects.\n# Using this function is better than looping with `predict_image` as the model \n# will only be instantiated once and batching is done during inference.\nimage_handles = [\n  \"path/to/your/image1.jpg\",\n  \"path/to/your/image2.jpg\",\n  # ...\n]\n\nnsfw_probabilities = n2.predict_images(image_handles)\n```\n\n## Video\n\n```python\nimport opennsfw2 as n2\n\n# The video can be in any format supported by OpenCV.\nvideo_path = \"path/to/your/video.mp4\"\n\n# Return two lists giving the elapsed time in seconds and the NSFW probability of each frame.\nelapsed_seconds, nsfw_probabilities = n2.predict_video_frames(video_path)\n```\n\n## Lower level with Keras\n\n```python\nimport numpy as np\nimport opennsfw2 as n2\nfrom PIL import Image\n\n# Load and preprocess image.\nimage_path = \"path/to/your/image.jpg\"\npil_image = Image.open(image_path)\nimage = n2.preprocess_image(pil_image, n2.Preprocessing.YAHOO)\n# The preprocessed image is a NumPy array of shape (224, 224, 3).\n\n# Create the model.\n# By default, this call will search for the pre-trained weights file from path:\n# $HOME/.opennsfw2/weights/open_nsfw_weights.h5\n# If not exists, the file will be downloaded from this repository.\n# The model is a `keras_core.Model` object.\nmodel = n2.make_open_nsfw_model()\n\n# Make predictions.\ninputs = np.expand_dims(image, axis=0)  # Add batch axis (for single image).\npredictions = model.predict(inputs)\n\n# The shape of predictions is (num_images, 2).\n# Each row gives [sfw_probability, nsfw_probability] of an input image, e.g.:\nsfw_probability, nsfw_probability = predictions[0]\n```\n\n# API\n\n### `preprocess_image`\nApply necessary preprocessing to the input image.\n- Parameters:\n  - `pil_image` (`PIL.Image.Image`): Input as a Pillow image.\n  - `preprocessing` (`Preprocessing` enum, default `Preprocessing.YAHOO`): \n    See [preprocessing details](#preprocessing-details).\n- Return:\n  - NumPy array of shape `(224, 224, 3)`.\n\n### `Preprocessing`\nEnum class for preprocessing options.\n- `Preprocessing.YAHOO`\n- `Preprocessing.SIMPLE`\n\n### `make_open_nsfw_model`\nCreate an instance of the NSFW model, optionally with pre-trained weights from Yahoo.\n- Parameters:\n  - `input_shape` (`Tuple[int, int, int]`, default `(224, 224, 3)`):\n    Input shape of the model, this should not be changed.\n  - `weights_path` (`Optional[str]`, default `$HOME/.opennsfw/weights/open_nsfw_weights.h5`): \n    Path to the weights in HDF5 format to be loaded by the model. \n    The weights file will be downloaded if not exists.\n    If `None`, no weights will be downloaded nor loaded to the model.\n    Users can provide path if the default is not preferred. \n    The environment variable `OPENNSFW2_HOME` can also be used to indicate\n    where the `.opennsfw2/` directory should be located.\n  - `name` (`str`, default `opennsfw2`): Model name to be used for the Keras model object.\n- Return:\n  - `tf.keras.Model` object.\n\n### `predict_image`\nEnd-to-end pipeline function from the input image to the predicted NSFW probability.\n- Parameters:\n  - `image_handle` (`Union[str, PIL.Image.Image]`):\n    Path to the input image file with a format supported by Pillow, or a `PIL.Image.Image` object.\n  - `preprocessing`: Same as that in `preprocess_image`.\n  - `weights_path`: Same as that in `make_open_nsfw_model`.\n  - `grad_cam_path` (`Optional[str]`, default `None`): If not `None`, e.g., `cam.jpg`,\n    a [Gradient-weighted Class Activation Mapping (Grad-CAM)](https://keras.io/examples/vision/grad_cam/) \n    overlay plot will be saved, which highlights the important region(s) of the \n    (preprocessed) input image that lead to the prediction.\n    Note that this feature is currently only supported by the TensorFlow backend.\n  - `alpha` (`float`, default `0.8`): Opacity of the Grad-CAM layer of the plot,\n    only valid if `grad_cam_path` is not `None`.\n- Return:\n  - `nsfw_probability` (`float`): The predicted NSFW probability of the image.\n\n### `predict_images`\nEnd-to-end pipeline function from the input images to the predicted NSFW probabilities.\n- Parameters:\n  - `image_handles` (`Union[Sequence[str], Sequence[PIL.Image.Image]]`):\n    List of paths to the input image files with formats supported by Pillow,\n    or list of `PIL.Image.Image` objects.\n  - `batch_size` (`int`, default `8`): Batch size to be used for model inference. \n    Choose a value that works the best with your device resources.\n  - `preprocessing`: Same as that in `preprocess_image`.\n  - `weights_path`: Same as that in `make_open_nsfw_model`.\n  - `grad_cam_paths` (`Optional[Sequence[str]]`, default `None`): If not `None`,\n    the corresponding Grad-CAM plots for the input images will be saved.\n    See the description in `predict_image`.\n    Note that this feature is currently only supported by the TensorFlow backend.\n  - `alpha`: Same as that in `predict_image`.\n- Return:\n  - `nsfw_probabilities` (`List[float]`): Predicted NSFW probabilities of the images.\n\n### `Aggregation`\nEnum class for aggregation options in video frames prediction.\n- `Aggregation.MEAN`\n- `Aggregation.MEDIAN`\n- `Aggregation.MAX`\n- `Aggregation.MIN`\n\n### `predict_video_frames`\nEnd-to-end pipeline function from the input video to predictions.\n- Parameters:\n  - `video_path` (`str`): Path to the input video source. \n    The video format must be supported by OpenCV.\n  - `frame_interval` (`int`, default `8`): Prediction will be done on every this \n    number of frames, starting from frame 1, i.e., if this is 8, then \n    prediction will only be done on frame 1, 9, 17, etc.\n  - `aggregation_size` (`int`, default `8`):\n    Number of frames for which their predicted NSFW probabilities will be aggregated.\n    For instance, if a prediction will be done \"on\" frame 9 (decided by `frame_interval`),\n    then it actually means prediction will be done on `aggregation_size` frames \n    starting from frame 9, e.g., frames 9 to 16 if the size is 8. \n    The predicted probabilities will be aggregated. After aggregation, \n    each of these frames in that interval will be assumed the same aggregated probability.\n  - `aggregation` (`Aggregation` enum, default `Aggregation.MEAN`): \n    The aggregation method.\n  - `batch_size` (`int`, default `8`, upper-bounded by `aggregation_size`): \n    Batch size to be used for model inference. Choose a value that works the best \n    with your device resources.\n  - `output_video_path` (`Optional[str]`, default `None`): \n    If not `None`, e.g., `out.mp4`,\n    an output MP4 video with the same frame size and frame rate as\n    the input video will be saved via OpenCV. The predicted NSFW probability \n    is printed on the top-left corner of each frame. Be aware that the output \n    file size could be much larger than the input file size.\n    This output video is for reference only.\n  - `preprocessing`: Same as that in `preprocess_image`.\n  - `weights_path`: Same as that in `make_open_nsfw_model`.\n  - `progress_bar` (`bool`, default `True`): Whether to show the progress bar.\n- Return:\n  - Tuple of `List[float]`, each with length equals to the number of video frames.\n    - `elapsed_seconds`: Video elapsed time in seconds at each frame.\n    - `nsfw_probabilities`: NSFW probability of each frame. \n      For any `frame_interval \u003e 1`, all frames without a prediction \n      will be assumed to have the NSFW probability of the previous predicted frame.\n\n# Preprocessing details\n\nThis implementation provides the following preprocessing options.\n- `YAHOO`: The default option which was used in the original \n  [Yahoo's Caffe](https://github.com/yahoo/open_nsfw/blob/master/classify_nsfw.py#L19-L80) \n  and the later \n  [TensorFlow 1](https://github.com/mdietrichstein/tensorflow-open_nsfw/blob/master/image_utils.py#L4-L53) \n  implementations. The key steps are:\n  - Resize the input Pillow image to `(256, 256)`.\n  - Store the image as JPEG in memory and reload it again to a NumPy image \n    (this step is mysterious, but somehow it really makes a difference).\n  - Crop the centre part of the NumPy image with size `(224, 224)`.\n  - Swap the colour channels to BGR.\n  - Subtract the training dataset mean value of each channel: `[104, 117, 123]`.\n- `SIMPLE`: A simpler and probably more intuitive preprocessing option is also provided,\n  but note that the model output probabilities will be different.\n  The key steps are:\n  - Resize the input Pillow image to `(224, 224)`.\n  - Convert to a NumPy image.\n  - Swap the colour channels to BGR.\n  - Subtract the training dataset mean value of each channel: `[104, 117, 123]`.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbhky%2Fopennsfw2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbhky%2Fopennsfw2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbhky%2Fopennsfw2/lists"}