前言
今天瞎点看到一个项目 https://github.com/devzwy/open_nsfw_android 安卓调用tflite模型实现nsfw(not save for work )识别。
这个项目是移植的雅虎的一个项目:https://github.com/yahoo/open_nsfw
然后想到之前的机器人插件是通过调用华为云API(有调用上限 以及收费 但是包含了暴恐 敏感人物等识别)实现的,如果把这个模型下下来简单封装成一个WebAPI 给机器人调用就可以完成离线调用了。
识别速度大概40MS左右(有GPU的情况下),准确率还是挺高的。
第一次识别会久一点,后续识别就很快了,懂的都懂。
(由于Google Adsense(我的金主爸爸)不能放出裸露 性诱惑 性暗示等图片 所以 我打码了@(欢呼))
相关代码
模型下载: https://imacro.lanzoui.com/iw3QDiv0zji
模型方法代码:
import io
import sys
import argparse
import tensorflow as tf
from PIL import Image
import numpy as np
import skimage
import skimage.io
import os
# 预加载模型
VGG_MEAN = [104, 117, 123]
model_path = "nsfw.tflite"
interpreter = tf.lite.Interpreter(model_path=model_path)
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
# print(str(input_details))
output_details = interpreter.get_output_details()
# print(str(output_details))
def prepare_image(image,img_width, img_height): #预处理图片
H, W, _ = image.shape
h, w = (img_width, img_height)
h_off = max((H - h) // 2, 0)
w_off = max((W - w) // 2, 0)
image = image[h_off:h_off + h, w_off:w_off + w, :]
image = image[:, :, :: -1]
image = image.astype(np.float32, copy=False)
image = image * 255.0
image = image-np.array(VGG_MEAN, dtype=np.float32)
image = np.expand_dims(image, axis=0)
return image
def getNSFW(im): #传入Image类型参数
global interpreter,input_details,output_details
if im.mode != "RGB":
im = im.convert('RGB')
imr = im.resize((256, 256), resample=Image.BILINEAR)
fh_im = io.BytesIO()
imr.save(fh_im, format='JPEG')
fh_im.seek(0)
image = (skimage.img_as_float(skimage.io.imread(fh_im, as_gray=False))
.astype(np.float32))
# 填装数据
final = prepare_image(image, 224, 224)
interpreter.set_tensor(input_details[0]['index'], final)
# 调用模型
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
# 出来的结果去掉没用的维度
result = np.squeeze(output_data)
return result #返回sfw以及nsfw
简单的Flask框架实现WebAPI
请求地址: http://127.0.0.1:8777/nsfw
请求类型: POST
请求参数:
- 参数名 img
- 参数内容 base64 过的 图片数据
import io
from urllib import parse
from PIL import Image
from flask import Flask, request
import base64
from time import *
import tflite
import json
app = Flask(__name__)
@app.route('/nsfw',methods=["POST"])
def get_tasks():
if request.method=='POST':
begin_time = time()
base64_str = request.form['img']
img_b64decode = base64.b64decode(base64_str)
image = io.BytesIO(img_b64decode)
img = Image.open(image)
result = tflite.getNSFW(img)
take_time = round((time() - begin_time)*1000)
print('SFW:{} NSFW:{} TOOK:{}'.format(result[0], result[1], take_time))
return json.dumps({'sfw': str(result[0]), 'nsfw': str(result[1]), 'took':take_time})
app.run(debug=False, port=8777)
现在就可以进行WebAPI请求 然后返回一段包含sfw和nsfw数据的json了,判断nsfw超过一定的数值即为色情图片。
公用的API接口就不放出来了,上次超星查题的接口被大批量爆破,直接就把服务器挤爆了,直接找我要题库数据库我可能直接给你了,这么搞(还是大批量的用代理IP进行请求)。。现在接口我已经停掉了,估计被他爬了十几万题了,也有可能仅仅只是想进行CC攻击。反正他死了一万个妈!@[鄙视]
所以,大佬,那个自动答题脚本 还能用吗?
@Past Tense 你可以在群里问 我私发一个给你,或者可以去https://greasyfork.org/找一个
@Past Tense 恢复了