美文网首页web前端
node实现图片鉴黄

node实现图片鉴黄

作者: 姜治宇 | 来源:发表于2022-03-08 17:41 被阅读0次

nsfwjs是一款强大的开源鉴黄的框架,不过搭建过程比较繁琐,今天花了一些时间试错,最后终于成功跑起来。将过程整理了下来,避免后来者踩坑。
我们结合express搭建鉴黄服务。

1、搭建express

npm install -g express
npm install express-generator -g
express  identifyimg

2、安装windows-build-tools

在windows下,nsfwjs安装需要一些C++库和python版本的支持。
我们需要用管理员身份打开cmd,然后再用npm安装。


1png

然后在cmd下安装windows-build-tools。

C:\Windows\System32> npm install --global windows-build-tools

运行画面:


2.png

3、安装相关依赖包

npm install nsfwjs -S
npm install @tensorflow/tfjs-node -S
npm install multiparty -S
npm install image-js -S

安装@tensorflow/tfjs-node插件的依赖较多,可能需要翻墙。

4、代码部分

在任意路由下实现即可。

var express = require('express');
var router = express.Router();

var multiparty = require('multiparty');
var imgJS = require("image-js");
const nsfw = require('nsfwjs');
const tf = require('@tensorflow/tfjs-node');
const safeContent = ['Drawing', 'Neutral']; // 设置图片内容安全的类型
//转换图片格式
const convert = async file => {
  const image = await imgJS.Image.load(file.path);
  const numChannels = 3;
  const numPixels = image.width * image.height;
  const values = new Int32Array(numPixels * numChannels);

  for (let i = 0; i < numPixels; i++) {
    for (let c = 0; c < numChannels; ++c) {
      values[i * numChannels + c] = image.data[i * 4 + c];
    }
  }

  return tf.tensor3d(values, [image.height, image.width, numChannels], 'int32');
};


const isSafeContent = predictions => {
  let safeProbability = 0;
  for (let index = 0; index < predictions.length; index++) {
    const item = predictions[index];
    const className = item.className;
    const probability = item.probability;
    if (safeContent.includes(className)) {
      safeProbability += probability;
    }
  }
  return safeProbability > 0.5;
};
router.post('/', function (req, res, next) {

  var form = new multiparty.Form();
  form.parse(req, async (err, fields, files) => {
    let img = await convert(files.file[0]);

    let model = await nsfw.load('file://./public/mobilenet/web_model/', {
      type: 'graph'
    });
    let predictions = await model.classify(img);
    const isSafe = isSafeContent(predictions);
    console.log('是否安全:', isSafe);

  });

});

module.exports = router;

5、model包

如果nsfw.load()不传参数的话,默认加载一个官方的模型地址,模型的大小大概几十上百兆,加载的过程会比较慢,如果你的服务部署到非互联网环境,那就直接启动不了了,所以把模型放到本地服务才是比较好的解决方案。
先去nsfw_model下载模型到本地,选择第一个nsfw_mobilenet_v2_140_224.zip
即可,然后解压zip包,web_model文件夹里面就是我们需要的模型了,我们可以将其放在public目录下。
下载不了的同学,可以去百度网盘下载。
链接:https://pan.baidu.com/s/1E00MAsQq5kLoZOG1PMJdVg
提取码:g0mh

参考文章:

https://www.jianshu.com/p/b70a0f4238ee
http://dengtongyu.com/2021/05/10/node+nsfwjs%E6%90%AD%E5%BB%BA%E5%9B%BE%E7%89%87%E9%89%B4%E9%BB%84%E6%9C%8D%E5%8A%A1/

相关文章

网友评论

    本文标题:node实现图片鉴黄

    本文链接:https://www.haomeiwen.com/subject/eciarrtx.html