.net 调用 nsfwjs 进行视频鉴别

1. npm 安装 nsfwjs

npm install express --save
npm install multer --save
npm install jpeg-js --save
npm install @tensorflow/tfjs-node --save
npm install nsfwjs --save

注意:安装 @tensorflow/tfjs-node 需要用到 python, 建议添加到用户环境变量 Path 中

2. 运行 WebAPI 服务

nsfwjs 作者提供了一个简单的 server.js 来提供 WebAPI 服务,为方便复制到这里

const express = require('express')
const multer = require('multer')
const jpeg = require('jpeg-js')

const tf = require('@tensorflow/tfjs-node')
const nsfw = require('nsfwjs')

const app = express()
const upload = multer()

let _model

const convert = async (img) => {
  // Decoded image in UInt8 Byte array
  const image = await jpeg.decode(img, true)

  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')
}

app.post('/nsfw', upload.single('image'), async (req, res) => {
  if (!req.file) res.status(400).send('Missing image multipart/form-data')
  else {
    const image = await convert(req.file.buffer)
    const predictions = await _model.classify(image)
    image.dispose()
    res.json(predictions)
  }
})

const load_model = async () => {
  _model = await nsfw.load() //you can specify module here
}

// Keep the model in memory, make sure it's loaded only once
load_model().then(() => app.listen(8080))

尝试运行这个服务 ( 注意这个app仅支持jpeg格式的图片 )

node server.js

用 curl 测试

curl --request POST localhost:8080/nsfw --header 'Content-Type: multipart/form-data' --data-binary '[email protected]'

想简单些,可以写成这样

curl -F "[email protected]" "http://localhost:8080/nsfw"

Windows 下可以通过 Postman 来测试。

3. .net 封装调用

nsfwjs 的 WebAPI 服务能跑起来了,用 .net  封装调用就很简单了

3.1 首先通过 process 启动 node server.js,可以通过输出重定向隐藏控制台

3.2 分析视频,参考这篇文章通过调用 ffmpeg 或者使用 FFMpeg.AutoGen 编程实现截图

3.3 通过 HttpClient 或者RestSharp 等客户端组件提交需要鉴别的图片,返回结果

运行效果上来看还是不错的,200K 以内的图片一般都能在 200ms 内返回鉴别结果,唯一的不足是 nsfwjs 安装完有将近 700M,实在是太大了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章