python NSFW Model 图片识别鉴黄 后面更新视频检测

article/2025/10/10 4:43:56

基于 NSFW Model 图片识别鉴黄 后面更新视频检测

识别效果

在这里插入图片描述

在这里插入图片描述
推荐SFW 0.98 色情 NSFW 0.015

在这里插入图片描述

在这里插入图片描述

推荐SFW 0.00 色情 NSFW 0.99 为色情图片

中文github代码下载 - 原文地址

环境条件

所有代码都应该与Python 3.6and兼容Tensorflow 1.x(用 1.12 测试)。模型实现可以在 中找到model.py

作者python环境

Python 3.6.13 :: Anaconda, Inc.

pip list

absl-py==1.1.0
astor==0.8.1
cached-property==1.5.2
certifi==2021.5.30
cycler==0.11.0
dataclasses==0.8
decorator==4.4.2
gast==0.5.3
grpcio==1.46.3
h5py==3.1.0
imageio==2.15.0
importlib-metadata==4.8.3
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.2
kiwisolver==1.3.1
Markdown==3.3.7
matplotlib==3.3.4
networkx==2.5.1
numpy==1.16.2
Pillow==8.4.0
protobuf==4.21.0
pyparsing==3.0.9
python-dateutil==2.8.2
PyWavelets==1.1.1
scikit-image==0.17.2
scipy==1.5.4
six==1.16.0
tensorboard==1.12.2
tensorflow==1.12.0
termcolor==1.1.0
tifffile==2020.9.3
typing_extensions==4.1.1
Werkzeug==2.0.3
wincertstore==0.2
zipp==3.6.0

安装依赖

方法 1.
pip install tensorflow== 1.12
pip installnumpy==1.16.2
pip install scikit-image==0.17.2方法 2.
pip install -r requirements.txt

使用方法

这里注意一下只支持.jpg类型图片

python classify_nsfw.py -m data/open_nsfw-weights.npy data/test.jpg	
SFW score推荐比例  , NSFW score 不推荐比例
Results for 'test.jpg'SFW score:	0.9355766177177429 NSFW score:	0.06442338228225708 

视频或者图片批量检测

python python http_nsfw.py	POST请求 http://127.0.0.1:2200/?token=aid.sd5@ns85
///图片格式///
{"temp_path":"C:/Users/lijie/Desktop/新-短视频/视频分割检测/66/","type":"image","valve":0.8,"src":["http://aliyuncs.com/image/2022-06/16/I1nfUPElFH6oz8ux.jpeg","http://aliyuncs.com/image/2022-06/16/OGCVPdDnV1wLdTn9.png"]
}
//视频格式//
{"temp_path":"C:/Users/lijie/Desktop/新-短视频/视频分割检测/66/","type":"video","valve":0.8,"src":"http://aliyuncs.com/image/2022-06/16/OGCVPd.mp4"
}返回信息 
{"isViolation": false, //是否涩情"tNsfw": "0.07921311259269714","tsfw": "0.9207869172096252"
}

##http_nsfw.py 代码

