在生活中不可避免会出现色情视频,因此视频的鉴定就成为了我们需要解决的问题,本博客在NSFW项目(见下面参考文献)的基础上面改进了封装,用来检测视频是否是色情视频。首先,这个项目是基于Caffe 的,使用的网络结构是ResNet网络(可以查看参考文献中的论文)。

为了完成对视频的检测,博主使用了FFMPEG,用来从视频中提取帧数,每20秒提取一次图像,当然为了检测更加精确,可以在后面修改间隔时间。

检测分为三个等级,score < 0.2 的表示很安全,socre > 0.8 的表示有很大的可能性是色情的。

最后程序输出:

总共提取检测视频中的图像帧数

socre < 0.2   很安全 safe的数量,占的比重

score >= 0.2 && score <= 0.8  medimum , 介于危险和安全之间的数量,比重

score > 0.8 dangerous, 有很大可能性是色情占的比重

最后我们可以根据dangerous 占的比重可以确定视频是否是色情视频。

废话不多说,下面进入实战环节。

首先就是安装ffmpeg,由于我使用的是Ubuntu 14的系统,安装这个的时候着实费了一点功夫,所幸终于找到了一个好用的源安装成功。

sudo add-apt-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get install ffmpeg gstreamer0.10-ffmpeg

接下来就是安装caffe了,如果你没有安装过,也没有关系,使用docker就可以了。

安装docker容器:

这里就不多说了。

安装caffe 容器 CPU版:

docker build -t caffe:cpu https://raw.githubusercontent.com/BVLC/caffe/master/docker/cpu/Dockerfile

查看caffe版本:

docker run caffe:cpu caffe --version

下载open_nsfw:

 git clone https://github.com/yahoo/open_nsfw

进入工作目录:

cd open_nsfw

在这里需要说明的是启动docker的时候需要我们把工作目录挂载到docker中,例如:

docker run -ti --volume={}:/workspace caffe:cpu bash".format("/home/duan/open_nsfw/

这里先不用着急运行这一步。

接下来就是视频帧提取代码了,每20秒提取一帧,存放于open_nsfw/picture文件夹下面:

# -*- encoding:utf-8 -*-
__date__ = "17/1/16"
__author__  = "duan"import os
import shutil
from argparse import ArgumentParserdef video_to_frames(video_path, frames_path, step_size = 20):if not os.path.exists(frames_path):os.makedirs(frames_path)else:shutil.rmtree(frames_path)os.makedirs(frames_path)output_file = frames_path + "/out%05d.jpg"print("ffmpeg -i {} -f image2 {}".format(video_path, output_file))#extract an image every 20 seconds# you can also set every 10 seconds, just set fps = fps = 1/10os.system("ffmpeg -i {} -f image2 -vf fps=fps=1/{} {}".format(video_path, step_size, output_file))if __name__ == '__main__':parser = ArgumentParser()parser.add_argument('--content',dest='content', help='content image',metavar='CONTENT', required=True)parser.add_argument('--step', type=int, default = 20,dest='step', help='the video step you want use',metavar='STEP')options = parser.parse_args()video_name = options.content # the video name you want to detectstep_size = options.step # the video step you want to use#video_name = "1994.mp4" # the video name you want to detectvideo_path = "./"  # the video path, i put the video at current folderframes_path = "picture"video_to_frames(video_path + video_name, frames_path, step_size)# start the docker and set the workspace as "/home/duan/open_nsfw"# set as your own path#launch the dockeros.system("docker run -ti --volume={}:/workspace caffe:cpu bash -c \"python video_detect.py\"".format("/home/duan/open_nsfw/"))

接下来新建一个文件,,用来检测提取出来的图像,在上面的程序启动docker之后,就可以运行

python video_detect.py
# -*- encoding:utf-8 -*-
__date__ = "17/1/16"
__author__  = "duan"import os
import shutilframes_path = "picture"files= os.listdir(frames_path) results = []import video_nsfwsafe = 0.0
median = 0.0
dangerous = 0.0for file in files:   if not os.path.isdir(file):res = video_nsfw.detact("nsfw_model/deploy.prototxt", "nsfw_model/resnet_50_1by2_nsfw.caffemodel", frames_path + "/" + file)if res < 0.2:safe += 1elif res < 0.8:median += 1else:dangerous += 1results.append(res)print(len(results))
print("safe count: {}, proportion: {}%".format(safe, round(safe / len(results) * 100, 3)))
print("median count: {}, proportion: {}%".format(median, round(median / len(results) * 100, 3)))
print("dangerous count: {}, proportion: {}%".format(dangerous, round(dangerous / len(results) * 100, 3)))

核心的检测代码, 文件为 video_nsfw.py:

