Securing Images in Python With the Imagga NSFW Categorization API

In web and mobile applications, as well as any other digital media, the use of images as part of their content is very common. With images being so ubiquitous, there comes a need to ensure that the images posted are appropriate to the medium they are on. This is especially true for any medium accepting user-generated content. Even with set rules for what can and cannot be posted, you can never trust users to adhere to the set conditions. Whenever you have a website or medium accepting user-generated content, you will find that there is a need to moderate the content.

Why Moderate Content?

There are various reasons why content moderation might be in your best interest as the owner/maintainer of a digital medium. Some common ones are:

  • Legal obligations - If your application accommodates underaged users, then you are obligated to protect them from adult content.
  • Brand protection - How your brand is perceived by users is important, so you might want to block some content that may negatively affect your image.
  • Protect your users - You might want to protect your users against harassment from other users. The harassment can be in the form of users attacking others by posting offensive content. An example of this is Facebook’s recent techniques of combating revenge p0rn on their platform.
  • Financial - It might be in your best interest financially, to moderate the content shown on your applications. For instance, if your content is somewhat problematic, other businesses might not want to associate with you in terms of advertising on your platform or accepting you as an affiliate for them. For some Ad networks, keeping your content clean is a rule that you have to comply with if you want to use them. Google Adsense is an example of this. They strictly forbid users of the service from placing their ads on pages with adult content.
  • Platform rules - You might be forced to implement some form of content moderation if the platform your application is on requires it. For instance,Apple requires applications to have a way of moderating and restricting user-generated content before they can be placed on the App Store and Google also restricts apps that contain sexually explicit content

As you can see, if your application accepts user-generated content, moderation might be a requirement that you can’t ignore. There are different ways moderation can be carried out:

  • Individual driven - an example of this is a website that has admins that moderate the content. The website might work by either restricting the display of any uploaded content until it has been approved by an admin or it might allow immediate display of uploaded content, but have admins who constantly check posted content. This method tends to be very accurate in identifying inappropriate content, as the admins will most likely be clear as to what is appropriate/inappropriate for the medium. The obvious problem with this is the human labor needed. Hiring moderators might get costly especially as the application’s usage grows. Relying on human moderators can also affect the app’s user experience. The human response will always be slower than an automated one. Even if you have people working on moderation at all times, there will still be a delay in identifying and removing problematic content. By the time it is removed, a lot of users could have seen it. On systems that restrict showing uploaded content until it has been approved by an admin, this delay can become annoying to users.
  • Community driven - with this type of moderation, the owner of the application puts in place features that enable the app’s users to report any inappropriate content e.g. flagging the content. After a user flags a post, an admin will then be notified. This also suffers from a delay in identifying inappropriate content from both the community (who might not act immediately the content is posted) and the administrators (who might be slow to respond to flagged content). Leaving moderation up to the community might also result in reported false positives as content that is safe is seen by some users as inappropriate. With a large community, you will always have differing opinions, and because many people will probably not have read the Terms and Conditions of the medium, they will not have clear-cut rules of what is and isn’t okay.
  • Automated - with this, a computer system usually using some machine learning algorithm is used to classify and identify problematic content. It can then act by removing the content or flagging it and notifying an admin. With this, there is a decreased need for human labor, but the downside is that it might be less accurate than a human moderator.
  • A mix of some or all the above methods - Each of the methods described above comes with a shortcoming. The best outcome might be achieved by combining some or all of them e.g. you might have in place an automated system that flags suspicious content while at the same time enabling the community to also flag content. An admin can then come in to determine what to do with the content.

A Look at the Imagga NSFW Categorization API

Imagga makes available the NSFW (not safe for work) Categorization API that you can use to build a system that can detect adult content. The API works by categorizing images into three categories:

  • nsfw - these are images considered not safe. Chances are high that they contain ponographic content and/or display nude bodies or inappropriate body parts.
  • underwear - this categorizes medium safe images. These might be images displaying lingerie, underwear, swimwear, e.t.c.
  • safe - these are completely safe images with no nudity.

The API works by giving a confidence level of a submitted image. The confidence is a percentage that indicates the probability of an image belonging to a certain category.

To see the NSFW API in action, we’ll create two simple programs that will process some images using the API. The first program will demonstrate how to categorize a single image while the second will batch process several images.

Setting up the Environment

Before writing any code, we’ll first set up a virtual environment. This isn’t necessary but is recommended as it prevents package clutter and version conflicts in your system’s global Python interpreter.