#!/usr/bin/env python
import sys
import argparse
import tensorflow as tffrom model import OpenNsfwModel, InputType
from image_utils import create_tensorflow_image_loader
from image_utils import create_yahoo_image_loader
from pathlib import Path
import subprocess
import os
import numpy as npfrom flask import request
from flask import jsonify
from flask import Flask
import json
from flask import jsonify
import urllib.requestclass main(object):def __init__(self):self.model =''self.sess =''def test(self):print(666)def model_load(self, weights=""):model = OpenNsfwModel()#创建加载NSF模型input_type = InputType['TENSOR'] #模型类型 [InputType.TENSOR.name.lower(), InputType.BASE64_JPEG.name.lower()])model.build(weights_path=weights, input_type=input_type)self.model = model;print('模型加载OK')self.sess =tf.Session() #创建对象self.sess.run(tf.global_variables_initializer())def distinguish(self,input_file):fn_load_image = Nonefn_load_image = create_yahoo_image_loader() #创建雅虎图片加载器image = fn_load_image(input_file)predictions = \self.sess.run(self.model.predictions,feed_dict={self.model.input: image}) #识别# print("Results for '{}'".format(args.input_file))# print("\tSFW score:\t{}\n\tNSFW score:\t{}".format(*predictions[0]))return {"tSFW":predictions[0][0],"tNSFW":predictions[0][1]}# if __name__ == "__main__":def save_image(video_path, image_dir, fps):#文件夹创建if not os.path.exists(image_dir):os.makedirs(image_dir)#-vf scale=320:240cmd_str = f'ffmpeg -i {video_path}  -f image2 -r {fps} {image_dir}/%d.jpeg -loglevel quiet 'subprocess.run(cmd_str, encoding="utf-8" , shell=True)app = Flask(__name__)@app.route('/', methods=['POST'])
def distinguish():token = request.values.get("token")if token != 'aid.sd5@ns85': #tokenreturn '403'params = json.loads(request.data)try:# 不能确定正确执行的代码params = json.loads(request.data) # 将json字符串转为dictexcept:return '405 参数错误'distinguish = '';is_violation = False;#视频识别if params['type'] == 'video':#视频进行抽针处理save_image(params['src'],params['temp_path'],1)#保存帧数1# os.listdir()方法获取文件夹名字,返回数组file_name_list = os.listdir(params['temp_path'])for index,img in enumerate(file_name_list):img_str = params['temp_path'] + imgdistinguish =  Model.distinguish(img_str)if distinguish['tNSFW'] > params['valve']:is_violation = TruebreakreturnData =  {"tsfw":f"{distinguish['tSFW']}","tNsfw":f"{distinguish['tNSFW']}","isViolation":is_violation}return jsonify(returnData);#图片识别if params['type'] == 'image':#文件夹创建if not os.path.exists(params['temp_path']):os.makedirs(params['temp_path'])n = 0#用来计数或命名for img in params['src']:n += 1img_url = params['temp_path']+"%s.jpeg" % nurllib.request.urlretrieve(img, img_url)#保存图片到本地distinguish = Model.distinguish(img_url)if distinguish['tNSFW'] > params['valve']:is_violation = TruebreakreturnData =  {"tsfw":f"{distinguish['tSFW']}","tNsfw":f"{distinguish['tNSFW']}","isViolation":is_violation}return jsonify(returnData);return "Ok"if __name__ == '__main__':Model =  main()Model.model_load("data/open_nsfw-weights.npy")app.run(host='0.0.0.0', port=2200, debug=False)

出现错误

caffe: TypeError: _open() got an unexpected keyword argument ‘as_grey‘“as_grey” 实际应当修改为 “as_gray”,原因是 scikit-image 的 0.17.2 版本修改了参数名称ValueError: Object arrays cannot be loaded when allow_pickle=False
自Numpy 1.16.3版本发行之后,函数 numpy.load() 和 numpy.lib.format.read_array() 采用allow_pickle关键字,现在默认为False以响
pip install numpy=1.16.2

Note: Currently only jpeg images are supported.

classify_nsfw.py accepts some optional parameters you may want to play around with:

usage: classify_nsfw.py [-h] -m MODEL_WEIGHTS [-l {yahoo,tensorflow}][-t {tensor,base64_jpeg}]input_jpeg_filepositional arguments:input_file            Path to the input image. Only jpeg images aresupported.optional arguments:-h, --help            show this help message and exit-m MODEL_WEIGHTS, --model_weights MODEL_WEIGHTSPath to trained model weights file-l {yahoo,tensorflow}, --image_loader {yahoo,tensorflow}image loading mechanism-i {tensor,base64_jpeg}, --input_type {tensor,base64_jpeg}input type

-l/–image-loader

The classification tool supports two different image loading mechanisms.

  • yahoo (default) replicates yahoo’s original image loading and preprocessing. Use this option if you want the same
    results as with the original implementation
  • tensorflow is an image loader which uses tensorflow exclusively (no dependencies on PIL, skimage, etc.). Tries
    to replicate the image loading mechanism used by the original caffe implementation, differs a bit though due to
    different jpeg and resizing implementations.
    See this issue for details.

Note: Classification results may vary depending on the selected image loader!

-i/–input_type