# -*- encoding:utf-8 -*-
__date__ = "17/1/16"
__author__  = "duan"import os
import shutilimport numpy as np
import os
import sys
import argparse
import glob
import time
from PIL import Image
from StringIO import StringIO
import caffedef resize_image(data, sz=(256, 256)):"""Resize image. Please use this resize logic for best results instead of the caffe, since it was used to generate training dataset """img_data = str(data)im = Image.open(StringIO(img_data))if im.mode != "RGB":im = im.convert('RGB')imr = im.resize(sz, resample=Image.BILINEAR)fh_im = StringIO()imr.save(fh_im, format='JPEG')fh_im.seek(0)return bytearray(fh_im.read())def caffe_preprocess_and_compute(pimg, caffe_transformer=None, caffe_net=None,output_layers=None):"""Run a Caffe network on an input image after preprocessing it to prepareit for Caffe."""if caffe_net is not None:# Grab the default output names if none were requested specifically.if output_layers is None:output_layers = caffe_net.outputsimg_data_rs = resize_image(pimg, sz=(256, 256))image = caffe.io.load_image(StringIO(img_data_rs))H, W, _ = image.shape_, _, h, w = caffe_net.blobs['data'].data.shapeh_off = max((H - h) / 2, 0)w_off = max((W - w) / 2, 0)crop = image[h_off:h_off + h, w_off:w_off + w, :]transformed_image = caffe_transformer.preprocess('data', crop)transformed_image.shape = (1,) + transformed_image.shapeinput_name = caffe_net.inputs[0]all_outputs = caffe_net.forward_all(blobs=output_layers,**{input_name: transformed_image})outputs = all_outputs[output_layers[0]][0].astype(float)return outputselse:return []def detact(model_def, pretrained_model, input_file):pycaffe_dir = os.path.dirname(__file__)#args = parser.parse_args()image_data = open(input_file).read()# Pre-load caffe model.nsfw_net = caffe.Net(model_def,  # pylint: disable=invalid-namepretrained_model, caffe.TEST)# Load transformer# Note that the parameters are hard-coded for best resultscaffe_transformer = caffe.io.Transformer({'data': nsfw_net.blobs['data'].data.shape})caffe_transformer.set_transpose('data', (2, 0, 1))  # move image channels to outermostcaffe_transformer.set_mean('data', np.array([104, 117, 123]))  # subtract the dataset-mean value in each channelcaffe_transformer.set_raw_scale('data', 255)  # rescale from [0, 1] to [0, 255]caffe_transformer.set_channel_swap('data', (2, 1, 0))  # swap channels from RGB to BGR# Classify.scores = caffe_preprocess_and_compute(image_data, caffe_transformer=caffe_transformer, caffe_net=nsfw_net, output_layers=['prob'])# Scores is the array containing SFW / NSFW image probabilities# scores[1] indicates the NSFW probabilityprint("NSFW score:  " , scores[1])return scores[1]

最后运行的时候运行:

python launch_video_detact.py --content 1995.mp4 --step 20

step选项是隔几秒提取的帧数,可以省略,默认20。当然最后的效果也与这个的选取有关。

本文最后检测了一下《肖申克的救赎》,实验结果如下:

总共以每隔20秒的时间提取视频,共检测429帧,因此可以以93.7%的概率确定《肖申克的救赎》非常安全。

当然你可以自己检测色情视频,嘿嘿。

转载请注明:转载自 http://blog.csdn.net/willduan1/article/details/54577351

------------------------EOF------------------------------

参考文献:

https://github.com/yahoo/open_nsfw/blob/master/README.md

He, Kaiming, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. “Deep residual learning for image recognition” arXiv preprint arXiv:1512.03385 (2015).

Simonyan, Karen, and Andrew Zisserman. “Very deep convolutional networks for large-scale image recognition.”; arXiv preprint arXiv:1409.1556(2014).

Iandola, Forrest N., Matthew W. Moskewicz, Khalid Ashraf, Song Han, William J. Dally, and Kurt Keutzer. “SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and 1MB model size.”; arXiv preprint arXiv:1602.07360 (2016).

He, Kaiming, and Jian Sun. “Convolutional neural networks at constrained time cost.” In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 5353-5360. 2015.

Szegedy, Christian, Wei Liu, Yangqing Jia, Pierre Sermanet,Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, and Andrew Rabinovich. “Going deeper with convolutions” In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 1-9. 2015.

Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. “Imagenet classification with deep convolutional neural networks” In Advances in neural information processing systems, pp. 1097-1105. 2012.

