Spaces:
Running
Running
File size: 2,245 Bytes
88236cc 7a4063f 88236cc dc8c83e 88236cc dc8c83e 88236cc dc8c83e 88236cc d41c204 dc8c83e 88236cc dc8c83e 88236cc d41c204 88236cc 5458b42 7a4063f dc8c83e 88236cc 7a4063f 88236cc b685f81 88236cc 5458b42 7a4063f d41c204 7a4063f dc8c83e 7a4063f dc8c83e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
#!/usr/bin/env python
import functools
import os
import pathlib
import tarfile
import urllib.request
import cv2
import gradio as gr
import huggingface_hub
import numpy as np
DESCRIPTION = "# [nagadomi/lbpcascade_animeface](https://github.com/nagadomi/lbpcascade_animeface)"
def load_sample_image_paths() -> list[pathlib.Path]:
image_dir = pathlib.Path("images")
if not image_dir.exists():
dataset_repo = "hysts/sample-images-TADNE"
path = huggingface_hub.hf_hub_download(dataset_repo, "images.tar.gz", repo_type="dataset")
with tarfile.open(path) as f:
f.extractall() # noqa: S202
return sorted(image_dir.glob("*"))
def load_model() -> cv2.CascadeClassifier:
url = "https://raw.githubusercontent.com/nagadomi/lbpcascade_animeface/master/lbpcascade_animeface.xml"
path = pathlib.Path("lbpcascade_animeface.xml")
if not path.exists():
urllib.request.urlretrieve(url, path.as_posix()) # noqa: S310
return cv2.CascadeClassifier(path.as_posix())
def detect(image_path: str, detector: cv2.CascadeClassifier) -> np.ndarray:
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
preds = detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(24, 24))
res = image.copy()
for x, y, w, h in preds:
cv2.rectangle(res, (x, y), (x + w, y + h), (0, 255, 0), 2)
return res[:, :, ::-1]
image_paths = load_sample_image_paths()
examples = [[path.as_posix()] for path in image_paths]
detector = load_model()
fn = functools.partial(detect, detector=detector)
with gr.Blocks(css_paths="style.css") as demo:
gr.Markdown(DESCRIPTION)
with gr.Row():
with gr.Column():
image = gr.Image(label="Input", type="filepath")
run_button = gr.Button()
with gr.Column():
result = gr.Image(label="Result")
gr.Examples(
examples=examples,
inputs=image,
outputs=result,
fn=fn,
cache_examples=os.getenv("CACHE_EXAMPLES") == "1",
)
run_button.click(
fn=fn,
inputs=image,
outputs=result,
api_name="predict",
)
if __name__ == "__main__":
demo.queue(max_size=15).launch()
|