Determines if the model internally uses a float tensor (tensor - [None, 224, 224, 3] - default) or a base64 encoded
string tensor (base64_jpeg - [None, ]) as input. If base64_jpeg is used, then the tensorflow image loader will
be used, regardless of the -l/–image-loader argument.

Tools

The tools folder contains some utility scripts to test the model.

create_predict_request.py

Takes an input image and generates a json file suitable for prediction requests to a Open NSFW Model deployed
with Google Cloud ML Engine (gcloud ml-engine predict)
or tensorflow-serving.

export_savedmodel.py

Exports the model using the tensorflow serving export api (SavedModel). The export can be used to deploy the model
on Google Cloud ML Engine
, Tensorflow Serving or on mobile (haven’t tried that one yet).

export_tflite.py

Exports the model in TFLite format. Use this one if you want to run inference on
mobile or IoT devices. Please note that the base64_jpeg input type does not work with TFLite since the standard
runtime lacks a number of required tensorflow operations.

export_graph.py

Exports the tensorflow graph and checkpoint. Freezes and optimizes the graph per default for improved inference and
deployment usage (e.g. Android, iOS, etc.). Import the graph with tf.import_graph_def.


http://chatgpt.dhexx.cn/article/CqL7BCoU.shtml

相关文章

Python 批量鉴别审核黄图

作者:美图博客 https://www.meitubk.com/zatan/229.html 前言 最近写了一款微信小程序需要用到图片审核,人工审核是不可能的人工审核的太费精力了,所以我就写了一个多线程批量识别脚本来处理,主要是调用百度 AI 的接口&#xff0…

Python快速实现黄图检测——车速检测器

文章目录 简介安装图像视频预加载车速检测器视频车速检测器无声音TODO: 有声音 参考文献 简介 使用雅虎开源的 TensorFlow 2 Open-NSFW 模型 NSFW:not safe for work,工作场所不宜 1.jpg 2.jpg 自己去下 安装 Python 3.7 及以上,本人尝…

做了个色情图片识别系统

项目介绍 本项目将使用python3去识别图片是否为色情图片,会使用到PIL这个图像处理库,并且编写算法来划分图像的皮肤区域 介绍一下PIL: PIL(Python Image Library)是一种免费的图像处理工具包,这个软件包提供…

图像鉴黄的数据集及相关算法汇总

前方高能预警,非战斗人士请火速撤离…… 数据集1:https://github.com/EBazarov/nsfw_data_source_urls/tree/master/raw_data 在 raw_data 文件夹里,可以找到不同的 .txt 格式的文档,每个文档都含有一组 URL,以下是关…

微信小程序—智能鉴黄、敏感识别

小程序提供内容安全接口 security.imgSecCheck:图片检测 security.msgSecCheck:文本检测 调用效果如下: 敏感信息,不好暴漏,可自行体验 体验路径:扫码>>AI智能系列>>安全检测—敏感词语、黄…

android图片颜色识别器,颜色识别器APP

颜色识别器APP是一款手机上的颜色辨别应用,用户只需用摄像头拍出要识别的颜色,应用就能将颜色信息识别出并转换为相关的颜色信息,如颜色名称,颜色的HEX码、RGB码等,还有实时识别,测色仪,色差计等…

二维码/条码识别、身份证识别、银行卡识别、车牌识别、图片文字识别、黄图识别、驾驶证(驾照)识别

Scanner 项目地址:shouzhong/Scanner 简介: 二维码/条码识别、身份证识别、银行卡识别、车牌识别、图片文字识别、黄图识别、驾驶证(驾照)识别 更多:作者 提 Bug 标签: >>> reset-###- …

身份证、银行卡、车牌、图片文字识别、黄图识别、驾驶证识别库实现功能

预览图效果: 原文来自:http://code.662p.com/view/19388.html ,需要自己去下载就可以了。 使用 依赖 implementation com.shouzhong:Scanner:1.1.3以下选择自己需要的 // zxing implementation com.google.zxing:core:3.3.3 // zbar imp…

黄图识别-open nsfw

大楷简介: open nsfw是一款开源的黄图识别的模型。对的,只是模型。并且有有python的代码作为预测图片是否黄图。 https://github.com/yahoo/open_nsfw 这里网址。 open nsfw是雅虎开源项目caffeonspark,使用深度学习训练得到caffe模型。ns…

