nsfwjs是一个免费开源的图片鉴别插件,本地打包尺寸过大,不符合预期,所以大多数人选择在服务端部署。
下面是node版本部署流程笔记:(仅供参考)
node服务这里采用的是express框架:Express - Node.js web application framework
npm install express --savensfwjs代码库地址:GitHub - infinitered/nsfwjs: NSFW detection on the client-side via TensorFlow.js
https://github.com/infinitered/nsfwjs建议:用管理员权限启动cmd
第一步:环境准备
npm install --global windows-build-tools或
npm install -g --production windows-build-tools以上环境准备我个人尝试了多次才执行成功,若遇到失败可重试,不要着急
第二步:依赖安装
npm install nsfwjs注意:下面这个安装需要翻墙,里面部分引用资源在外网。
大家遇到最多的问题就是这个包安装或者执行失败,可尝试用cnpm
npm install @tensorflow/tfjs-node@tensorflow/tfjs-node和@tensorflow/tfjs两个包是互斥的,删除node_modules后重试
你可能会用到的包
npm i @tensorflow/tfjs-node-gpu相关文档:tfjs/README.md at master · tensorflow/tfjs · GitHub
快速删除庞大的node_modules指令:
rd /s /q node_modules扩展,文档中推荐的另一个模式(sharp):
Output options - sharp - High performance Node.js image processing (pixelplumbing.com)
const getMetadata = async (img) => { const image = await sharp(img).jpeg().metadata(); const { data, info } = await sharp(img) .toFormat('jpeg') .raw() .toBuffer({ resolveWithObject: 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] = 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 { try { const image = await getMetadata(req.file.buffer) // const image = await convert(req.file.buffer) const predictions = await _model.classify(image) image.dispose() res.json(predictions) } catch (error) { res.status(400).send(error) } } })也可以将模型下载到项目中:
模型发布仓库:GitHub - GantMan/nsfw_model: Keras model of NSFW detector