The problem detecting NSFW has been around for over two decades.
This study from 2005 about finding naked people, demonstrates a strategy for finding such images based on the color and texture properties to fetch an effective mask for skin regions attempting to group a human figure using geometric constraints on the human structure. This method demonstrated
60% precision and 52% recall on a test set of 138 uncontrolled images of naked people.
Here are a few figures from the study explaining the algorithm:
The following post contains visualizations of nudity for scientific purposes (hover to display):
A more recent approach is using convolutional networks. This study from 2014PDF demonstrated impressive classification performance based on the ImageNet dataset. It's not clear 'how and why they perform so well', however they can be used for classification of images with a very low error rate.
For further details, check: What convolutional neural networks look at when they see nudity.
You will find the code example and the heatmap for how convnets see NSFW in the above link.