Files
hexo-blog/source/_posts/你也可以成为鉴黄师,nsfwjs鉴黄库初探.md
T
2020-11-25 10:27:30 +08:00

105 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: 你也可以成为鉴黄师,nsfwjs鉴黄库初探
id: '361'
categories:
- 分享
tags:
- 鉴黄
- nsfwjs
- tensorflow
date: 2020-06-20 12:11:46
---
近日,我偶然在Github发现了一个鉴定不雅内容的 js 库 NSFW JS,出于好奇,于是就研究了一下,并且写了一个demo。下面就跟大家分享一下。
首先,NSFW JS 给一张图片鉴定的结果可能会得到如下 5 个分类结果。
1. 绘画(Drawing)——无害的艺术,或艺术绘画;
2. 变态(Hentai)——色情艺术,不适合大多数工作环境;
3. 中立(Neutral)——一般,无害的内容;
4. 色情(Porn)——不雅的内容和行为,通常涉及生殖器;
5. 性感(Sexy)——不合时宜的挑衅内容。
最终结果输出一个数组,每个分类都会输出一个概率,按概率从高到低排,所有分类的概率总和是1
```
[
{
"className": "Sexy",
"probability": 0.35769057273864746
},
{
"className": "Neutral",
"probability": 0.3514401912689209
},
{
"className": "Porn",
"probability": 0.2888406813144684
},
{
"className": "Hentai",
"probability": 0.0012577027082443237
},
{
"className": "Drawing",
"probability": 0.0007708172197453678
}
]
```
### 安装
NSFW JS是由TensorFlow.js作为对等依赖项提供支持。 所以我们要先安装TensorFlow.js。
```
yarn add @tensorflow/tfjs
yarn add nsfwjs
// or
npm i @tensorflow/tfjs
npm i nsfwjs
```
### 加载模型
然后我们需要加载模型。这个“模型”是用来评估图像的函数。可以在[nsfw\_model](https://github.com/gantman/nsfw_model)下载它们。这些文件是 4MB 大小的分片,便于在客户端进行缓存。因为我在vue项目中使用,所以把它们放在 /public/model/ 文件夹中。
![QQ截图20200620114436](https://image.dengtongyu.com/blog/2020/06/QQ截图20200620114436.png)
### 使用
```
// 导入模块
import * as nsfwjs from "nsfwjs";
// 图片dom节点
const img = document.getElementById('img')
// 载入模型
nsfwjs.load().then(model => {
// 鉴定图片
model.classify(img).then(predictions => {
console.log("Predictions: ", predictions);
});
});
```
在demo中测试的结果很惊喜,特意选取了一些干扰性的图片,也能正确识别
![微信图片_20200620120800](https://image.dengtongyu.com/blog/2020/06/微信图片_20200620120800.png)
![微信图片_20200620120806](https://image.dengtongyu.com/blog/2020/06/微信图片_20200620120806.png)
![微信图片_20200620120811](https://image.dengtongyu.com/blog/2020/06/微信图片_20200620120811.png) 最后,这里附上我写的demo,[传送门](https://demo.dengtongyu.com/nsfwtool/)