from watchdog.observers import Observer
from watchdog.events import *
import time
import sys
import os
import _io
from collections import namedtuple
from PIL import Image
import argparseclass Nude(object):
Skin = namedtuple("Skin", "id skin region x y")
def __init__(self, path_or_image):
# 若 path_or_image 為 Image.Image 類型的實例,直接賦值
if isinstance(path_or_image, Image.Image):
self.image = path_or_image
# 若 path_or_image 為 str 類型的實例,打開圖片
elif isinstance(path_or_image, str):
self.image = Image.open(path_or_image) # 獲得圖片所有顏色通道
bands = self.image.getbands()
# 判斷是否為單通道圖片(也即灰度圖),是則將灰度圖轉換為 RGB 圖
if len(bands) == 1:
# 新建相同大小的 RGB 圖像
new_img = Image.new("RGB", self.image.size)
# 拷貝灰度圖 self.image 到 RGB圖 new_img.paste (PIL 自動進行顏色通道轉換)
new_img.paste(self.image)
f = self.image.filename
# 替換 self.image
self.image = new_img
self.image.filename = f # 存儲對應圖像所有像素的全部 Skin 對象
self.skin_map = []
# 檢測到的皮膚區域,元素的索引即為皮膚區域號,元素都是包含一些 Skin 對象的列表
self.detected_regions = []
# 元素都是包含一些 int 對象(區域號)的列表
# 這些元素中的區域號代表的區域都是待合併的區域
self.merge_regions = []
# 整合後的皮膚區域,元素的索引即為皮膚區域號,元素都是包含一些 Skin 對象的列表
self.skin_regions = []
# 最近合併的兩個皮膚區域的區域號,初始化為 -1
self.last_from, self.last_to = -1, -1
# 色情圖像判斷結果
self.result = None
# 處理得到的信息
self.message = None
# 圖像寬高
self.width, self.height = self.image.size
# 圖像總像素
self.total_pixels = self.width * self.height def resize(self, maxwidth=1000, maxheight=1000):
"""
基於最大寬高按比例重設圖片大小,
注意:這可能影響檢測算法的結果 如果沒有變化返回 0
原寬度大於 maxwidth 返回 1
原高度大於 maxheight 返回 2
原寬高大於 maxwidth, maxheight 返回 3 maxwidth - 圖片最大寬度
maxheight - 圖片最大高度
傳遞參數時都可以設置為 False 來忽略
"""
# 存儲返回值
ret = 0
if maxwidth:
if self.width > maxwidth:
wpercent = (maxwidth / self.width)
hsize = int((self.height * wpercent))
fname = self.image.filename
# Image.LANCZOS 是重採樣濾波器,用於抗鋸齒
self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS)
self.image.filename = fname
self.width, self.height = self.image.size
self.total_pixels = self.width * self.height
ret += 1
if maxheight:
if self.height > maxheight:
hpercent = (maxheight / float(self.height))
wsize = int((float(self.width) * float(hpercent)))
fname = self.image.filename
self.image = self.image.resize((wsize, maxheight), Image.LANCZOS)
self.image.filename = fname
self.width, self.height = self.image.size
self.total_pixels = self.width * self.height
ret += 2
return ret # 分析函數
def parse(self):
# 如果已有結果,返回本對象
if self.result is not None:
return self
# 獲得圖片所有像素數據
pixels = self.image.load()
# 遍歷每個像素
for y in range(self.height):
for x in range(self.width):
# 得到像素的 RGB 三個通道的值
# [x, y] 是 [(x,y)] 的簡便寫法
r = pixels[x, y][0] # red
g = pixels[x, y][1] # green
b = pixels[x, y][2] # blue
# 判斷當前像素是否為膚色像素
isSkin = True if self._classify_skin(r, g, b) else False
# 給每個像素分配唯一 id 值(1, 2, 3...height*width)
# 注意 x, y 的值從零開始
_id = x + y * self.width + 1
# 為每個像素創建一個對應的 Skin 對象,並添加到 self.skin_map 中
self.skin_map.append(self.Skin(_id, isSkin, None, x, y))
# 若當前像素不為膚色像素,跳過此次循環
if not isSkin:
continue # 設左上角為原點,相鄰像素為符號 *,當前像素為符號 ^,那麼相互位置關係通常如下圖
# ***
# *^ # 存有相鄰像素索引的列表,存放順序為由大到小,順序改變有影響
# 注意 _id 是從 1 開始的,對應的索引則是 _id-1
check_indexes = [_id - 2, # 當前像素左方的像素
_id - self.width - 2, # 當前像素左上方的像素
_id - self.width - 1, # 當前像素的上方的像素
_id - self.width] # 當前像素右上方的像素
# 用來記錄相鄰像素中膚色像素所在的區域號,初始化為 -1
region = -1
# 遍歷每一個相鄰像素的索引
for index in check_indexes:
# 嘗試索引相鄰像素的 Skin 對象,沒有則跳出循環
try:
self.skin_map[index]
except IndexError:
break
# 相鄰像素若為膚色像素:
if self.skin_map[index].skin:
# 若相鄰像素與當前像素的 region 均為有效值,且二者不同,且尚未添加相同的合併任務
if (self.skin_map[index].region != None and
region != None and region != -1 and
self.skin_map[index].region != region and
self.last_from != region and
self.last_to != self.skin_map[index].region) :
# 那麼這添加這兩個區域的合併任務
self._add_merge(region, self.skin_map[index].region)
# 記錄此相鄰像素所在的區域號
region = self.skin_map[index].region
# 遍歷完所有相鄰像素後,若 region 仍等於 -1,説明所有相鄰像素都不是膚色像素
if region == -1:
# 更改屬性為新的區域號,注意元祖是不可變類型,不能直接更改屬性
_skin = self.skin_map[_id - 1]._replace(region=len(self.detected_regions))
self.skin_map[_id - 1] = _skin
# 將此膚色像素所在區域創建為新區域
self.detected_regions.append([self.skin_map[_id - 1]])
# region 不等於 -1 的同時不等於 None,説明有區域號為有效值的相鄰膚色像素
elif region != None:
# 將此像素的區域號更改為與相鄰像素相同
_skin = self.skin_map[_id - 1]._replace(region=region)
self.skin_map[_id - 1] = _skin
# 向這個區域的像素列表中添加此像素
self.detected_regions[region].append(self.skin_map[_id - 1])
# 完成所有區域合併任務,合併整理後的區域存儲到 self.skin_regions
self._merge(self.detected_regions, self.merge_regions)
# 分析皮膚區域,得到判定結果
self._analyse_regions()
return self # self.merge_regions 的元素都是包含一些 int 對象(區域號)的列表
# self.merge_regions 的元素中的區域號代表的區域都是待合併的區域
# 這個方法便是將兩個待合併的區域號添加到 self.merge_regions 中
def _add_merge(self, _from, _to):
# 兩個區域號賦值給類屬性
self.last_from = _from
self.last_to = _to # 記錄 self.merge_regions 的某個索引值,初始化為 -1
from_index = -1
# 記錄 self.merge_regions 的某個索引值,初始化為 -1
to_index = -1 # 遍歷每個 self.merge_regions 的元素
for index, region in enumerate(self.merge_regions):
# 遍歷元素中的每個區域號
for r_index in region:
if r_index == _from:
from_index = index
if r_index == _to:
to_index = index # 若兩個區域號都存在於 self.merge_regions 中
if from_index != -1 and to_index != -1:
# 如果這兩個區域號分別存在於兩個列表中
# 那麼合併這兩個列表
if from_index != to_index:
self.merge_regions[from_index].extend(self.merge_regions[to_index])
del(self.merge_regions[to_index])
return # 若兩個區域號都不存在於 self.merge_regions 中
if from_index == -1 and to_index == -1:
# 創建新的區域號列表
self.merge_regions.append([_from, _to])
return
# 若兩個區域號中有一個存在於 self.merge_regions 中
if from_index != -1 and to_index == -1:
# 將不存在於 self.merge_regions 中的那個區域號
# 添加到另一個區域號所在的列表
self.merge_regions[from_index].append(_to)
return
# 若兩個待合併的區域號中有一個存在於 self.merge_regions 中
if from_index == -1 and to_index != -1:
# 將不存在於 self.merge_regions 中的那個區域號
# 添加到另一個區域號所在的列表
self.merge_regions[to_index].append(_from)
return # 合併該合併的皮膚區域
def _merge(self, detected_regions, merge_regions):
# 新建列表 new_detected_regions
# 其元素將是包含一些代表像素的 Skin 對象的列表
# new_detected_regions 的元素即代表皮膚區域,元素索引為區域號
new_detected_regions = [] # 將 merge_regions 中的元素中的區域號代表的所有區域合併
for index, region in enumerate(merge_regions):
try:
new_detected_regions[index]
except IndexError:
new_detected_regions.append([])
for r_index in region:
new_detected_regions[index].extend(detected_regions[r_index])
detected_regions[r_index] = [] # 添加剩下的其餘皮膚區域到 new_detected_regions
for region in detected_regions:
if len(region) > 0:
new_detected_regions.append(region) # 清理 new_detected_regions
self._clear_regions(new_detected_regions) # 皮膚區域清理函數
# 只保存像素數大於指定數量的皮膚區域
def _clear_regions(self, detected_regions):
for region in detected_regions:
if len(region) > 30:
self.skin_regions.append(region) # 分析區域
def _analyse_regions(self):
# 如果皮膚區域小於 3 個,不是色情
# if len(self.skin_regions) < 3:
# self.message = "Less than 2 skin regions ({_skin_regions_size})".format(
# _skin_regions_size=len(self.skin_regions))
# self.result = False
# return self.result # 為皮膚區域排序
self.skin_regions = sorted(self.skin_regions, key=lambda s: len(s),
reverse=True) # 計算皮膚總像素數
total_skin = float(sum([len(skin_region) for skin_region in self.skin_regions])) # 如果皮膚區域與整個圖像的比值小於 15%,那麼不是色情圖片
if total_skin / self.total_pixels * 100 < 15:
self.message = "Total skin percentage lower than 15 ({:.2f})".format(total_skin / self.total_pixels * 100)
self.result = False
return self.result # 如果最大皮膚區域小於總皮膚面積的 45%,不是色情圖片
if len(self.skin_regions[0]) / total_skin * 100 < 45:
self.message = "The biggest region contains less than 45 ({:.2f})".format(len(self.skin_regions[0]) / total_skin * 100)
self.result = False
return self.result # 皮膚區域數量超過 60個,不是色情圖片
if len(self.skin_regions) > 60:
self.message = "More than 60 skin regions ({})".format(len(self.skin_regions))
self.result = False
return self.result # 其它情況為色情圖片
self.message = "Nude!!"
self.result = True
return self.result # 基於像素的膚色檢測技術
def _classify_skin(self, r, g, b):
# 根據RGB值判定
rgb_classifier = r > 95 and \
g > 40 and g < 100 and \
b > 20 and \
max([r, g, b]) - min([r, g, b]) > 15 and \
abs(r - g) > 15 and \
r > g and \
r > b
# 根據處理後的 RGB 值判定
nr, ng, nb = self._to_normalized(r, g, b)
norm_rgb_classifier = nr / ng > 1.185 and \
float(r * b) / ((r + g + b) ** 2) > 0.107 and \
float(r * g) / ((r + g + b) ** 2) > 0.112 # HSV 顏色模式下的判定
h, s, v = self._to_hsv(r, g, b)
hsv_classifier = h > 0 and \
h < 35 and \
s > 0.23 and \
s < 0.68 # YCbCr 顏色模式下的判定
y, cb, cr = self._to_ycbcr(r, g, b)
ycbcr_classifier = 97.5 <= cb <= 142.5 and 134 <= cr <= 176 # 效果不是很好,還需改公式
# return rgb_classifier or norm_rgb_classifier or hsv_classifier or ycbcr_classifier
return ycbcr_classifier def _to_normalized(self, r, g, b):
if r == 0:
r = 0.0001
if g == 0:
g = 0.0001
if b == 0:
b = 0.0001
_sum = float(r + g + b)
return [r / _sum, g / _sum, b / _sum] def _to_ycbcr(self, r, g, b):
# 公式來源:
# http://stackoverflow.com/questions/19459831/rgb-to-ycbcr-conversion-problems
y = .299*r + .587*g + .114*b
cb = 128 - 0.168736*r - 0.331364*g + 0.5*b
cr = 128 + 0.5*r - 0.418688*g - 0.081312*b
return y, cb, cr def _to_hsv(self, r, g, b):
h = 0
_sum = float(r + g + b)
_max = float(max([r, g, b]))
_min = float(min([r, g, b]))
diff = float(_max - _min)
if _sum == 0:
_sum = 0.0001 if _max == r:
if diff == 0:
h = sys.maxsize
else:
h = (g - b) / diff
elif _max == g:
h = 2 + ((g - r) / diff)
else:
h = 4 + ((r - g) / diff) h *= 60
if h < 0:
h += 360 return [h, 1.0 - (3.0 * (_min / _sum)), (1.0 / 3.0) * _max]
def inspect(self):
_image = '{} {} {}×{}'.format(self.image.filename, self.image.format, self.width, self.height)
return "{_image}: result={_result} message='{_message}'".format(_image=_image, _result=self.result, _message=self.message) # 將在源文件目錄生成圖片文件,將皮膚區域可視化
def showSkinRegions(self):
# 未得出結果時方法返回
if self.result is None:
return
# 皮膚像素的 ID 的集合
skinIdSet = set()
# 將原圖做一份拷貝
simage = self.image
# 加載數據
simageData = simage.load() # 將皮膚像素的 id 存入 skinIdSet
for sr in self.skin_regions:
for pixel in sr:
skinIdSet.add(pixel.id)
# 將圖像中的皮膚像素設為白色,其餘設為黑色
for pixel in self.skin_map:
if pixel.id not in skinIdSet:
simageData[pixel.x, pixel.y] = 0, 0, 0
else:
simageData[pixel.x, pixel.y] = 255, 255, 255
# 源文件絕對路徑
filePath = os.path.abspath(self.image.filename)
# 源文件所在目錄
fileDirectory = os.path.dirname(filePath) + '/'
# 源文件的完整文件名
fileFullName = os.path.basename(filePath)
# 分離源文件的完整文件名得到文件名和擴展名
fileName, fileExtName = os.path.splitext(fileFullName)
# 保存圖片
simage.save('{}{}_{}{}'.format(fileDirectory, fileName,'Nude' if self.result else 'Normal', fileExtName)) def del_files(path):
for root , dirs, files in os.walk(path):
for name in files:
if name.endswith(".CR2"):
os.remove(os.path.join(root, name))
print ("Delete File: " + os.path.join(root, name))class FileEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self)
def on_created(self, event):
if event.is_directory:
pass
else:
time.sleep(0.1)
fname = "{0}".format(event.src_path)
#fname = "d:/test/new/c.jpg"
if os.path.isfile(fname):
n = Nude(fname)
n.resize(maxheight=800, maxwidth=600)
n.parse()
print(n.result, n.inspect())
if(n.result):
print('true')
my_file = fname
if os.path.exists(my_file):
#刪除文件
os.remove(my_file)
else:
print("false")
else:
print(fname, "is not a file")
if __name__ == "__main__":
observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler,'d:\\test',True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
本文章為轉載內容,我們尊重原作者對文章享有的著作權。如有內容錯誤或侵權問題,歡迎原作者聯繫我們進行內容更正或刪除文章。