First, create a directory where you’ll put your code files.

[cc lang="bash"]$ mkdir nsfw_test[/cc]

Then navigate to that directory with your Terminal application.

[cc lang="bash"]$ cd nsfw_test[/cc]

Create the virtual environment by running:

[cc lang="bash"]$ python3 -m venv venv[/cc]

We’ll use Python 3 in our code. In the above, we create a virtual environment with Python 3. With this, the default Python version inside the virtual environment will be version 3.

Activate the environment with (on MacOS and Linux):

[cc lang="bash"]$ source venv/bin/activate[/cc]

On Windows:

[cc lang="bash"]$ venv\Scripts\activate[/cc]

Categorizing Images

To classify an image with the NSFW API, you can either send a GET request with the image URL to the [cci]/categories/<categorizer_id>[/cci] endpoint or you can upload the image to [cci]/uploads[/cci], get back a [cci]upload_id[/cci] value which you will then use in the call to the [cci]/categories/<categorizer_id>/[/cci] endpoint. We’ll create two applications that demonstrate these two scenarios.

Processing a Single Image

The first app we’ll create is a simple web application that can be used to check if an image is safe or not. We’ll create the app with Flask.

To start off, install the following dependencies.

[cc lang="bash"]$ pip install flask flask-bootstrap requests[/cc]

Then create a folder named [cci]templates[/cci] and inside that folder, create a file named [cci]index.html[/cci] and add the following code to it.

{% extends "bootstrap/base.html" %}

{% block title %}Imagga NSFW API Test{% endblock %}

{% block navbar %}

