|
import gradio as gr |
|
import numpy as np |
|
import urllib |
|
import cv2 |
|
from tensorflow.keras.preprocessing import image |
|
from tensorflow.keras.models import load_model |
|
|
|
|
|
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") |
|
|
|
|
|
model = load_model('my_model.h5') |
|
def classify_image(img): |
|
|
|
|
|
|
|
img_copy = img |
|
height, width = img_copy.shape[0], img_copy.shape[1] |
|
|
|
img_copy = cv2.resize(img_copy, (500, 500)) |
|
|
|
gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY) |
|
|
|
|
|
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) |
|
|
|
if len(faces) > 0: |
|
|
|
face_area_list = [] |
|
|
|
for (x, y, w, h) in faces: |
|
cv2.rectangle(img_copy, (x, y), (x+w, y+h), (0, 255, 0), 2) |
|
area = w * h |
|
face_area_list.append(area) |
|
|
|
big_face_area = sorted(face_area_list)[-1] |
|
img_area = img_copy.shape[0] * img_copy.shape[1] |
|
|
|
|
|
|
|
perc_area = (big_face_area/img_area)*100 |
|
if perc_area>7.5: |
|
img = image.img_to_array(img) |
|
img = np.expand_dims(img, axis=0) |
|
img /= 255.0 |
|
|
|
|
|
prediction = model.predict(img)[0] |
|
|
|
dic = {'SFW': float(prediction[1]), 'NSFW': float(prediction[0])} |
|
else : |
|
dic = {'SFW': float(0), 'NSFW': float(1)} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
else: |
|
dic = {'SFW': float(0), 'NSFW': float(1)} |
|
|
|
|
|
return dic |
|
|
|
def classify_url(url): |
|
|
|
response = urllib.request.urlopen(url) |
|
img = image.load_img(response, target_size=(224, 224)) |
|
|
|
return classify_image(img) |
|
|
|
|
|
|
|
examples = [f"example{i}.jpg" for i in range(1,9)] |
|
|
|
app = gr.Interface(classify_image, gr.Image(shape=(224, 224)), outputs="label", allow_flagging="never", examples = examples,title="NSFW/SFW Classifier") |
|
|
|
|
|
app.launch() |
|
|
|
|