基于深度学习的色情视频鉴定相关推荐

  1. 山东大学项目实训小组一——基于深度学习的AI视频剪辑器“易剪”

    技术要点:图像处理 计算机视觉 深度学习 多媒体前端 一.项目研究背景: 随着短视频热潮的兴起,越来越多的人投入精力到了视频剪辑视频制作之中.然而利用现有的视频剪辑工具,剪辑一段视频是非常麻烦的,尤其 ...

  2. 目标检测,FFmpeg中第一个基于深度学习模型的视频分析功能

    2021年4月,终于把目标检测(object detection)加到FFmpeg upstream了,有maintainer身份加持,还是交互了将近100封邮件,花了两个多月才完成upstream, ...

  3. 基于深度学习算法实现视频人脸自动打码

    前言 1.在当下的环境上,短视频已是生活的常态,但这是很容易就侵犯别人肖像权,好多视频都会在后期给不相关的人打上码,这里是基于yolov5的人脸检测实现人脸自动打码功能. 2.开发环境是win10,显 ...

  4. DL之Yolov3:基于深度学习Yolov3算法实现视频目标检测之对《我要打篮球》视频段进行实时目标检测

    DL之Yolov3:基于深度学习Yolov3算法实现视频目标检测之对<我要打篮球>视频段进行实时目标检测 目录 输出结果 设计思路 核心代码 相关文章 成功解决AttributeError ...

  5. DL之Yolov3:基于深度学习Yolov3算法实现视频目标检测之对《俄罗斯总统普京对沙特王储摊的“友好摊手”瞬间—东道主俄罗斯5-0完胜沙特》视频段实时检测

    DL之Yolov3:基于深度学习Yolov3算法实现视频目标检测之对<俄罗斯总统普京对沙特王储摊的"友好摊手"瞬间-东道主俄罗斯5-0完胜沙特>视频段实时检测 导读   ...

  6. CV:基于深度学习实现目标检测之GUI界面产品设计并实现图片识别、视频识别、摄像头识别(准确度非常高)

    CV:基于深度学习实现目标检测之GUI界面产品设计并实现图片识别.视频识别.摄像头识别(准确度非常高) 目录 GUI编程设计界面 产品演示 GUI编程设计界面 产品演示 视频演示:https://bl ...

  7. ECCV 2018论文解读 | DeepVS:基于深度学习的视频显著性方法

    作者丨蒋铼 学校丨北京航空航天大学在校博士,大不列颠哥伦比亚大学联合培养博士 研究方向丨计算机视觉 本文概述了来自北京航空航天大学徐迈老师组 ECCV 2018 的工作 DeepVS: A Deep ...

  8. 基于深度学习的视频预测研究综述

    原址:http://html.rhhz.net/tis/html/201707032.htm (收集材料ing,为论文做准备)[综述性文章,,,可以做背景资料] 莫凌飞, 蒋红亮, 李煊鹏 摘要:近年 ...

  9. 中国人工智能学会通讯——基于视频的行为识别技术 1.5 基于深度学习的视频识别方法...

    1.5 基于深度学习的视频识别方法 下面介绍面向视频分类的深度学习方 法.深度卷积神经网络在图像分类取得 成功后,研究人员就希望把它推广到视 频分类中.但这不是一件很容易的事, 一个原因是缺乏足够的训 ...

  10. [翻译]2020年综述:基于深度学习的视频超分辨率

    综述:基于深度学习的视频超分辨率 Video Super Resolution Based on Deep Learning: A Comprehensive Survey 论文链接:https:// ...

最新文章

  1. 2022,人工智能开启未来新密码
  2. 敏捷团队如何通过Leangoo领歌做迭代管理、迭代规划及任务协同
  3. php linux权限,Linux权限位
  4. IPv6的脚步声近了!
  5. 六十.完全分布式 、 节点管理 、 NFS网关
  6. R语言实战应用精讲50篇(十一)-单因素方差分析 | 事后两两多重比较 | 趋势方差分析
  7. Python之包管理工具
  8. 下拉式菜单在GridView编辑时联动选择
  9. Node.js 模块化开发
  10. 设计人的33个好习惯
  11. 大数据之-Hadoop3.x_MapReduce_MapJoin案例完成---大数据之hadoop3.x工作笔记0134
  12. java判断字符串是json_java中如何判断字符串是否为json格式
  13. 【报告分享】中国年轻用户电商消费洞察报告:寻找电商换道增长机遇.pdf(附下载链接)...
  14. 自动填写html文本框的值,网页自动填表——文本输入框及多行文本输入框
  15. 零基础安装Ubuntu kylin 16.04 LTS 后应该做什么[本人安装目的:学习Python数据分析]
  16. iOS NSString追加字符串的方法
  17. Linux文档内容查阅命令总结 - cat,tac,nl,more,less,head,tail,od
  18. PHPstorm链接服务器自动保存
  19. java switch程序_Java 基础分支语句之程序流程控制switch-case
  20. python pip国内源_Python pip配置国内源 (转载)

热门文章

  1. 怎样避免每次运行都启用宏的麻烦
  2. 如何利用DTM预览功能来验证新版本的配置是否正确?
  3. CDOJ 796 DAGE(Big Brother)
  4. VMware tools 安装失败
  5. 水星路由器登录界面找不到服务器,新版水星(Mercurey)路由器后台登陆界面打不开怎么办?...
  6. 【深度学习笔记】AUC(Area under Curve Roc曲线下面积)
  7. 量子计算机的算力是多少,我国量子计算机实现算力全球领先
  8. wifi密码破解软件,谨慎使用!
  9. 龙卷风路径_龙卷风接连来袭 我国哪些地方最易发生强龙卷?
  10. 动态电路中的动态元件——电容和电感