<nav class="navbar navbar-inverse" role="navigation">
<div class="container"><a class="navbar-brand" href="{{ url_for('index') }}">NSFW API Test</a></div>
</nav>{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-8">
            <form action="" method="POST">

                <div class="form-group">
                    <label for="image_url">Image URL</label>
                    <input type="url" id="image_url" name="image_url"/>
                    <button class="btn btn-primary" type="submit">Submit</button>

    {% if image_url %}
    <div class="row">
        <div class="col-md-4"><img class="img-thumbnail" src="{{ image_url }}" /></div>
        <div class="col-md-4">{{ res }}</div>
    {% endif %}

{% endblock %}

In the above code, we create an HTML template containing a form that the user can use to submit an image URL to the Imagga API. When the response comes back from the server, it will be shown next to the processed image.

Next, create a file named [cci][/cci] in the root directory of your project and add the following code to it. Be sure to replace [cci]INSERT_API_KEY[/cci] and [cci]INSERT_API_SECRET[/cci] with your Imagga API Key and Secret. You can signup for a free account to get these credentials. After creating an account, you’ll find these values on your dashboard:

from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap
import requests
from requests.auth import HTTPBasicAuth

app = Flask(__name__)

# API Credentials. Set your API Key and Secret here
API_KEY = 'acc_xxxxxxxxxxxxxxx'
API_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

@app.route('/', methods=['GET', 'POST'])
def index():
    image_url = None
    res = None

    if request.method == 'POST' and 'image_url' in request.form:
        image_url = request.form['image_url']
        response = requests.get(
           '%s?image_url=%s' % (ENDPOINT, image_url),

            res = response.json()
        except Exception as e:
            print('Exception in JSON decode:')
            print(response.content, response.status_code)

    return render_template('index.html', image_url=image_url, res=res)

if __name__ == '__main__':

Every call to the Imagga API must be authenticated. Currently, the only supported method for authentication is Basic. With Basic Auth, credentials are transmitted as user ID/password pairs, encoded using base64. In the above code, we achieve this with a call to [cci]HTTPBasicAuth()[/cci].

We then create a function that will be triggered by GET and POST requests to the [cci]/[/cci] route. If the request is a POST, we get the data submitted by form and send it to the Imagga API for classification.

The NSFW Categorizer is one of a few categorizers made available by the Imagga API. A Categorizer is used to recognize various objects and concepts. There are a couple predefined ones available (Personal Photos and NSFW Beta) but if none of them fit your needs we can build a custom one for you.

As mentioned previously, to send an image for classification, you send a GET request to the [cci]/categories/<categorizer_id>[/cci] endpoint. The [cci]categorizer_id[/cci] for the NSFW API is [cci]nsfw_beta[/cci]. You can send the following parameters with the request:

  • image_url: URL of an image to submit for categorization.
  • image_upload_id: You can also directly send image files for categorization by uploading the images to our [cci]/uploads[/cci] endpoint and then provide the received content identifiers via this parameter.
  • language: If you’d like to get a translation of the tags in other languages, you should use the language parameter. Its value should be the code of the language you’d like to receive tags in. You can apply this parameter multiple times to request tags translated in several languages. See all available languages here.

After processing the request, the API sends back a JSON object holding the image’s categorization data in case of a successful processing, and an error message incase there was a problem processing the image.

Below you can see the response of a successful categorization:

  "result": {
    "categories": [
        "confidence": 99.1496658325195,
        "name": {
          "en": "safe"
  "status": {
    "text": "",
    "type": "success"


Note that you might not always get JSON with the three categories displayed. If the confidence of a category is [cci]0[/cci], this category will not be included in the JSON object.

Below you can see the response of a failed categorization.

  "status": {
    "text": "Unexpected error while running the classification job.",
    "type": "error"

Back to our app, you can save your code and run it with:

[cc lang="bash"]
$ python

If you navigate to you should see a form with one input field. Paste in the URL of an image and submit it. The image will be processed and you will get back a page displaying the image and the JSON returned from the server. To keep it simple, we just display the raw JSON, but in a more sophisticated app, it would be parsed and used to make some decision.

Below, you can see the results of some images we tested the API with.

As you can see, the images have been categorized quite accurately. The first two have [cci]safe[/cci] confidence scores of [cci]99.22[/cci] and [cci]99.23[/cci] respectively while the last one has an [cci]underwear[/cci] score of [cci]96.21[/cci]. Of course, we can’t show an [cci]nsfw[/cci] image here on this blog, but you are free to test that on your own.

To know the exact confidence score to use for your app, you should first test the API with several images. When you look at the results of several images, you will be able to better judge which number to look out for in your code when filtering okay and not okay images. If you are still not sure about this, our suggestion is setting the confidence threshold at 15-20%. However, if you’d like to be more strict on the accuracy of the results, setting the confidence threshold at 30% might do the trick.

You should know that the technology is far from perfect and that the NSFW API is still in beta. From time to time, you might get an incorrect classification.

Note that the API has a limit of 5 seconds for downloading the image. If the limit is exceeded with the URL you send, the analysis will be unsuccessful. If you find that most of your requests are unsuccessful due to timeout error, we suggest uploading the images to our [cci]/uploads[/cci] endpoint first (which is free and not accounted towards your usage) and then use the content id returned to submit the images for processing via the [cci]content[/cci] parameter. We’ll see this in action in the next section.

Batch Processing Several Images

The last app we created allowed the user to process one image at a time. In this section, we are going to create a program that can batch process several images. This won’t be a web app, it will be a simple script that you can run from the command line.

Create a file named [cci][/cci] and add the code below to it. If you are still using the virtual environment created earlier, then the needed dependencies have already been installed, otherwise, install them with [cci]pip install requests[/cci].

import os
import json
import argparse
import requests
from requests.auth import HTTPBasicAuth

# API Credentials. Set your API Key and Secret here
API_KEY = 'acc_xxxxxxxxxxxxxxx'
API_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

FILE_TYPES = ['.png', '.jpg', '.jpeg', '.gif']

class ArgumentException(Exception):

if API_KEY == 'YOUR_API_KEY' or \
    raise ArgumentException('You haven\'t set your API credentials. '
                            'Edit the script and set them.')


def upload_image(image_path):
    if not os.path.isfile(image_path):
        raise ArgumentException('Invalid image path')

    # Open the desired file
    with open(image_path, 'rb') as image_file:
        # Upload the image with a POST
        # request to the /uploads endpoint
        uploads_response =
            '%s/uploads' % API_ENDPOINT,
            files={'image': image_file})

    # Example /uploads response:
    # {
    #   "result": {
    #     "upload_id": "i05e132196706b94b1d85efb5f3SaM1j"
    #   },
    #   "status": {
    #     "text": "",
    #     "type": "success"
    #   }
    # }
        upload_id = uploads_response.json()['result']['upload_id']
    except Exception as e:
        print('Error when reading upload response: ', e.text)

    return upload_id

def check_image(upload_id):
    # Using the uploads id, make a GET request to the /categorizations/nsfw
    # endpoint to check if the image is safe
    params = {
       'image_upload_id': upload_id
    response = requests.get(
        '%s/categories/nsfw_beta' % API_ENDPOINT,
    return response.json()

def main():
    parser = argparse.ArgumentParser(description='Tags images in a folder')
        'input', help='The input - a folder containing images')
        'output', help='The output - a folder to output the results')
    args = parser.parse_args()

    tag_input = args.input
    tag_output = args.output
    results = {}

    if not os.path.exists(tag_output):

    if not os.path.isdir(tag_input):
        raise ArgumentException(
            'The input directory does not exist: %s' % tag_input)

    images = []
    for img in os.scandir(tag_input):
        if not os.path.isfile(img.path):
            print('Bad file path', img.path)

        name, extension = os.path.splitext(

        if extension.lower() not in FILE_TYPES:
            print('Extension %s not in allowed' % extension, FILE_TYPES)


    images_count = len(images)

    for i, image_path in enumerate(images):
        print('[%s / %s] %s uploading' %
              (i + 1, images_count, image_path))

        upload_id = upload_image(image_path)
        nsfw_result = check_image(upload_id)
        results[image_path] = nsfw_result

        print('[%s / %s] %s checked' % (
            i + 1, images_count, image_path))

    for image_path, result in results.items():
        image_name = os.path.basename(image_path)
        result_path = os.path.join(tag_output, 'result_%s.json' % image_name)

        with open(result_path, 'w') as results_file:
            json.dump(result, results_file, indent=4)

    print('Done. Check your output folder for the results')

if __name__ == '__main__':

We use the [cci]argparse[/cci] module to parse arguments from the command line. The first argument passed in will be the path to a folder containing images to be processed while the second argument is a path to a folder where the results will be saved.

For each image in the input folder, the script uploads it with a POST request to the [cci]/uploads[/cci] endpoint. After getting a content id back, it makes another call to the [cci]/categories/<categorizer_id>[/cci] endpoint. It then writes the response of that request to a file in the output folder.

Note that all uploaded files sent to [cci]/uploads[/cci] remain available for 24 hours. After this period, they are automatically deleted. If you need the file, you have to upload it again. You can also manually delete an image by making a DELETE request to [cci]<upload_id>[/cci].

Add some images to a folder and test the script with:

[cc lang="bash"]$ python path/to/input/folder path/to/output/folder[/cc]

If you look at the output folder you selected, you should see a JSON file for each processed image.

Feel free to test out the Imagga NSFW Categorization API. If you have any suggestions on ways to improve it or just general comments on the API, you can post them in the Comment Section below or get in touch with us directly. We are always happy to get feedback on our products.

Why Using Image Recognition Software Can Save Your Cloud Platform a Ton of Resources

In recent years, we have seen significant growth in artificial intelligence technology and its use in different industries such as automotive, healthcare, e-commerce, gaming, e.t.c. Image recognition, one of the flagship applications of AI, has had wide adoption across industries. It is estimated that the worldwide market for image recognition will grow to $29.98 billion by 2020.

A major factor in the growing demand for image recognition technology has been the increased use of the internet and the move of small and medium enterprises (SMEs) to the cloud. With this move, the businesses have benefited from some of the advantages a cloud platform offers such as widespread reach, scalability, flexible billing options, rapid deployment and constant availability. With the move to the cloud, businesses have found it necessary to adopt technology that helps them better navigate the smarter and more connected platform; and image recognition is one of those technologies.

Image recognition (sometimes called computer vision) is the ability of software to analyze an image or video, identifying its content e.g. people, objects, places and text. It is widely used in different industries e.g. in self-driving cars, facial and optical character recognition software, disease diagnosis, e.t.c. For businesses that operate in the cloud, image recognition can offer numerous benefits as outlined below.

Automating Tasks with Image Recognition Software Saves Time

Unlike other resources that you can create or acquire more of, time is a finite resource that most likely, to stay competitive, you can't afford to waste.

Without a doubt, computers are faster than humans at some particular tasks, and so for those tasks, it makes sense to automate the job using software, leaving your employees free to work on other urgent tasks. Image recognition software can be used to automate such tasks as categorizing and tagging media content, content moderation and editing images (e.g. cropping or background removal).

Use of Image Recognition Software can Help Keep your Team Lean and Thus Save Costs

Use of image recognition software can reduce or eliminate required labour. Without image recognition, you would have to put people on the job to do such tasks as tagging and categorizing your digital assets, moderating user-generated content, individually editing images, e.t.c. In some cases, such a feat might be annoying and frustrating at best, but in other cases, it might be outright impossible to do. Take, for instance, a firm that might be offering Digital Asset Management services. The firm might have several clients, each having millions of digital content that needs to be processed. It would be very difficult, if not impossible to run such a service on manual labour alone. To keep its client's happy, the business will have to keep its asset processing time to a minimal, which means it would have to keep a lot of people on board to do the work. With time, as its client list increases or as the content each client maintains increases, the business's labour costs will also be skyrocketing. Running such a business on manual labour alone isn't sustainable. By automating some tasks with image recognition software, you can maintain a lean and cost-effective team.

Image Recognition can Reduce Human Error

To err is human, to forgive divine so the saying goes; but when you are running a business that depends on the accuracy of its operations, you might not be so lax about errors that might occur.

Human labour is susceptible to making errors. When tasked with entering a large amount of data, it is probable that some data will be recorded incorrectly. Human labour is also prone to tiring. When one has to process thousands of images or videos, they might not be as keen on processing a few thousands. With exhaustion and waning focus, errors might creep in here and there.

For some use cases, image recognition has been shown to give better results than humans. In the medical field, for instance, there is a visual recognition software that has a higher success rate in diagnosing a particular type of cancer. In the still infant field of self-driving cars, it has been said that driverless cars are safer than human drivers.

Image recognition can help eliminate or at least reduce the inaccuracies of human intervention. This will, in turn, save the business resources that would have been lost due to the errors, whether in the form of revenue, labour or time.

Image Recognition can Help you Innovate According to Market Trends

One advantage of running an online business is that a lot of your customers are also online. In this connected ecosystem, it is easier to monitor the market by observing what people share online. By analyzing visual content that is shared online, you might be able to recognize a trend that you can piggyback on when it comes to product release. With image recognition, you can also gain some insights into your competitors by detecting their online visual presence. You can observe how the market engages with the competitor's visual content and determine if their reaction to it is positive or not. This can, in turn, inform your product design decisions.

Instead of using tedious questionnaires and discovery processes to find out what users want, you can use data to determine this. You can determine what users gravitate towards online by observing what they share and how they react to different content. An example of this in use is Netflix which uses data to determine what shows to create. This can save you the effort and cost of creating something that won't be profitable once it hits the market.

Image Recognition can Improve your Marketing Efforts

Other than using image recognition to predict products that will be popular amongst your target market, you can also use it to determine how best to market the products to consumers. Using image recognition, you can mine your target market's visual content and monitor market trends in real time. In this way, you can gain insights on how visual posts spread online, what type of visuals get the most attention, the type of people engaging most with your content, the individual influencers driving most of the traffic and the best platform to post your content on. This can, in turn, help you launch marketing campaigns that are most likely to succeed. Your marketers don't have to waste their budget guessing at what will work, they can use data to decide on the way forward.

How something is presented can have a huge impact on the level of engagement people will have with it. Netflix discovered from conducting consumer research, that the artwork on their website was not only the biggest influencer to a member's decision to watch content, but it also constituted over 82% of their focus while browsing. This is why they go through so much effort to determine the best artwork to display on their website, a feat that would be impossible without image recognition and machine learning. If you are running an online business, you should pay attention to how you present your product or service. In a world where consumers are spoilt for choice when searching for a product or service, you should ensure that your website communicates the value of what you are trying to sell in the best way possible.

Image Recognition can Help Online MarketPlaces Fight Counterfeit Goods

According to the Organization for Economic Co-operation and Development (OECD), counterfeit products may cost the global economy up to $250 billion a year. Businesses running online platforms that allow sellers to sell goods always run the risk of having some sellers selling counterfeit products. This can damage the marketplace's reputation when consumers get products that are subpar to their genuine counterparts.

To counter this, marketplace websites have started turning to image recognition technology to help identify legit and counterfeit products. Using software, the platforms put uploaded product images through some checks to ensure their authenticity.

In General, Image Recognition Makes for Better Apps

Overall, incorporating image recognition improves the user experience of cloud applications and makes their operation effective and efficient. Using better apps is good for any business's bottom line as they reduce the overall overhead costs.

In the presence of numerous competition, most companies compete primarily on the basis of customer experience. Poor user experience can lead to customer churn, and in an interconnected world, it is very easy for disgruntled customers to spread the word about the terrible service they had at your hands; so it is always in your best interest to employ any technology you can to produce the best possible product for your target market.

Do you use image recognition in your product? If yes, let us know how you use it and how it has improved your business. If you would like to find out more about the Imagga Image Recognition API, please contact us and we'll get back to you promptly.