0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ColabでFalconsai/nsfw_image_detectionを試してみた~画像の安全性チェック~

Posted at

はじめに

Hugging Faceに公開されている Falconsai/nsfw_image_detection は、Vision Transformer (ViT) をベースに「通常画像」か「NSFW画像」かを判定するシンプルな分類器です。精度は約98%と高く、Webアプリや自動化ワークフローに組み込みやすいのが特徴です。

今回はこのモデルを Google Colab 上で動かし、
・画像アップロードでの即時判定(Gradio UI)
・複数画像を一括処理 → CSV保存
・判定結果の集計と「要確認」候補の抽出
まで一気にやってみました。

セットアップ

1Colab環境で必要なライブラリをインストールしてモデルを呼び出します。

!pip -q install "transformers==4.43.2" timm pillow accelerate gradio
from transformers import pipeline

GPUがなくてもCPUで動作しますが、A100などが割り当てられていれば自動的にGPUを利用できます。
2 Gradioで判定UIを作成
簡単に使えるアップローダーUIを用意しました。

import gradio as gr
from PIL import Image
import torch

device = 0 if torch.cuda.is_available() else -1
cls = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=device)

def judge(img: Image.Image):
    r = cls(img)[0]
    return {"label": r["label"], "score": float(r["score"])}

demo = gr.Interface(fn=judge, inputs=gr.Image(type="pil"), outputs="json",
                    title="NSFW Detector (Falconsai)")
demo.launch(share=True)

Colabで実行すると https://xxxx.gradio.live のリンクが出ます。そこから画像をアップロード → 判定結果(normal/nsfw + スコア)が表示されます。

3 複数画像を一括判定 → CSV出力
フォルダ内の画像をまとめて処理し、結果をCSVに保存しました。

import csv, glob, os
from PIL import Image

cls = pipeline("image-classification", model="Falconsai/nsfw_image_detection")

rows = [("path","label","score")]
for p in glob.glob("/content/images/*"):
    img = Image.open(p).convert("RGB")
    r = cls(img)[0]
    rows.append((p, r["label"], f'{r["score"]:.6f}'))

with open("result.csv","w",newline="",encoding="utf-8") as f:
    csv.writer(f).writerows(rows)

集計結果

ファイル名 label score
1a normal 0.986223
2a normal 0.981359
3a normal 0.986476

1a
1a.jpg
2a
2a.jpg
3a
3a.jpg

まとめ

・Falconsai/nsfw_image_detection は簡単にColab上で動かせる高精度なNSFW分類器。
・Gradioを使えば即席のWeb判定UIが作れる。
・複数画像を一括処理 → CSV出力 → 「要確認」リスト抽出まで自動化可能。
・運用では しきい値設定 と 人手レビュー を組み合わせるのが安全。

これで「とりあえず画像をスクリーニングしたい」というニーズには十分応えられます。今後は閾値調整や別モデルとの組み合わせで精度をさらに高めるのも良さそうです。


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

[Twitter)(https://twitter.com/JackdeS11)
Medium

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?