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,實在是太大了。