日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python:使用opennsfw2对图片/视频进行鉴黄识别

發布時間:2024/3/24 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python:使用opennsfw2对图片/视频进行鉴黄识别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 簡介
    • 實踐
      • 1.環境準備,
      • 2.代碼實踐
    • 高級用法
      • 1. 加載的方式
      • 2.車速檢測
      • 3. 視頻車速檢測(無聲)
      • 4. 視頻車速檢測(有聲)
    • 小結


簡介

使用雅虎開源的 TensorFlow 2 Open-NSFW 模型,NSFW:not safe for work,工作場所不宜

實踐

1.環境準備,

Python 3.7 及以上,安裝 opennsfw2 庫。圖片素材請參考 小結中地址進行下載。

pip install opennsfw2

2.代碼實踐

圖片識別 代碼如下:

import opennsfw2 as n2# 將自動下載預訓練模型 open_nsfw_weights.h5 到 C:\Users\Administrator\.opennsfw2\weights # pip install opennsfw2# 單張預測 image_path = '1.jpg' nsfw_probability = n2.predict_image(image_path) print(nsfw_probability) # 0.16282974183559418# 批量預測 image_paths = ['1.jpg', '2.jpg'] nsfw_probabilities = n2.predict_images(image_paths) print(nsfw_probabilities) # [0.16282965242862701, 0.8638442158699036]

視頻識別 代碼如下:

import opennsfw2 as n2video_path = '1.mp4' elapsed_seconds, nsfw_probabilities = n2.predict_video_frames(video_path) for second, probability in zip(elapsed_seconds, nsfw_probabilities):print(f'{second:.2f}s: {probability * 100:.0f} %') # 0.03s: 1% # ... # 10.01s: 87.00% # ... # 10.64s: 69.00%

高級用法

1. 加載的方式

import numpy as np from PIL import Image from opennsfw2._model import make_open_nsfw_model from opennsfw2._image import preprocess_image, Preprocessingimage_path = '1.jpg' image = preprocess_image(Image.open(image_path), Preprocessing.YAHOO) model = make_open_nsfw_model() nsfw_probability = float(model.predict(np.expand_dims(image, 0), batch_size=1)[0][1]) print(nsfw_probability) # 0.16282974183559418

2.車速檢測

import time import numpy as np import tkinter as tk from pathlib import Path from tkinter import filedialog from tkinter import messagebox from PIL import ImageTk, Imagefrom opennsfw2._model import make_open_nsfw_model from opennsfw2._image import preprocess_image, Preprocessingbegin = time.time() model = make_open_nsfw_model() # 加載模型 elapsed = time.time() - begin # 加載模型耗時 initialdir = Path.cwd() # 初始化目錄,可切換為圖片Path.home() / 'Pictures' img = None # 當前打開的圖片def scale(size, width=None, height=None):"""獲取按比例縮放后的寬高"""if not width and not height:width, height = sizeif not width or not height:_width, _height = sizeheight = width * _height / _width if width else heightwidth = height * _width / _height if height else widthreturn int(width), int(height)def img_resize(event=None):"""顯示圖片"""global imgif img:_img = img.resize(scale(img.size, height=win.winfo_height()))_img = ImageTk.PhotoImage(_img)label.config(image=_img)label.image = _imgdef on_closing():"""關閉事件"""if messagebox.askokcancel('關閉', '是否退出程序?'):win.destroy()def open_file(event=None):"""打開圖片"""global initialdirglobal imgfile_path = filedialog.askopenfilename(title='選擇圖片', initialdir=initialdir,filetypes=[('image files', ('.png', '.jpg', '.jpeg', '.gif'))])if file_path:statusbar.config(text='正在加載...')statusbar.update_idletasks()begin = time.time()path = Path(file_path)initialdir = path.parentimg = Image.open(file_path)img_resize()_img = preprocess_image(Image.open(file_path), Preprocessing.YAHOO)probability = float(model.predict(np.expand_dims(_img, 0), batch_size=1)[0][1])print(probability)end = time.time()statusbar.config(text=f'{path.name} 耗時: {end - begin:.2f}s 概率: {probability * 100:.2f} %')win = tk.Tk() win.title('黃圖檢測') # 標題 menu = tk.Menu(win) menu.add_command(label='打開', command=open_file) win.config(menu=menu) win.bind('<Configure>', img_resize) win.geometry('600x300+300+300') win.minsize(200, 200) win.protocol('WM_DELETE_WINDOW', on_closing) statusbar = tk.Label(win, text=f'加載模型耗時: {elapsed:.2f}s', bd=1, relief=tk.SUNKEN, anchor=tk.W, name='statusbar') statusbar.pack(side=tk.BOTTOM, fill=tk.X) label = tk.Label(win, text='雙擊打開圖片') label.bind('<Double-Button-1>', open_file) label.pack(fill=tk.BOTH, expand=True) win.mainloop()