计算机无法对NAS硬盘操作,使用计算机为Synology NAS安装DSM操作系统

Synology NAS由硬件,系统和应用程序套件组成. Synology最著名的是DSM操作系统. DSM操作系统是Synology开发的用于存储的智能操作系统. 它不仅功能强大,而且在DSM中可用. 在操作系统上安装各种应用程序包,以满足您的需求. 可以通过手机或计算机…

Delta-Sigma调制(DSM)技术

前言 数字信号处理和通信系统的性能很大程度上受到了模拟信号到数字信号转换接口——ADC的精度和分辨率的限制。而传统的线性脉冲编码调制(PCM)ADC受到了制造工艺的限制,无法达到很高的分辨率。但基于Delta-Sigma调制技术的ADC可以在现有工艺…

黑群晖 DSM 6.2 3617 成功安装教程

黑群晖简介: 黑群晖指的是不是购买正规的群晖的nas 而是在普通电脑上装群晖nas的系统。从硬件来说,群晖本来就是软阵列,和普通PC的软阵列比,没多大分别;黑群晖给你一个打包好的nas,功能全面的轻量化系统&am…

趋势DSM安装

1、基础环境准备 ①准备一台虚拟机,操作系统:CentOS 7.9(带图形) 4vCPU,16GB内存,200GB存储。 ②虚拟机需要安装数据库(支持MSSQL/Oracle/PostgreSQL)和Java环境。 ③本次环境以PostGreSQL位例,进行安装。 2、Pos…

dsm操作系统服务器,DSM 5.1操作系统提供以下新功能

DSM 5.1操作系统提供以下新功能 DSM 5.1操作系统提供以下新功能: 一、打造你的多媒体娱乐中心 DSM 5.1公开分享功能的覆盖范围遍及多媒体内容、档案与数字笔记,NAS上的档案仅通过一键产生网址的方式就能够实时和他人分享。此外,Video Station…

用户DSN、系统DSN、文件DSN的区别

“ODBC数据源管理器”提供了三种DSN,分别为用户DSN、系统DSN和文件DSN。 文件DSN:是建立一个 DSN 的文件, 信息存在文件里。只能由配置该DSN的用户使用或只能在当前的计算机上使用。 系统DSN:是建立一个系统级的DSN&#xff0c…

黑群晖DSM安装教程及详细配置

本文同步发布在个人博客:YouForever - 专注于互联网分享 欢迎访问 为什么要安装黑群晖 先说说什么是NAS服务器,简单来说就是一个网络存储器,你可以存放音乐、视频、文件等,方便地从各个设备进行访问。而群晖的Synology DSM&#…

nDSM、CHM、DTM、DEM、DSM,剪不断、却理得清

nDSM、CHM、DTM、DEM、DSM,剪不断、却理得清 目前,围绕地形产品这一主题,在测绘、地理信息、林业与生态、地质、土木工程等领域普遍存在DTM、DEM、DSM、nDSM、CHM、DCM等英文缩写词。这些缩写的英文专业名词往往被混淆,即使是部分…

如何通过ABB代理程序备份群晖DSM系统

Active Backup for Business代理程序仅支持7.1系统,6.2系统及虚拟DSM系统不支持。 适用机型 备份还原限制 目的地 NAS 必须为与来源 NAS 相同机种或为后续机种,方可进行系统还原 (例:DS218 可还原至另一台 DS218 或 DS220)。目的地 NAS 所安…

把“友商”装进芯里威联通运行黑群晖最新DSM系统

原文网址:http://www.nasyun.com/forum.php?modviewthread&tid30334&fromuid106494 (出处: NAS云论坛) 接触过威联通NAS的玩家可能知道,威联通X86架构的机型NAS,支持在NAS系统中运行虚拟机软件,从而在里面虚拟化运行各种…

DBMS(数据库管理系统)的功能

DBMS是数据库系统中重要的组成部分,比如用户在数据库中的增删改查操作以及各种控制都是由DBMS进行的。简单来讲,DBMS可以帮助用户、满足用户的需要,从抽象逻辑数据转换成计算机的物理数据,给用户带来很大的便利。 DBMS的主要功能 …