3. 視頻車速檢測(無聲)

import time import threading import tkinter as tk from pathlib import Path from tkinter import filedialog from tkinter import messagebox from timeit import default_timer as timerimport imageio import numpy as np from PIL import ImageTk, Imagefrom opennsfw2._model import make_open_nsfw_model from opennsfw2._image import preprocess_image, Preprocessing# pip install imageio-ffmpegbegin = time.time() model = make_open_nsfw_model() # 加載模型 elapsed = time.time() - begin # 加載模型耗時 initialdir = Path.cwd() # 初始化目錄,可切換為圖片Path.home() / 'Pictures' reader = None # 視頻讀取器accum_time = 0 curr_fps = 0 last_fps = 0 prev_time = timer()def on_closing():"""關閉事件"""if messagebox.askokcancel('關閉', '是否退出程序?'):win.destroy()def play():global readerglobal prev_time, accum_time, curr_fpsfor image in reader:image = Image.fromarray(image)frame_image = ImageTk.PhotoImage(image)label.config(image=frame_image)label.image = frame_image_img = preprocess_image(image, Preprocessing.YAHOO)probability = float(model.predict(np.expand_dims(_img, 0), batch_size=1)[0][1])# FPScurr_time = timer()exec_time = curr_time - prev_timeprev_time = curr_timeaccum_time = accum_time + exec_timecurr_fps = curr_fps + 1if accum_time > 1:accum_time = accum_time - 1last_fps = curr_fpscurr_fps = 0statusbar.config(text=f'概率: {probability * 100:.2f} % FPS: {last_fps}')def open_file(event=None):"""打開視頻"""global initialdirglobal readerfile_path = filedialog.askopenfilename(title='選擇視頻', initialdir=initialdir,filetypes=[('Select files', ('.mp4', '.mkv', '.avi', '.wmv'))])if file_path:statusbar.config(text='正在加載...')statusbar.update_idletasks()path = Path(file_path)initialdir = path.parentreader = imageio.get_reader(path)thread = threading.Thread(target=play, daemon=True)thread.start()win = tk.Tk() win.title('黃圖檢測') # 標題 menu = tk.Menu(win) menu.add_command(label='打開', command=open_file) win.config(menu=menu) win.geometry('1280x720+300+300') win.minsize(200, 200) win.protocol('WM_DELETE_WINDOW', on_closing) statusbar = tk.Label(win, text=f'加載模型耗時: {elapsed:.2f}s', bd=1, relief=tk.SUNKEN, anchor=tk.W, name='statusbar') statusbar.pack(side=tk.BOTTOM, fill=tk.X) label = tk.Label(win, text='雙擊打開視頻') label.bind('<Double-Button-1>', open_file) label.pack(fill=tk.BOTH, expand=True) win.mainloop()

4. 視頻車速檢測(有聲)

import ioimport pyglet import numpy as np from PIL import Image from opennsfw2._model import make_open_nsfw_model from opennsfw2._image import preprocess_image, Preprocessing# pip install pygletmodel = make_open_nsfw_model() filename = '1.mp4' source = pyglet.media.load(filename) video_format = source.video_format width, height = video_format.width, video_format.height title = 'Video Player' window = pyglet.window.Window(width, height, title) player = pyglet.media.Player() player.queue(source) player.play()@window.event def on_draw():window.clear()if player.source and player.source.video_format:player.get_texture().blit(0, 0, width=width, height=height)image_data = player.get_texture().get_image_data()pitch = -(image_data.width * len('RGB'))data = image_data.get_data('RGB', pitch)_img = preprocess_image(Image.frombytes('RGB', (width, height), data, 'raw'), Preprocessing.YAHOO)probability = float(model.predict(np.expand_dims(_img, 0), batch_size=1)[0][1])print(probability)pyglet.app.run()

運行結果:

效率分析: get_data() 0.941 s frombytes() 0.001 s preprocess_image() 0.006 s predict() 0.052 s

小結

參考: https://blog.csdn.net/lly1122334/article/details/121247781
https://github.com/bhky/opennsfw2

資源: https://img-blog.csdnimg.cn/20210702231858370.jpg
http://www.lenna.org/full/len_full.jpg

總結

以上是生活随笔為你收集整理的Python:使用opennsfw2对图片/视频进行鉴黄识别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。