Spaces:
Runtime error
Runtime error
Commit ·
8096125
1
Parent(s): b0c1552
Add application file
Browse filesFiles changed (49)
- README.md+122-12
- __pycache__/app.cpython-312.pycAdded
- __pycache__/conftest.cpython-312-pytest-8.4.2.pycAdded
- __pycache__/developer_api.cpython-312.pycAdded
- app.pyAdded+471
- assets/sample_cells.pngAdded
- assets/sample_grid.pngAdded
- assets/sample_portrait_placeholder.pngAdded
- assets/style_texture_1.pngAdded
- assets/style_texture_2.pngAdded
- assets/style_texture_3.pngAdded
- batch/__init__.pyAdded
- batch/__pycache__/__init__.cpython-312.pycAdded
- batch/__pycache__/dataset_processor.cpython-312.pycAdded
- batch/dataset_processor.pyAdded+61
- cli.pyAdded+98
- conftest.pyAdded+6
- cv_ops/__init__.pyAdded
- cv_ops/__pycache__/__init__.cpython-312.pycAdded
- cv_ops/__pycache__/analysis.cpython-312.pycAdded
- cv_ops/__pycache__/morphology.cpython-312.pycAdded
- cv_ops/__pycache__/transforms.cpython-312.pycAdded
- cv_ops/analysis.pyAdded+44
- cv_ops/morphology.pyAdded+49
- cv_ops/transforms.pyAdded+46
- developer_api.pyAdded+102
- filters/__init__.pyAdded
- filters/__pycache__/__init__.cpython-312.pycAdded
- filters/__pycache__/builtin.cpython-312.pycAdded
- filters/__pycache__/custom.cpython-312.pycAdded
- filters/__pycache__/registry.cpython-312.pycAdded
- filters/builtin.pyAdded+137
- filters/custom.pyAdded+37
- filters/registry.pyAdded+98
- models/__init__.pyAdded
- models/__pycache__/__init__.cpython-312.pycAdded
- models/__pycache__/face_filters.cpython-312.pycAdded
- models/__pycache__/style_transfer.cpython-312.pycAdded
- models/face_filters.pyAdded+352
- models/style_transfer.pyAdded+41
- pytest.iniAdded+4
- requirements.txtAdded+10
- saved_ar_filters/ar_filters_registry.jsonAdded+210
- saved_ar_filters/fa0c305e-44b6-459a-ae32-a1256dc2ecc2.jsonAdded+204
- saved_filters/filters_registry.jsonAdded+1
- tests/__pycache__/test_cv_ops.cpython-312-pytest-8.4.2.pycAdded
- tests/__pycache__/test_developer_api.cpython-312-pytest-8.4.2.pycAdded
- tests/test_cv_ops.pyAdded+90
- tests/test_developer_api.pyAdded+51
123456789101112131415---title: AI Lab CAMemoji: 😻colorFrom: indigocolorTo: redsdk: gradiosdk_version: 6.23.1python_version: '3.12'app_file: app.pypinned: falselicense: apache-2.0short_description: AI Lab CAM---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# CV Lab CameraCV Lab Camera is a local Gradio application and developer suite for computer vision, scientific image analysis, geometric transformations, morphology, neural style transfer, AR face overlays, and batch dataset processing.---## Developer Quickstart### 1. Web AppLaunch the interactive Gradio laboratory:```bashpython app.py```### 2. Command Line Interface (CLI)Process images directly from your terminal or shell scripts:```bash# Apply built-in filterpython cli.py filter --input input.jpg --filter Sepia --output result.jpg# Apply geometric transformationpython cli.py transform --input input.jpg --op Rotation --angle 45 --output result.jpg# Apply morphological operationpython cli.py morph --input input.jpg --op Opening --size 5 --output result.jpg# Apply AR face overlaypython cli.py ar --input face.jpg --filter Glasses --output ar_result.jpg# Apply neural style transferpython cli.py style --input content.jpg --style-image style.jpg --output stylized.jpg# Batch process datasetpython cli.py batch --dir ./my_dataset --filter Grayscale --output-zip processed.zip```### 3. Python Developer SDK (`developer_api.py`)Import CV Lab functions directly in your Python code:```pythonfrom developer_api import process_image, generate_python_snippet# Process image programmaticallyresult, meta = process_image(image_input="photo.png",operation_type="filter",operation_name="Sepia",output_path="output_sepia.png")# Generate copy-pasteable Python codecode = generate_python_snippet("Sepia", {"contrast": 1.2})print(code)```---## Architecture Overview```ComputerVision_Project/├── app.py # Gradio UI Web App (interactive tabs & code generator)├── cli.py # Developer Command Line Interface (CLI)├── developer_api.py # Developer SDK / Python API wrapper├── batch/│ └── dataset_processor.py # Batch directory/zip processing with manifest.json├── cv_ops/│ ├── analysis.py # Intensity histograms & pixel statistics│ ├── morphology.py # Thresholding & morphological operations│ └── transforms.py # Translation, rotation, scaling, reflection├── filters/│ ├── builtin.py # Pure NumPy / OpenCV filter functions│ ├── custom.py # Custom kernel & pipeline JSON parsers│ └── registry.py # Filter registry & saved JSON persistence├── models/│ ├── face_filters.py # OpenCV AR face landmark detector & filter engine│ └── style_transfer.py # TensorFlow Hub Magenta neural style transfer├── saved_filters/ # Saved custom filter JSONs├── saved_ar_filters/ # Saved custom AR filter JSONs├── tests/ # Pytest suite└── requirements.txt # Python dependencies```---## Custom Filters & AR Filters### Image Processing Filter PipelinesSave multi-step filter pipelines as JSON:```json[{"operation": "Grayscale", "params": {}},{"operation": "Sharpen", "params": {"amount": 1.4}}]```### Custom AR Face FiltersDesign landmark-based AR overlays attached to `head_top`, `forehead`, `eyes`, `nose`, `mouth`, `chin`:```json{"elements": [{"landmark": "forehead","shape": "crown","color": [255, 215, 0],"scale": 1.0,"offset_y": -0.15},{"landmark": "eyes","shape": "visor","color": [0, 255, 255],"scale": 1.0}]}```---## TestingRun the test suite:```bashpytest```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471"""CV Lab Camera: Gradio scientific camera and image filtering lab."""
from __future__ import annotations
import jsonimport tempfilefrom pathlib import Pathfrom typing import Any
import gradio as grimport numpy as npfrom PIL import Image
from batch.dataset_processor import process_datasetfrom cv_ops.analysis import histogram_figure, low_resolution_pair, pixel_preview, statsfrom cv_ops.morphology import apply_morphologyfrom cv_ops.transforms import reflect, rotate, scale_image, translatefrom filters.builtin import BUILTIN_FILTERS, ensure_rgbfrom filters.custom import parse_kernel, parse_pipelinefrom filters.registry import apply_definition, apply_step, delete_filter, load_definition, names, operation_to_definition, save_filterfrom models.face_filters import apply_face_filter, ar_filter_names, delete_ar_filter, load_ar_definition, save_ar_filterfrom models.style_transfer import stylize
ROOT = Path(__file__).resolve().parentSTYLE_SAMPLES = sorted(str(p) for p in (ROOT / "assets").glob("style_*.png"))
DEFAULT_CUSTOM_AR_JSON = json.dumps( { "elements": [ {"landmark": "forehead", "shape": "crown", "color": [255, 215, 0], "scale": 1.0, "offset_y": -0.15}, {"landmark": "eyes", "shape": "visor", "color": [0, 255, 255], "scale": 1.0}, {"landmark": "mouth", "shape": "mustache", "color": [40, 20, 20], "scale": 0.9, "offset_y": -0.05}, ] }, indent=2,)
def export_image(image: np.ndarray | None) -> str | None: if image is None: return None arr = np.asarray(image) if arr.ndim == 2: img_obj = Image.fromarray(arr) else: img_obj = Image.fromarray(arr.astype(np.uint8)) out_dir = Path(tempfile.mkdtemp(prefix="cv_lab_dl_")) filepath = out_dir / "cv_lab_result.png" img_obj.save(filepath) return str(filepath)
def set_global_image(image: np.ndarray | None) -> tuple[np.ndarray | None, np.ndarray | None, str]: if image is None: return None, None, "No image loaded." img = ensure_rgb(image) return img, img, f"Loaded image: {img.shape[1]} x {img.shape[0]}"
def make_code_snippet(operation: str, params: dict[str, Any]) -> str: params_str = json.dumps(params, indent=2) return f"""import numpy as npfrom PIL import Imagefrom filters.registry import apply_step
image = np.array(Image.open("input.png").convert("RGB"))params = {params_str}result = apply_step(image, "{operation}", params)Image.fromarray(result).save("output.png")"""
def run_builtin(image: np.ndarray | None, filter_name: str, blur_method: str, kernel_size: int, edge_method: str, low: int, high: int, brightness: int, contrast: float, saturation: float, hue_shift: int, channel: str) -> tuple[np.ndarray | None, dict[str, Any], str]: if image is None: raise gr.Error("Load or capture an image first.") params = { "method": blur_method if filter_name == "Blur" else edge_method, "kernel_size": kernel_size, "low": low, "high": high, "brightness": brightness, "contrast": contrast, "saturation": saturation, "hue_shift": hue_shift, "channel": channel, } result = apply_step(image, filter_name, params) definition = operation_to_definition(filter_name, params) code = make_code_snippet(filter_name, params) return result, definition, code
def preview_kernel(image: np.ndarray | None, kernel_text: str) -> tuple[np.ndarray | None, dict[str, Any], str]: if image is None: raise gr.Error("Load or capture an image first.") kernel = parse_kernel(kernel_text) definition = {"type": "kernel", "kernel": kernel} code = f"""import numpy as npfrom PIL import Imagefrom filters.builtin import custom_kernel
image = np.array(Image.open("input.png").convert("RGB"))kernel = {json.dumps(kernel)}result = custom_kernel(image, kernel=kernel)Image.fromarray(result).save("output.png")""" return apply_definition(image, definition), definition, code
def preview_pipeline(image: np.ndarray | None, pipeline_text: str) -> tuple[np.ndarray | None, dict[str, Any], str]: if image is None: raise gr.Error("Load or capture an image first.") definition = parse_pipeline(pipeline_text) code = f"""import numpy as npfrom PIL import Imagefrom filters.registry import apply_definition
image = np.array(Image.open("input.png").convert("RGB"))pipeline = {json.dumps(definition, indent=2)}result = apply_definition(image, pipeline)Image.fromarray(result).save("output.png")""" return apply_definition(image, definition), definition, code
def save_current_filter(name: str | None, definition: dict[str, Any] | None) -> tuple[str, gr.Dropdown]: if not name or not name.strip(): raise gr.Error("Enter a filter name before saving.") if not definition: raise gr.Error("Preview a built-in, kernel, or pipeline filter before saving.") saved = save_filter(name, definition) return f"Saved filter '{saved['name']}'.", gr.Dropdown(choices=names(False), value=saved["name"])
def load_saved_filter(image: np.ndarray | None, name: str | None) -> tuple[np.ndarray | None, dict[str, Any], str]: if not name: raise gr.Error("Select a saved filter from the dropdown to load.") if image is None: raise gr.Error("Load or capture an image first.") try: definition = load_definition(name) except Exception as exc: raise gr.Error(str(exc)) return apply_definition(image, definition), definition, json.dumps(definition, indent=2)
def delete_saved(name: str | None) -> tuple[str, gr.Dropdown]: if not name: raise gr.Error("Select a saved filter from the dropdown to delete.") delete_filter(name) return f"Deleted '{name}'.", gr.Dropdown(choices=names(False), value=None)
def analyze(image: np.ndarray | None, percent: int, x: int, y: int): if image is None: raise gr.Error("Load or capture an image first.") high_rgb, low_rgb, high_gray, low_gray = low_resolution_pair(image, percent) return high_rgb, low_rgb, high_gray, low_gray, pixel_preview(high_rgb, x, y), pixel_preview(low_rgb, x, y), histogram_figure(high_rgb, low_rgb), {"high_rgb": stats(high_rgb), "low_rgb": stats(low_rgb), "high_gray": stats(high_gray), "low_gray": stats(low_gray)}
def transform(image: np.ndarray | None, op: str, tx: int, ty: int, border: str, angle: float, scale: float, cx: float, cy: float, expand: bool, sx: float, sy: float, interp: str, flip: str): if image is None: raise gr.Error("Load or capture an image first.") if op == "Translation": return translate(image, tx, ty, border) if op == "Rotation": return rotate(image, angle, scale, cx, cy, expand) if op == "Scaling": return scale_image(image, sx, sy, interp) return reflect(image, flip)
def morph(image: np.ndarray | None, operation: str, threshold_method: str, threshold: int, shape: str, size: int, iterations: int): if image is None: raise gr.Error("Load or capture an image first.") result, kernel = apply_morphology(image, operation, shape, size, iterations, threshold_method, threshold) return result, kernel.tolist()
def run_style(image: np.ndarray | None, style_upload: np.ndarray | None, style_path: str | None, max_size: int): if image is None: raise gr.Error("Load or capture a content image first.") if style_upload is None and not style_path: raise gr.Error("Upload a style image or choose a sample style.") style = style_upload if style_upload is not None else np.asarray(Image.open(style_path).convert("RGB")) result, seconds, message = stylize(image, style, max_size) return result, f"{message} Inference time: {seconds:.2f}s"
def run_face(image: np.ndarray | None, filter_name: str): if image is None: raise gr.Error("Load or capture an image first.") return apply_face_filter(image, filter_name)
def preview_ar_custom(image: np.ndarray | None, custom_json: str | None) -> tuple[np.ndarray | None, str]: if image is None: raise gr.Error("Load or capture an image first.") if not custom_json or not custom_json.strip(): raise gr.Error("Enter a custom AR filter JSON definition.") try: definition = json.loads(custom_json) except Exception as exc: raise gr.Error(f"Invalid AR filter JSON: {exc}") return apply_face_filter(image, filter_name="Custom", custom_def=definition)
def save_custom_ar_filter(name: str | None, custom_json: str | None) -> tuple[str, gr.Dropdown, gr.Dropdown]: if not name or not name.strip(): raise gr.Error("Enter an AR filter name before saving.") if not custom_json or not custom_json.strip(): raise gr.Error("Enter a custom AR filter JSON definition.") try: definition = json.loads(custom_json) except Exception as exc: raise gr.Error(f"Invalid AR filter JSON: {exc}") saved = save_ar_filter(name, definition) return f"Saved AR filter '{saved['name']}'.", gr.Dropdown(choices=ar_filter_names(True), value=saved["name"]), gr.Dropdown(choices=ar_filter_names(False), value=saved["name"])
def load_saved_ar_filter(image: np.ndarray | None, name: str | None) -> tuple[np.ndarray | None, str, str]: if not name: raise gr.Error("Select a saved AR filter from the dropdown to load.") if image is None: raise gr.Error("Load or capture an image first.") try: definition = load_ar_definition(name) except Exception as exc: raise gr.Error(str(exc)) result, msg = apply_face_filter(image, filter_name=name) return result, json.dumps(definition, indent=2), msg
def delete_saved_ar_filter(name: str | None) -> tuple[str, gr.Dropdown, gr.Dropdown]: if not name: raise gr.Error("Select a saved AR filter from the dropdown to delete.") delete_ar_filter(name) return f"Deleted AR filter '{name}'.", gr.Dropdown(choices=ar_filter_names(True), value="Glasses"), gr.Dropdown(choices=ar_filter_names(False), value=None)
def run_batch(files: list[str] | None, directory: str, filter_name: str, progress=gr.Progress()): if not filter_name: raise gr.Error("Choose a built-in or saved filter.") return process_dataset(files, directory or None, filter_name, progress)
custom_theme = gr.themes.Soft( primary_hue="indigo", secondary_hue="cyan", neutral_hue="slate", font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],)
with gr.Blocks(theme=custom_theme, title="CV Lab Camera Studio") as demo: current_image = gr.State() current_definition = gr.State()
gr.Markdown( """# 📸 CV Lab Camera Studio### Comprehensive Computer Vision & AR Laboratory for Photo Editors, Scientists & Developers*Capture with your webcam or upload an image to use seamlessly across all processing modules below.*""" ) with gr.Row(): global_input = gr.Image(label="Global Image Input", sources=["webcam", "upload"], type="numpy") global_preview = gr.Image(label="Active Image Canvas", type="numpy") status = gr.Markdown("✨ Load or capture an image above to start processing across all tabs.") global_input.change(set_global_image, global_input, [current_image, global_preview, status])
with gr.Tabs(): with gr.Tab("🎨 Photo Filters & Pipelines"): gr.Markdown("Apply built-in visual filters, adjust parameters, or create reusable custom matrix kernels and multi-step JSON pipelines.") with gr.Row(): before = gr.Image(value=None, label="Original Input", type="numpy") after = gr.Image(label="Filtered Result", type="numpy") current_image.change(lambda x: x, current_image, before)
with gr.Group(): filter_name = gr.Dropdown(list(BUILTIN_FILTERS.keys())[:-1], value="Sepia", label="Built-in Filter Selection") with gr.Row(): blur_method = gr.Radio(["Gaussian", "Median", "Bilateral"], value="Gaussian", label="Blur Method", info="Smoothing algorithm") kernel_size = gr.Slider(1, 31, value=7, step=2, label="Kernel Size", info="Must be an odd integer") edge_method = gr.Radio(["Canny", "Sobel"], value="Canny", label="Edge Detection Method") with gr.Row(): low = gr.Slider(0, 255, value=80, step=1, label="Canny Low Threshold", info="Lower hysteresis bound") high = gr.Slider(0, 255, value=160, step=1, label="Canny High Threshold", info="Upper hysteresis bound") brightness = gr.Slider(-100, 100, value=0, step=1, label="Brightness Shift") contrast = gr.Slider(0.1, 3.0, value=1.0, step=0.05, label="Contrast Multiplier") with gr.Row(): saturation = gr.Slider(0, 3, value=1, step=0.05, label="Saturation Factor") hue_shift = gr.Slider(-90, 90, value=0, step=1, label="Hue Shift Degrees") channel = gr.Radio(["R", "G", "B"], value="R", label="Channel Isolation") apply_builtin = gr.Button("⚡ Apply Built-in Filter", variant="primary")
with gr.Accordion("⚙️ Custom Kernel & Pipeline JSON Editor", open=False): with gr.Row(): with gr.Column(): kernel_text = gr.Textbox(value="[[0,-1,0],[-1,5,-1],[0,-1,0]]", lines=4, label="Custom 3x3 Matrix Kernel JSON") apply_kernel = gr.Button("Preview Custom Kernel") with gr.Column(): pipeline_text = gr.Textbox(value='[{"operation":"Grayscale","params":{}},{"operation":"Sharpen","params":{"amount":1.4}}]', lines=5, label="Multi-Step Pipeline JSON") apply_pipeline = gr.Button("Preview Pipeline")
with gr.Row(): save_name = gr.Textbox(label="Filter Name to Save") save_btn = gr.Button("💾 Save Current Filter") saved_dropdown = gr.Dropdown(choices=names(False), label="Load Saved Filter Preset") load_btn = gr.Button("📂 Load Filter") delete_btn = gr.Button("🗑️ Delete Filter", variant="stop")
filter_msg = gr.Markdown() with gr.Accordion("📋 Filter JSON Definition & Python Code Snippet", open=False): filter_json = gr.JSON(label="Current Filter Definition JSON") dev_code = gr.Code(label="Python Code Snippet for Developers", language="python") download_filter = gr.DownloadButton("📥 Download Filtered Result", value=None)
apply_builtin.click(run_builtin, [current_image, filter_name, blur_method, kernel_size, edge_method, low, high, brightness, contrast, saturation, hue_shift, channel], [after, current_definition, dev_code]).then(export_image, after, download_filter).then(lambda d: d, current_definition, filter_json) apply_kernel.click(preview_kernel, [current_image, kernel_text], [after, current_definition, dev_code]).then(export_image, after, download_filter).then(lambda d: d, current_definition, filter_json) apply_pipeline.click(preview_pipeline, [current_image, pipeline_text], [after, current_definition, dev_code]).then(export_image, after, download_filter).then(lambda d: d, current_definition, filter_json) save_btn.click(save_current_filter, [save_name, current_definition], [filter_msg, saved_dropdown]) load_btn.click(load_saved_filter, [current_image, saved_dropdown], [after, current_definition, pipeline_text]).then(export_image, after, download_filter).then(lambda d: d, current_definition, filter_json) delete_btn.click(delete_saved, saved_dropdown, [filter_msg, saved_dropdown])
with gr.Tab("🔬 Resolution & Color Analysis"): gr.Markdown("Compare high/low resolution RGB and grayscale representations, analyze pixel crops, and inspect intensity histograms.") with gr.Row(): percent = gr.Slider(5, 100, value=25, step=5, label="Low Resolution Percent", info="Downsample scale percentage") px = gr.Number(value=0, precision=0, label="Pixel Crop X Coordinate") py = gr.Number(value=0, precision=0, label="Pixel Crop Y Coordinate") analyze_btn = gr.Button("🔬 Run Analysis", variant="primary") with gr.Row(): high_rgb = gr.Image(label="High RGB Original", type="numpy") low_rgb = gr.Image(label="Low RGB Upsampled", type="numpy") with gr.Row(): high_gray = gr.Image(label="High Grayscale", type="numpy") low_gray = gr.Image(label="Low Grayscale", type="numpy") with gr.Row(): pix_high = gr.Dataframe(label="High RGB Pixel Values", row_count=5) pix_low = gr.Dataframe(label="Low RGB Pixel Values", row_count=5) hist = gr.Plot(label="Channel Intensity Histograms") stat_json = gr.JSON(label="Detailed Image Statistics") analyze_btn.click(analyze, [current_image, percent, px, py], [high_rgb, low_rgb, high_gray, low_gray, pix_high, pix_low, hist, stat_json])
with gr.Tab("📐 Geometric Transformations"): gr.Markdown("Apply affine geometric transformations including translation, rotation, scaling, and reflection while inspecting matrix parameters.") op = gr.Radio(["Translation", "Rotation", "Scaling", "Reflection"], value="Rotation", label="Transformation Operation") with gr.Group(): with gr.Row(): tx = gr.Slider(-300, 300, value=30, step=1, label="Translation X Offset (px)") ty = gr.Slider(-300, 300, value=30, step=1, label="Translation Y Offset (px)") border = gr.Radio(["constant", "reflect", "replicate"], value="constant", label="Border Extrapolation") with gr.Row(): angle = gr.Slider(0, 360, value=30, step=1, label="Rotation Angle (deg)") rot_scale = gr.Slider(0.1, 3, value=1, step=0.05, label="Rotation Scale Factor") cx = gr.Slider(0, 1, value=0.5, step=0.05, label="Center X Ratio") cy = gr.Slider(0, 1, value=0.5, step=0.05, label="Center Y Ratio") expand = gr.Checkbox(value=True, label="Expand Canvas Bounds") with gr.Row(): sx = gr.Slider(0.1, 4, value=1.2, step=0.05, label="Scale X Factor") sy = gr.Slider(0.1, 4, value=1.2, step=0.05, label="Scale Y Factor") interp = gr.Radio(["nearest", "linear", "cubic", "area"], value="linear", label="Interpolation Mode") flip = gr.Radio(["horizontal", "vertical", "both"], value="horizontal", label="Reflection Axis") trans_btn = gr.Button("📐 Apply Transformation", variant="primary") with gr.Row(): trans_before = gr.Image(label="Original Canvas", type="numpy") trans_after = gr.Image(label="Transformed Canvas", type="numpy") matrix = gr.JSON(label="Affine Transformation Matrix 2x3") trans_dl = gr.DownloadButton("📥 Download Transformed Result", value=None) current_image.change(lambda x: x, current_image, trans_before) trans_btn.click(transform, [current_image, op, tx, ty, border, angle, rot_scale, cx, cy, expand, sx, sy, interp, flip], [trans_after, matrix]).then(export_image, trans_after, trans_dl)
with gr.Tab("🧪 Morphological Operations"): gr.Markdown("Apply thresholding and mathematical morphology operations with custom structuring element kernels.") with gr.Group(): with gr.Row(): morph_op = gr.Dropdown(["Erosion", "Dilation", "Opening", "Closing", "Gradient", "Top-Hat", "Black-Hat"], value="Opening", label="Morphological Operation") thresh_method = gr.Radio(["Otsu", "Manual"], value="Otsu", label="Binarization Threshold Method") thresh_value = gr.Slider(0, 255, value=128, step=1, label="Manual Threshold Value") with gr.Row(): shape = gr.Radio(["rect", "ellipse", "cross"], value="rect", label="Kernel Structuring Shape") morph_size = gr.Slider(1, 31, value=5, step=2, label="Kernel Size", info="Must be an odd integer") iterations = gr.Slider(1, 10, value=1, step=1, label="Iteration Count") morph_btn = gr.Button("🧪 Apply Morphology", variant="primary") with gr.Row(): morph_before = gr.Image(label="Original Input", type="numpy") morph_after = gr.Image(label="Morphology Output", type="numpy") kernel_view = gr.JSON(label="Structuring Element Kernel Matrix") morph_dl = gr.DownloadButton("📥 Download Result", value=None) current_image.change(lambda x: x, current_image, morph_before) morph_btn.click(morph, [current_image, morph_op, thresh_method, thresh_value, shape, morph_size, iterations], [morph_after, kernel_view]).then(export_image, morph_after, morph_dl)
with gr.Tab("🌌 Neural Style Transfer"): gr.Markdown("Transfer artistic textures from a style reference image to your content image using the TensorFlow Hub Magenta deep neural model.") with gr.Row(): style_upload = gr.Image(label="Custom Style Image Upload", type="numpy") style_choice = gr.Dropdown(choices=STYLE_SAMPLES, label="Synthetic Sample Style Presets") max_size = gr.Slider(128, 1024, value=512, step=64, label="Inference Resolution Max Size (px)", info="Higher resolution takes longer") style_btn = gr.Button("🌌 Run Style Transfer", variant="primary") style_out = gr.Image(label="Stylized Result", type="numpy") style_msg = gr.Markdown() style_dl = gr.DownloadButton("📥 Download Stylized Result", value=None) style_btn.click(run_style, [current_image, style_upload, style_choice, max_size], [style_out, style_msg]).then(export_image, style_out, style_dl)
with gr.Tab("🎭 Face AR Filters"): gr.Markdown("Apply landmark-anchored AR face overlays or design, preview, and save custom JSON AR filters.") with gr.Row(): ar_choice = gr.Dropdown(choices=ar_filter_names(True), value="Glasses", label="AR Filter Presets") ar_btn = gr.Button("🎭 Apply AR Filter", variant="primary") with gr.Row(): ar_before = gr.Image(label="Original Face Input", type="numpy") ar_out = gr.Image(label="AR Overlay Result", type="numpy") current_image.change(lambda x: x, current_image, ar_before)
with gr.Accordion("🎨 Custom AR Filter Designer & JSON Editor", open=False): ar_custom_text = gr.Textbox(value=DEFAULT_CUSTOM_AR_JSON, lines=8, label="Custom AR Filter JSON Definition") ar_preview_btn = gr.Button("👁️ Preview Custom AR Filter") with gr.Row(): ar_save_name = gr.Textbox(label="AR Filter Name to Save") ar_save_btn = gr.Button("💾 Save Custom AR Filter") ar_saved_dropdown = gr.Dropdown(choices=ar_filter_names(False), label="Load Saved AR Preset") ar_load_btn = gr.Button("📂 Load AR Filter") ar_delete_btn = gr.Button("🗑️ Delete AR Filter", variant="stop")
ar_msg = gr.Markdown() ar_dl = gr.DownloadButton("📥 Download AR Result", value=None)
ar_btn.click(run_face, [current_image, ar_choice], [ar_out, ar_msg]).then(export_image, ar_out, ar_dl) ar_preview_btn.click(preview_ar_custom, [current_image, ar_custom_text], [ar_out, ar_msg]).then(export_image, ar_out, ar_dl) ar_save_btn.click(save_custom_ar_filter, [ar_save_name, ar_custom_text], [ar_msg, ar_choice, ar_saved_dropdown]) ar_load_btn.click(load_saved_ar_filter, [current_image, ar_saved_dropdown], [ar_out, ar_custom_text, ar_msg]).then(export_image, ar_out, ar_dl) ar_delete_btn.click(delete_saved_ar_filter, ar_saved_dropdown, [ar_msg, ar_choice, ar_saved_dropdown])
with gr.Tab("📦 Batch Dataset Processing"): gr.Markdown("Apply built-in or custom filter pipelines to multiple images, folders, or zip dataset archives with a reproducible manifest.") batch_files = gr.File(label="Upload Images or Zip Archive", file_count="multiple", type="filepath") batch_dir = gr.Textbox(label="Optional Local Dataset Directory Path") batch_filter = gr.Dropdown(choices=names(True), value="Grayscale", label="Filter / Pipeline Selection") refresh_filters = gr.Button("🔄 Refresh Filter List") batch_btn = gr.Button("🚀 Process Batch Dataset", variant="primary") batch_zip = gr.File(label="Processed Output Zip + manifest.json") refresh_filters.click(lambda: gr.Dropdown(choices=names(True)), None, batch_filter) batch_btn.click(run_batch, [batch_files, batch_dir, batch_filter], batch_zip)
with gr.Tab("📖 Guide & Documentation"): gr.Markdown( """## Persona & Feature Guide
### 🎨 Photo Editors- Use **Photo Filters & Pipelines** for instant visual edits like Sepia, Vignette, Emboss, Cartoonify, or Channel Isolation.- Experiment with **Neural Style Transfer** to stylize portraits or landscapes with synthetic or custom reference artwork.- Have fun with **Face AR Filters** for accessories (Glasses, Visors, Crown, Pirate Eyepatch, Dog Ears).
### 🔬 Scientists & Researchers- Use **Resolution & Color Analysis** to downsample images and evaluate RGB vs Grayscale degradation, intensity histograms, and pixel crop tables.- Perform reproducible **Morphological Operations** (Opening, Closing, Top-Hat, Black-Hat) with explicit structuring element kernels.- Process large experiment datasets with **Batch Dataset Processing** to export processed images alongside `manifest.json`.
### 💻 Developers- Use the **Python SDK** (`developer_api.py`) or **CLI** (`cli.py`) for command line processing.- Build multi-step JSON filter pipelines or custom AR landmark overlays in the Web UI, save them to disk, and export auto-generated Python code snippets.""" )
if __name__ == "__main__": demo.launch(share=False)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Batch dataset processing and reproducibility manifest export."""
from __future__ import annotations
import jsonimport shutilimport tempfileimport zipfilefrom pathlib import Pathfrom typing import Any, Iterable
import cv2import numpy as npfrom PIL import Image
from cv_ops.analysis import statsfrom filters.registry import apply_definition, load_definition
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
def _iter_input_files(files: list[str] | None, directory: str | None, workdir: Path) -> Iterable[Path]: if directory: root = Path(directory).expanduser() if root.exists(): yield from (p for p in root.rglob("*") if p.suffix.lower() in IMAGE_SUFFIXES) for file in files or []: path = Path(file) if path.suffix.lower() == ".zip": with zipfile.ZipFile(path) as zf: zf.extractall(workdir / path.stem) yield from (p for p in (workdir / path.stem).rglob("*") if p.suffix.lower() in IMAGE_SUFFIXES) elif path.suffix.lower() in IMAGE_SUFFIXES: yield path
def process_dataset(files: list[str] | None, directory: str | None, filter_name: str, progress: Any = None) -> str: definition = load_definition(filter_name) temp_root = Path(tempfile.mkdtemp(prefix="cv_lab_batch_")) out_dir = temp_root / "processed" out_dir.mkdir() manifest: list[dict[str, Any]] = [] inputs = list(_iter_input_files(files, directory, temp_root)) total = max(1, len(inputs)) for idx, path in enumerate(inputs): if progress: progress((idx + 1) / total, desc=f"Processing {path.name}") record: dict[str, Any] = {"filename": path.name, "filter": filter_name} try: img = np.array(Image.open(path).convert("RGB")) result = apply_definition(img, definition) out_path = out_dir / f"{path.stem}_processed.png" cv2.imwrite(str(out_path), cv2.cvtColor(result, cv2.COLOR_RGB2BGR)) record.update({"status": "ok", "output": out_path.name, "stats": stats(result)}) except Exception as exc: record.update({"status": "error", "error": str(exc)}) manifest.append(record) (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") archive = shutil.make_archive(str(temp_root / "cv_lab_processed"), "zip", out_dir) return archive1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Command Line Interface (CLI) for CV Lab Camera operations."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
from developer_api import load_image, process_image, save_imagefrom batch.dataset_processor import process_dataset
def main(): parser = argparse.ArgumentParser(description="CV Lab Camera Command Line Interface for developers.") subparsers = parser.add_subparsers(dest="command", help="Sub-commands")
# Filter subcommand filter_parser = subparsers.add_parser("filter", help="Apply built-in or saved image filter") filter_parser.add_argument("-i", "--input", required=True, help="Input image file path") filter_parser.add_argument("-f", "--filter", default="Sepia", help="Filter name (e.g. Sepia, Grayscale, Blur)") filter_parser.add_argument("-p", "--params", help="JSON params string") filter_parser.add_argument("-o", "--output", required=True, help="Output image file path")
# Transform subcommand trans_parser = subparsers.add_parser("transform", help="Apply geometric transformation") trans_parser.add_argument("-i", "--input", required=True, help="Input image file path") trans_parser.add_argument("--op", default="Rotation", choices=["Translation", "Rotation", "Scaling", "Reflection"], help="Transformation type") trans_parser.add_argument("--angle", type=float, default=30.0, help="Rotation angle in degrees") trans_parser.add_argument("--tx", type=int, default=30, help="X translation offset") trans_parser.add_argument("--ty", type=int, default=30, help="Y translation offset") trans_parser.add_argument("-o", "--output", required=True, help="Output image file path")
# Morphology subcommand morph_parser = subparsers.add_parser("morph", help="Apply morphological operations") morph_parser.add_argument("-i", "--input", required=True, help="Input image file path") morph_parser.add_argument("--op", default="Opening", help="Morphology operation (e.g. Opening, Erosion, Dilation)") morph_parser.add_argument("--size", type=int, default=5, help="Kernel size") morph_parser.add_argument("-o", "--output", required=True, help="Output image file path")
# AR subcommand ar_parser = subparsers.add_parser("ar", help="Apply face AR filter") ar_parser.add_argument("-i", "--input", required=True, help="Input face image file path") ar_parser.add_argument("-f", "--filter", default="Glasses", help="AR filter name (e.g. Glasses, Cyberpunk Visor, Crown & Star Sparkles)") ar_parser.add_argument("-o", "--output", required=True, help="Output image file path")
# Style subcommand style_parser = subparsers.add_parser("style", help="Apply neural style transfer") style_parser.add_argument("-i", "--input", required=True, help="Content image file path") style_parser.add_argument("-s", "--style-image", required=True, help="Style image file path") style_parser.add_argument("--max-size", type=int, default=512, help="Output max image resolution") style_parser.add_argument("-o", "--output", required=True, help="Output image file path")
# Batch subcommand batch_parser = subparsers.add_parser("batch", help="Process image directory or list") batch_parser.add_argument("--files", nargs="*", help="List of input image or zip files") batch_parser.add_argument("--dir", help="Input directory") batch_parser.add_argument("-f", "--filter", default="Grayscale", help="Filter or pipeline name") batch_parser.add_argument("-o", "--output-zip", default="processed.zip", help="Output zip file path")
args = parser.parse_args()
if not args.command: parser.print_help() sys.exit(1)
if args.command == "filter": params = json.loads(args.params) if args.params else {} _, meta = process_image(args.input, "filter", operation_name=args.filter, params=params, output_path=args.output) print(f"Applied filter '{args.filter}' -> Saved to {args.output}")
elif args.command == "transform": params = {"angle": args.angle, "tx": args.tx, "ty": args.ty} _, meta = process_image(args.input, "transform", operation_name=args.op, params=params, output_path=args.output) print(f"Applied transform '{args.op}' -> Saved to {args.output}")
elif args.command == "morph": params = {"size": args.size} _, meta = process_image(args.input, "morphology", operation_name=args.op, params=params, output_path=args.output) print(f"Applied morphology '{args.op}' -> Saved to {args.output}")
elif args.command == "ar": _, meta = process_image(args.input, "ar", operation_name=args.filter, output_path=args.output) print(f"Applied AR filter '{args.filter}' ({meta.get('status')}) -> Saved to {args.output}")
elif args.command == "style": params = {"style_image": args.style_image, "max_size": args.max_size} _, meta = process_image(args.input, "style", params=params, output_path=args.output) print(f"Applied neural style transfer -> Saved to {args.output}")
elif args.command == "batch": zip_path = process_dataset(args.files, args.dir, args.filter) Path(zip_path).rename(args.output_zip) print(f"Batch dataset processed with '{args.filter}' -> Saved archive to {args.output_zip}")
if __name__ == "__main__": main()123456import sysfrom pathlib import Path
root = Path(__file__).resolve().parentif str(root) not in sys.path: sys.path.insert(0, str(root))1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Resolution, color-space, statistics, and histogram helpers."""
from __future__ import annotations
import matplotlib.pyplot as pltimport numpy as npimport cv2
from filters.builtin import ensure_rgb
def low_resolution_pair(image: np.ndarray, percent: int = 25) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: img = ensure_rgb(image) h, w = img.shape[:2] small = cv2.resize(img, (max(1, w * percent // 100), max(1, h * percent // 100)), interpolation=cv2.INTER_AREA) low_rgb = cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST) high_gray = cv2.cvtColor(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB) low_gray = cv2.cvtColor(cv2.cvtColor(low_rgb, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB) return img, low_rgb, high_gray, low_gray
def pixel_preview(image: np.ndarray, x: int = 0, y: int = 0, size: int = 6) -> list[list[str]]: img = ensure_rgb(image) y0, x0 = max(0, y), max(0, x) crop = img[y0 : y0 + size, x0 : x0 + size] return [[str(tuple(int(v) for v in px)) for px in row] for row in crop]
def stats(image: np.ndarray) -> dict[str, float | int | list[int]]: img = ensure_rgb(image) return {"shape": list(img.shape), "mean": float(img.mean()), "std": float(img.std()), "min": int(img.min()), "max": int(img.max())}
def histogram_figure(high_rgb: np.ndarray, low_rgb: np.ndarray): fig, axes = plt.subplots(1, 2, figsize=(10, 4), tight_layout=True) for ax, img, title in [(axes[0], high_rgb, "High resolution"), (axes[1], low_rgb, "Low resolution")]: for idx, color in enumerate(["red", "green", "blue"]): ax.hist(img[..., idx].ravel(), bins=64, range=(0, 255), color=color, alpha=0.35) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) ax.hist(gray.ravel(), bins=64, range=(0, 255), color="black", alpha=0.35) ax.set_title(title) ax.set_xlabel("Intensity") ax.set_ylabel("Pixels") return fig12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Morphological image operations."""
from __future__ import annotations
import cv2import numpy as np
from filters.builtin import ensure_rgb
SHAPES = {"rect": cv2.MORPH_RECT, "ellipse": cv2.MORPH_ELLIPSE, "cross": cv2.MORPH_CROSS}OPS = { "Erosion": cv2.MORPH_ERODE, "Dilation": cv2.MORPH_DILATE, "Opening": cv2.MORPH_OPEN, "Closing": cv2.MORPH_CLOSE, "Gradient": cv2.MORPH_GRADIENT, "Top-Hat": cv2.MORPH_TOPHAT, "Black-Hat": cv2.MORPH_BLACKHAT,}
def make_kernel(shape: str = "rect", size: int = 5) -> np.ndarray: size = max(1, int(size)) if size % 2 == 0: size += 1 return cv2.getStructuringElement(SHAPES.get(shape, cv2.MORPH_RECT), (size, size))
def threshold_image(image: np.ndarray, method: str = "Otsu", threshold: int = 128) -> np.ndarray: gray = cv2.cvtColor(ensure_rgb(image), cv2.COLOR_RGB2GRAY) if method == "Otsu": _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) else: _, binary = cv2.threshold(gray, int(threshold), 255, cv2.THRESH_BINARY) return binary
def apply_morphology(image: np.ndarray, operation: str = "Opening", shape: str = "rect", size: int = 5, iterations: int = 1, threshold_method: str = "Otsu", threshold: int = 128) -> tuple[np.ndarray, np.ndarray]: binary = threshold_image(image, threshold_method, threshold) kernel = make_kernel(shape, size) op = OPS.get(operation, cv2.MORPH_OPEN) if op == cv2.MORPH_ERODE: result = cv2.erode(binary, kernel, iterations=int(iterations)) elif op == cv2.MORPH_DILATE: result = cv2.dilate(binary, kernel, iterations=int(iterations)) else: result = cv2.morphologyEx(binary, op, kernel, iterations=int(iterations)) return cv2.cvtColor(result, cv2.COLOR_GRAY2RGB), kernel12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""2D geometric transformations implemented with OpenCV."""
from __future__ import annotations
import cv2import numpy as np
from filters.builtin import ensure_rgb
BORDER_MODES = {"constant": cv2.BORDER_CONSTANT, "reflect": cv2.BORDER_REFLECT, "replicate": cv2.BORDER_REPLICATE}INTERPOLATION = {"nearest": cv2.INTER_NEAREST, "linear": cv2.INTER_LINEAR, "cubic": cv2.INTER_CUBIC, "area": cv2.INTER_AREA}
def translate(image: np.ndarray, x: int = 20, y: int = 20, border: str = "constant") -> tuple[np.ndarray, list[list[float]]]: img = ensure_rgb(image) matrix = np.float32([[1, 0, x], [0, 1, y]]) out = cv2.warpAffine(img, matrix, (img.shape[1], img.shape[0]), borderMode=BORDER_MODES.get(border, cv2.BORDER_CONSTANT)) return out, matrix.tolist()
def rotate(image: np.ndarray, angle: float = 30, scale: float = 1.0, center_x: float = 0.5, center_y: float = 0.5, expand: bool = True) -> tuple[np.ndarray, list[list[float]]]: img = ensure_rgb(image) h, w = img.shape[:2] center = (w * center_x, h * center_y) matrix = cv2.getRotationMatrix2D(center, angle, scale) out_w, out_h = w, h if expand: cos, sin = abs(matrix[0, 0]), abs(matrix[0, 1]) out_w, out_h = int((h * sin) + (w * cos)), int((h * cos) + (w * sin)) matrix[0, 2] += out_w / 2 - center[0] matrix[1, 2] += out_h / 2 - center[1] return cv2.warpAffine(img, matrix, (out_w, out_h)), matrix.tolist()
def scale_image(image: np.ndarray, sx: float = 1.2, sy: float = 1.2, interpolation: str = "linear") -> tuple[np.ndarray, list[list[float]]]: img = ensure_rgb(image) out = cv2.resize(img, None, fx=sx, fy=sy, interpolation=INTERPOLATION.get(interpolation, cv2.INTER_LINEAR)) return out, [[sx, 0, 0], [0, sy, 0]]
def reflect(image: np.ndarray, mode: str = "horizontal") -> tuple[np.ndarray, list[list[float]]]: img = ensure_rgb(image) code = {"horizontal": 1, "vertical": 0, "both": -1}.get(mode, 1) matrix = {"horizontal": [[-1, 0, img.shape[1]], [0, 1, 0]], "vertical": [[1, 0, 0], [0, -1, img.shape[0]]], "both": [[-1, 0, img.shape[1]], [0, -1, img.shape[0]]]}.get(mode) return cv2.flip(img, code), matrix123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""High-level Python API / SDK for CV Lab developers."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
import numpy as npfrom PIL import Image
from batch.dataset_processor import process_datasetfrom cv_ops.analysis import histogram_figure, low_resolution_pair, pixel_preview, statsfrom cv_ops.morphology import apply_morphologyfrom cv_ops.transforms import reflect, rotate, scale_image, translatefrom filters.builtin import BUILTIN_FILTERS, ensure_rgbfrom filters.custom import parse_kernel, parse_pipelinefrom filters.registry import apply_definition, apply_step, load_definition, save_filterfrom models.face_filters import apply_face_filter, ar_filter_names, save_ar_filterfrom models.style_transfer import stylize
def load_image(source: str | Path | np.ndarray) -> np.ndarray: """Load an image from file path or return RGB numpy array.""" if isinstance(source, (str, Path)): img = Image.open(source).convert("RGB") return np.array(img, dtype=np.uint8) return ensure_rgb(source)
def save_image(image: np.ndarray, output_path: str | Path) -> str: """Save an RGB numpy image array to file.""" path = Path(output_path) path.parent.mkdir(parents=True, exist_ok=True) Image.fromarray(image).save(path) return str(path)
def generate_python_snippet(operation: str, params: dict[str, Any]) -> str: """Generate reproducible Python code snippet for developers.""" params_str = json.dumps(params, indent=2) return f"""import numpy as npfrom PIL import Imagefrom filters.registry import apply_step
# Load imageimage = np.array(Image.open("input.jpg").convert("RGB"))
# Apply filterparams = {params_str}result = apply_step(image, "{operation}", params)
# Save resultImage.fromarray(result).save("output.jpg")"""
def process_image( image_input: str | Path | np.ndarray, operation_type: str, operation_name: str = "Grayscale", params: dict[str, Any] | None = None, output_path: str | Path | None = None,) -> tuple[np.ndarray, dict[str, Any]]: """Programmatic API to process images with any CV Lab operation.""" img = load_image(image_input) params = params or {}
if operation_type == "filter": result = apply_step(img, operation_name, params) meta = {"operation": operation_name, "params": params} elif operation_type == "pipeline": definition = parse_pipeline(operation_name) if isinstance(operation_name, str) else operation_name result = apply_definition(img, definition) meta = {"definition": definition} elif operation_type == "transform": if operation_name == "Translation": result = translate(img, **params)[0] elif operation_name == "Rotation": result = rotate(img, **params)[0] elif operation_name == "Scaling": result = scale_image(img, **params)[0] else: result = reflect(img, **params)[0] meta = {"operation": operation_name, "params": params} elif operation_type == "morphology": result, kernel = apply_morphology(img, operation_name, **params) meta = {"operation": operation_name, "kernel_shape": kernel.shape} elif operation_type == "ar": result, msg = apply_face_filter(img, operation_name, custom_def=params.get("custom_def")) meta = {"status": msg} elif operation_type == "style": style_img = load_image(params["style_image"]) result, time_sec, msg = stylize(img, style_img, max_size=params.get("max_size", 512)) meta = {"time_seconds": time_sec, "message": msg} else: raise ValueError(f"Unknown operation type: {operation_type}")
if output_path: save_image(result, output_path)
return result, meta123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Built-in image filters for CV Lab Camera."""
from __future__ import annotations
from typing import Any, Callable
import cv2import numpy as np
FilterFn = Callable[..., np.ndarray]
def _odd(value: int) -> int: value = max(1, int(value)) return value if value % 2 else value + 1
def ensure_rgb(image: np.ndarray) -> np.ndarray: """Return an RGB uint8 image with three channels.""" if image is None: raise ValueError("Please provide an image first.") arr = np.asarray(image) if arr.ndim == 2: arr = cv2.cvtColor(arr, cv2.COLOR_GRAY2RGB) if arr.shape[-1] == 4: arr = arr[..., :3] return np.clip(arr, 0, 255).astype(np.uint8)
def grayscale(image: np.ndarray, **_: Any) -> np.ndarray: gray = cv2.cvtColor(ensure_rgb(image), cv2.COLOR_RGB2GRAY) return cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
def sepia(image: np.ndarray, **_: Any) -> np.ndarray: img = ensure_rgb(image).astype(np.float32) kernel = np.array([[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]) return np.clip(img @ kernel.T, 0, 255).astype(np.uint8)
def invert(image: np.ndarray, **_: Any) -> np.ndarray: return 255 - ensure_rgb(image)
def blur(image: np.ndarray, method: str = "Gaussian", kernel_size: int = 7, **_: Any) -> np.ndarray: img = ensure_rgb(image) k = _odd(kernel_size) if method == "Median": return cv2.medianBlur(img, k) if method == "Bilateral": return cv2.bilateralFilter(img, k, 75, 75) return cv2.GaussianBlur(img, (k, k), 0)
def sharpen(image: np.ndarray, amount: float = 1.0, **_: Any) -> np.ndarray: img = ensure_rgb(image) kernel = np.array([[0, -1, 0], [-1, 4 + amount, -1], [0, -1, 0]], dtype=np.float32) return np.clip(cv2.filter2D(img, -1, kernel), 0, 255).astype(np.uint8)
def edge_detection(image: np.ndarray, method: str = "Canny", low: int = 80, high: int = 160, **_: Any) -> np.ndarray: img = ensure_rgb(image) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) if method == "Sobel": sx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3) sy = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3) edges = cv2.convertScaleAbs(cv2.magnitude(sx, sy)) else: edges = cv2.Canny(gray, int(low), int(high)) return cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
def brightness_contrast(image: np.ndarray, brightness: int = 0, contrast: float = 1.0, **_: Any) -> np.ndarray: img = ensure_rgb(image).astype(np.float32) return np.clip(img * float(contrast) + int(brightness), 0, 255).astype(np.uint8)
def saturation_hsv(image: np.ndarray, saturation: float = 1.0, hue_shift: int = 0, **_: Any) -> np.ndarray: hsv = cv2.cvtColor(ensure_rgb(image), cv2.COLOR_RGB2HSV).astype(np.float32) hsv[..., 0] = (hsv[..., 0] + int(hue_shift)) % 180 hsv[..., 1] = np.clip(hsv[..., 1] * float(saturation), 0, 255) return cv2.cvtColor(hsv.astype(np.uint8), cv2.COLOR_HSV2RGB)
def emboss(image: np.ndarray, **_: Any) -> np.ndarray: kernel = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]], dtype=np.float32) return np.clip(cv2.filter2D(ensure_rgb(image), -1, kernel) + 128, 0, 255).astype(np.uint8)
def cartoonify(image: np.ndarray, **_: Any) -> np.ndarray: img = ensure_rgb(image) smooth = cv2.bilateralFilter(img, 9, 120, 120) edges = cv2.adaptiveThreshold(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) return cv2.bitwise_and(smooth, smooth, mask=edges)
def vignette(image: np.ndarray, strength: float = 0.65, **_: Any) -> np.ndarray: img = ensure_rgb(image).astype(np.float32) rows, cols = img.shape[:2] x = cv2.getGaussianKernel(cols, cols * float(strength)) y = cv2.getGaussianKernel(rows, rows * float(strength)) mask = (y @ x.T) mask = mask / mask.max() return np.clip(img * mask[..., None], 0, 255).astype(np.uint8)
def isolate_channel(image: np.ndarray, channel: str = "R", **_: Any) -> np.ndarray: img = ensure_rgb(image) out = np.zeros_like(img) idx = {"R": 0, "G": 1, "B": 2}.get(channel, 0) out[..., idx] = img[..., idx] return out
def custom_kernel(image: np.ndarray, kernel: list[list[float]] | np.ndarray, **_: Any) -> np.ndarray: arr = np.asarray(kernel, dtype=np.float32) if arr.ndim != 2 or arr.shape[0] != arr.shape[1]: raise ValueError("Kernel must be a square numeric matrix.") return np.clip(cv2.filter2D(ensure_rgb(image), -1, arr), 0, 255).astype(np.uint8)
BUILTIN_FILTERS: dict[str, FilterFn] = { "Grayscale": grayscale, "Sepia": sepia, "Invert": invert, "Blur": blur, "Sharpen": sharpen, "Edge Detection": edge_detection, "Brightness/Contrast": brightness_contrast, "Saturation/HSV Shift": saturation_hsv, "Emboss": emboss, "Cartoonify": cartoonify, "Vignette": vignette, "Channel Isolation": isolate_channel, "Custom Kernel": custom_kernel,}12345678910111213141516171819202122232425262728293031323334353637"""Custom kernel and JSON pipeline helpers."""
from __future__ import annotations
import jsonfrom typing import Any
import numpy as np
from filters.registry import apply_definition
def parse_kernel(text: str) -> list[list[float]]: try: kernel = json.loads(text) except json.JSONDecodeError as exc: raise ValueError("Kernel must be valid JSON, for example [[0,-1,0],[-1,5,-1],[0,-1,0]].") from exc arr = np.asarray(kernel, dtype=float) if arr.ndim != 2 or arr.shape[0] != arr.shape[1]: raise ValueError("Kernel must be a square matrix.") return arr.tolist()
def parse_pipeline(text: str) -> dict[str, Any]: try: payload = json.loads(text) except json.JSONDecodeError as exc: raise ValueError("Pipeline must be valid JSON.") from exc if isinstance(payload, list): payload = {"type": "pipeline", "steps": payload} if payload.get("type") != "pipeline" or not isinstance(payload.get("steps"), list): raise ValueError('Pipeline must look like {"type":"pipeline","steps":[...]} or a JSON step list.') return payload
def preview_definition(image: np.ndarray, definition: dict[str, Any]) -> np.ndarray: return apply_definition(image, definition)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Filter registry and saved-filter persistence."""
from __future__ import annotations
import jsonimport uuidfrom pathlib import Pathfrom typing import Any
import numpy as np
from filters.builtin import BUILTIN_FILTERSfrom cv_ops.morphology import apply_morphologyfrom cv_ops.transforms import reflect, rotate, scale_image, translate
ROOT = Path(__file__).resolve().parents[1]SAVE_DIR = ROOT / "saved_filters"REGISTRY_PATH = SAVE_DIR / "filters_registry.json"
def _ensure_store() -> None: SAVE_DIR.mkdir(exist_ok=True) if not REGISTRY_PATH.exists(): REGISTRY_PATH.write_text("{}", encoding="utf-8")
def load_registry() -> dict[str, dict[str, Any]]: _ensure_store() return json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
def save_filter(name: str, definition: dict[str, Any]) -> dict[str, Any]: if not name.strip(): raise ValueError("Filter name is required.") _ensure_store() registry = load_registry() filter_id = registry.get(name, {}).get("id", str(uuid.uuid4())) payload = {"id": filter_id, "name": name.strip(), **definition} path = SAVE_DIR / f"{filter_id}.json" path.write_text(json.dumps(payload, indent=2), encoding="utf-8") registry[name.strip()] = {"id": filter_id, "path": str(path.relative_to(ROOT)), "definition": payload} REGISTRY_PATH.write_text(json.dumps(registry, indent=2), encoding="utf-8") return payload
def delete_filter(name: str) -> None: registry = load_registry() item = registry.pop(name, None) if item: path = ROOT / item["path"] if path.exists(): path.unlink() REGISTRY_PATH.write_text(json.dumps(registry, indent=2), encoding="utf-8")
def names(include_builtin: bool = True) -> list[str]: saved = list(load_registry().keys()) return (list(BUILTIN_FILTERS.keys()) if include_builtin else []) + saved
def operation_to_definition(operation: str, params: dict[str, Any] | None = None) -> dict[str, Any]: return {"type": "pipeline", "steps": [{"operation": operation, "params": params or {}}]}
def apply_step(image: np.ndarray, operation: str, params: dict[str, Any] | None = None) -> np.ndarray: params = params or {} if operation in BUILTIN_FILTERS: return BUILTIN_FILTERS[operation](image, **params) if operation == "Translate": return translate(image, **params)[0] if operation == "Rotate": return rotate(image, **params)[0] if operation == "Scale": return scale_image(image, **params)[0] if operation == "Reflect": return reflect(image, **params)[0] if operation == "Morphology": return apply_morphology(image, **params)[0] raise ValueError(f"Unknown operation: {operation}")
def apply_definition(image: np.ndarray, definition: dict[str, Any]) -> np.ndarray: if definition.get("type") == "kernel": return BUILTIN_FILTERS["Custom Kernel"](image, kernel=definition["kernel"]) result = image for step in definition.get("steps", []): result = apply_step(result, step["operation"], step.get("params", {})) return result
def load_definition(name: str) -> dict[str, Any]: if name in BUILTIN_FILTERS: return operation_to_definition(name) item = load_registry().get(name) if not item: raise ValueError(f"Saved filter not found: {name}") return item["definition"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352"""Robust OpenCV based AR face filters and custom AR filter persistence."""
from __future__ import annotations
import jsonimport mathimport uuidfrom functools import lru_cachefrom pathlib import Pathfrom typing import Any
import cv2import numpy as np
from filters.builtin import ensure_rgb
ROOT = Path(__file__).resolve().parents[1]SAVE_AR_DIR = ROOT / "saved_ar_filters"REGISTRY_AR_PATH = SAVE_AR_DIR / "ar_filters_registry.json"
BUILTIN_AR_FILTERS = [ "Glasses", "Dog/Cat Ears + Nose", "Face Mask", "Sunglasses & Mustache", "Crown & Star Sparkles", "Pirate Eyepatch & Hat", "Cyberpunk Visor", "Party Hat & Horn",]
def _ensure_ar_store() -> None: SAVE_AR_DIR.mkdir(exist_ok=True) if not REGISTRY_AR_PATH.exists(): REGISTRY_AR_PATH.write_text("{}", encoding="utf-8")
def load_ar_registry() -> dict[str, dict[str, Any]]: _ensure_ar_store() try: return json.loads(REGISTRY_AR_PATH.read_text(encoding="utf-8")) except Exception: return {}
def save_ar_filter(name: str, definition: dict[str, Any]) -> dict[str, Any]: clean_name = (name or "").strip() if not clean_name: raise ValueError("AR Filter name is required.") _ensure_ar_store() registry = load_ar_registry() filter_id = registry.get(clean_name, {}).get("id", str(uuid.uuid4())) payload = {"id": filter_id, "name": clean_name, **definition} path = SAVE_AR_DIR / f"{filter_id}.json" path.write_text(json.dumps(payload, indent=2), encoding="utf-8") registry[clean_name] = {"id": filter_id, "path": str(path.relative_to(ROOT)), "definition": payload} REGISTRY_AR_PATH.write_text(json.dumps(registry, indent=2), encoding="utf-8") return payload
def delete_ar_filter(name: str | None) -> None: if not name: return registry = load_ar_registry() item = registry.pop(name, None) if item: path = ROOT / item["path"] if path.exists(): path.unlink() REGISTRY_AR_PATH.write_text(json.dumps(registry, indent=2), encoding="utf-8")
def ar_filter_names(include_builtin: bool = True) -> list[str]: saved = list(load_ar_registry().keys()) return (list(BUILTIN_AR_FILTERS) if include_builtin else []) + saved
def load_ar_definition(name: str | None) -> dict[str, Any]: if not name: raise ValueError("No AR filter selected.") if name in BUILTIN_AR_FILTERS: return {"name": name, "type": "builtin"} item = load_ar_registry().get(name) if not item: raise ValueError(f"Saved AR filter not found: {name}") return item.get("definition", {})
@lru_cache(maxsize=1)def _get_cascades(): face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml") return face_cascade, eye_cascade
def _detect_face_landmarks(img: np.ndarray) -> tuple[list[tuple[int, int, int, int, tuple[int, int], tuple[int, int]]], str]: gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) face_cascade, eye_cascade = _get_cascades()
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4, minSize=(30, 30)) if len(faces) == 0: alt_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt2.xml") faces = alt_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(30, 30))
if len(faces) == 0: return [], "No face detected in image."
results = [] for (x, y, w, h) in faces: face_roi = gray[y : y + h, x : x + w] eyes = eye_cascade.detectMultiScale(face_roi, scaleFactor=1.1, minNeighbors=3, minSize=(15, 15))
left_eye = (x + int(w * 0.3), y + int(h * 0.35)) right_eye = (x + int(w * 0.7), y + int(h * 0.35))
if len(eyes) >= 2: sorted_eyes = sorted(eyes, key=lambda e: e[0]) ex1, ey1, ew1, eh1 = sorted_eyes[0] ex2, ey2, ew2, eh2 = sorted_eyes[-1] left_eye = (x + ex1 + ew1 // 2, y + ey1 + eh1 // 2) right_eye = (x + ex2 + ew2 // 2, y + ey2 + eh2 // 2)
results.append((x, y, w, h, left_eye, right_eye))
return results, f"Detected {len(results)} face(s)."
def _blend_rgba(base: np.ndarray, overlay: np.ndarray, x: int, y: int) -> None: h, w = overlay.shape[:2] x0, y0 = max(0, x), max(0, y) x1, y1 = min(base.shape[1], x + w), min(base.shape[0], y + h) if x1 <= x0 or y1 <= y0: return crop = overlay[y0 - y : y1 - y, x0 - x : x1 - x] alpha = crop[..., 3:4].astype(float) / 255.0 base[y0:y1, x0:x1] = (crop[..., :3] * alpha + base[y0:y1, x0:x1] * (1 - alpha)).astype(np.uint8)
def _draw_element(img: np.ndarray, element: dict[str, Any], landmarks: dict[str, tuple[int, int]], fw: int, fh: int, dist: int, angle: float) -> None: if not isinstance(element, dict): return landmark_name = str(element.get("landmark", "eyes")) pos = landmarks.get(landmark_name, landmarks["eyes"]) dx = int(element.get("offset_x", 0) * fw) dy = int(element.get("offset_y", 0) * fh) center = (pos[0] + dx, pos[1] + dy)
shape = str(element.get("shape", "circle")).lower() raw_color = element.get("color", [255, 0, 0]) if not isinstance(raw_color, (list, tuple)) or len(raw_color) < 3: raw_color = [255, 0, 0] color = tuple(int(np.clip(c, 0, 255)) for c in raw_color[:3]) scale = max(0.05, float(element.get("scale", 1.0)))
if shape == "crown": cw, ch = max(10, int(fw * 0.8 * scale)), max(10, int(fh * 0.4 * scale)) pts = np.array([ [center[0] - cw // 2, center[1]], [center[0] - cw // 2, center[1] - ch], [center[0] - cw // 4, center[1] - ch // 2], [center[0], center[1] - ch], [center[0] + cw // 4, center[1] - ch // 2], [center[0] + cw // 2, center[1] - ch], [center[0] + cw // 2, center[1]], ], np.int32) cv2.fillPoly(img, [pts], color) cv2.polylines(img, [pts], True, (255, 255, 255), 2) cv2.circle(img, (center[0] - cw // 2, center[1] - ch), max(2, int(cw * 0.04)), (220, 30, 30), -1) cv2.circle(img, (center[0], center[1] - ch), max(2, int(cw * 0.05)), (30, 220, 30), -1) cv2.circle(img, (center[0] + cw // 2, center[1] - ch), max(2, int(cw * 0.04)), (220, 30, 30), -1)
elif shape in ("visor", "cyberpunk"): vw, vh = max(10, int(dist * 2.4 * scale)), max(6, int(dist * 0.5 * scale)) overlay = np.zeros((vh, vw, 4), dtype=np.uint8) cv2.rectangle(overlay, (0, 0), (vw - 1, vh - 1), (*color, 180), -1) cv2.rectangle(overlay, (0, 0), (vw - 1, vh - 1), (255, 255, 255, 255), 2) for i in range(10, vw, 20): cv2.line(overlay, (i, 0), (i, min(vh, 8)), (255, 255, 255, 220), 1) _blend_rgba(img, overlay, center[0] - vw // 2, center[1] - vh // 2)
elif shape == "mustache": mw, mh = max(10, int(fw * 0.5 * scale)), max(4, int(fh * 0.15 * scale)) cv2.ellipse(img, (center[0] - mw // 4, center[1]), (mw // 4, mh), 20, 0, 180, color, -1) cv2.ellipse(img, (center[0] + mw // 4, center[1]), (mw // 4, mh), -20, 0, 180, color, -1)
elif shape == "mask": mw, mh = max(10, int(fw * 0.9 * scale)), max(10, int(fh * 0.45 * scale)) overlay = np.zeros((mh, mw, 4), dtype=np.uint8) cv2.rectangle(overlay, (0, 0), (mw - 1, mh - 1), (*color, 220), -1) cv2.rectangle(overlay, (0, 0), (mw - 1, mh - 1), (255, 255, 255, 255), 2) _blend_rgba(img, overlay, center[0] - mw // 2, center[1] - mh // 2)
elif shape == "sparkles": sr = max(4, int(fw * 0.08 * scale)) for offset in [(-int(dist * 0.8), -int(fh * 0.05)), (int(dist * 0.8), -int(fh * 0.05)), (0, -int(fh * 0.15))]: sp = (center[0] + offset[0], center[1] + offset[1]) cv2.line(img, (sp[0] - sr, sp[1]), (sp[0] + sr, sp[1]), color, 2) cv2.line(img, (sp[0], sp[1] - sr), (sp[0], sp[1] + sr), color, 2)
elif shape == "text": txt = str(element.get("text", "AR")) font_scale = max(0.5, fw / 150.0 * scale) cv2.putText(img, txt, (center[0] - int(fw * 0.2), center[1]), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, 2, cv2.LINE_AA)
elif shape == "star": sr = max(6, int(fw * 0.12 * scale)) pts = [] for i in range(10): r = sr if i % 2 == 0 else sr // 2 a = i * math.pi / 5 - math.pi / 2 pts.append([int(center[0] + r * math.cos(a)), int(center[1] + r * math.sin(a))]) cv2.fillPoly(img, [np.array(pts, np.int32)], color)
elif shape == "heart": hr = max(6, int(fw * 0.1 * scale)) cv2.circle(img, (center[0] - hr // 2, center[1] - hr // 2), hr // 2, color, -1) cv2.circle(img, (center[0] + hr // 2, center[1] - hr // 2), hr // 2, color, -1) pts = np.array([[center[0] - hr, center[1] - hr // 4], [center[0] + hr, center[1] - hr // 4], [center[0], center[1] + hr]], np.int32) cv2.fillPoly(img, [pts], color)
elif shape == "rectangle": rw, rh = max(6, int(fw * 0.3 * scale)), max(6, int(fh * 0.2 * scale)) cv2.rectangle(img, (center[0] - rw // 2, center[1] - rh // 2), (center[0] + rw // 2, center[1] + rh // 2), color, -1)
else: r = max(4, int(fw * 0.15 * scale)) cv2.circle(img, center, r, color, -1)
def apply_face_filter(image: np.ndarray, filter_name: str = "Glasses", custom_def: dict[str, Any] | None = None) -> tuple[np.ndarray, str]: img = ensure_rgb(image).copy() h, w = img.shape[:2]
faces, status_msg = _detect_face_landmarks(img)
if not faces: fx, fy, fw, fh = w // 4, h // 4, w // 2, h // 2 left_eye = (w // 3, h // 3) right_eye = (2 * w // 3, h // 3) faces = [(fx, fy, fw, fh, left_eye, right_eye)] status_msg = "No face detected; filter centered on canvas." else: status_msg = f"AR face filter '{filter_name}' applied."
for (x, y, fw, fh, left_eye, right_eye) in faces: dist = max(20, int(np.linalg.norm(np.array(right_eye) - np.array(left_eye)))) angle = math.degrees(math.atan2(right_eye[1] - left_eye[1], right_eye[0] - left_eye[0]))
landmarks = { "head_top": (x + fw // 2, max(0, y - int(fh * 0.15))), "forehead": (x + fw // 2, y + int(fh * 0.12)), "eyes": ((left_eye[0] + right_eye[0]) // 2, (left_eye[1] + right_eye[1]) // 2), "left_eye": left_eye, "right_eye": right_eye, "nose": (x + fw // 2, y + int(fh * 0.55)), "mouth": (x + fw // 2, y + int(fh * 0.75)), "chin": (x + fw // 2, y + int(fh * 0.9)), }
definition = custom_def if not definition and filter_name not in BUILTIN_AR_FILTERS: try: definition = load_ar_definition(filter_name) except Exception: definition = None
if definition and "elements" in definition: for elem in definition["elements"]: _draw_element(img, elem, landmarks, fw, fh, dist, angle) continue
if filter_name == "Dog/Cat Ears + Nose": ear_w, ear_h = int(fw * 0.35), int(fh * 0.4) left_ear_pos = (x + int(fw * 0.05), max(0, y - int(fh * 0.3))) right_ear_pos = (x + int(fw * 0.6), max(0, y - int(fh * 0.3)))
cv2.ellipse(img, (left_ear_pos[0] + ear_w // 2, left_ear_pos[1] + ear_h // 2), (ear_w // 2, ear_h // 2), -15, 0, 360, (140, 80, 40), -1) cv2.ellipse(img, (right_ear_pos[0] + ear_w // 2, right_ear_pos[1] + ear_h // 2), (ear_w // 2, ear_h // 2), 15, 0, 360, (140, 80, 40), -1) cv2.ellipse(img, (left_ear_pos[0] + ear_w // 2, left_ear_pos[1] + ear_h // 2), (int(ear_w * 0.3), int(ear_h * 0.3)), -15, 0, 360, (230, 150, 170), -1) cv2.ellipse(img, (right_ear_pos[0] + ear_w // 2, right_ear_pos[1] + ear_h // 2), (int(ear_w * 0.3), int(ear_h * 0.3)), 15, 0, 360, (230, 150, 170), -1)
nose_pos = landmarks["nose"] cv2.ellipse(img, nose_pos, (int(fw * 0.08), int(fh * 0.05)), 0, 0, 360, (40, 30, 30), -1) cv2.line(img, (nose_pos[0] - 5, nose_pos[1]), (nose_pos[0] - int(fw * 0.3), nose_pos[1] - 5), (20, 20, 20), 2) cv2.line(img, (nose_pos[0] - 5, nose_pos[1] + 5), (nose_pos[0] - int(fw * 0.3), nose_pos[1] + 15), (20, 20, 20), 2) cv2.line(img, (nose_pos[0] + 5, nose_pos[1]), (nose_pos[0] + int(fw * 0.3), nose_pos[1] - 5), (20, 20, 20), 2) cv2.line(img, (nose_pos[0] + 5, nose_pos[1] + 5), (nose_pos[0] + int(fw * 0.3), nose_pos[1] + 15), (20, 20, 20), 2)
elif filter_name == "Face Mask": _draw_element(img, {"landmark": "mouth", "shape": "mask", "color": [70, 180, 220], "scale": 1.0}, landmarks, fw, fh, dist, angle)
elif filter_name == "Sunglasses & Mustache": gw, gh = int(dist * 2.3), int(dist * 0.7) overlay = np.zeros((gh, gw, 4), dtype=np.uint8) cv2.ellipse(overlay, (int(gw * 0.28), gh // 2), (gh // 2, int(gh * 0.45)), 0, 0, 360, (20, 20, 20, 240), -1) cv2.ellipse(overlay, (int(gw * 0.72), gh // 2), (gh // 2, int(gh * 0.45)), 0, 0, 360, (20, 20, 20, 240), -1) cv2.line(overlay, (int(gw * 0.28), int(gh * 0.2)), (int(gw * 0.72), int(gh * 0.2)), (220, 180, 50, 255), 3) _blend_rgba(img, overlay, landmarks["eyes"][0] - gw // 2, landmarks["eyes"][1] - gh // 2) _draw_element(img, {"landmark": "mouth", "shape": "mustache", "color": [30, 20, 20], "scale": 1.0, "offset_y": -0.05}, landmarks, fw, fh, dist, angle)
elif filter_name == "Crown & Star Sparkles": _draw_element(img, {"landmark": "forehead", "shape": "crown", "color": [255, 215, 0], "scale": 1.0, "offset_y": -0.15}, landmarks, fw, fh, dist, angle) _draw_element(img, {"landmark": "eyes", "shape": "sparkles", "color": [255, 240, 100], "scale": 1.0}, landmarks, fw, fh, dist, angle)
elif filter_name == "Pirate Eyepatch & Hat": hw, hh = int(fw * 1.1), int(fh * 0.5) hat_pts = np.array([ [landmarks["head_top"][0] - hw // 2, landmarks["head_top"][1]], [landmarks["head_top"][0], landmarks["head_top"][1] - hh], [landmarks["head_top"][0] + hw // 2, landmarks["head_top"][1]], ], np.int32) cv2.fillPoly(img, [hat_pts], (20, 20, 20)) cv2.polylines(img, [hat_pts], True, (200, 170, 40), 3)
ep = landmarks["left_eye"] cv2.circle(img, ep, int(dist * 0.35), (15, 15, 15), -1) cv2.circle(img, ep, int(dist * 0.35), (200, 200, 200), 2) cv2.line(img, (0, max(0, ep[1] - int(dist * 0.2))), (w, ep[1] + int(dist * 0.2)), (15, 15, 15), 2)
elif filter_name == "Cyberpunk Visor": _draw_element(img, {"landmark": "eyes", "shape": "visor", "color": [0, 240, 255], "scale": 1.1}, landmarks, fw, fh, dist, angle)
elif filter_name == "Party Hat & Horn": hw, hh = int(fw * 0.5), int(fh * 0.6) hat_pts = np.array([ [landmarks["head_top"][0] - hw // 2, landmarks["head_top"][1]], [landmarks["head_top"][0], landmarks["head_top"][1] - hh], [landmarks["head_top"][0] + hw // 2, landmarks["head_top"][1]], ], np.int32) cv2.fillPoly(img, [hat_pts], (240, 60, 120)) cv2.circle(img, (landmarks["head_top"][0], landmarks["head_top"][1] - hh), 8, (255, 230, 80), -1)
else: gw, gh = int(dist * 2.2), int(dist * 0.65) overlay = np.zeros((gh, gw, 4), dtype=np.uint8)
cv2.circle(overlay, (int(gw * 0.28), gh // 2), gh // 2 - 2, (30, 30, 30, 255), 4) cv2.circle(overlay, (int(gw * 0.28), gh // 2), gh // 2 - 5, (20, 50, 80, 140), -1)
cv2.circle(overlay, (int(gw * 0.72), gh // 2), gh // 2 - 2, (30, 30, 30, 255), 4) cv2.circle(overlay, (int(gw * 0.72), gh // 2), gh // 2 - 5, (20, 50, 80, 140), -1)
cv2.line(overlay, (int(gw * 0.45), gh // 2), (int(gw * 0.55), gh // 2), (30, 30, 30, 255), 4)
if abs(angle) > 1: matrix = cv2.getRotationMatrix2D((gw / 2, gh / 2), angle, 1) overlay = cv2.warpAffine(overlay, matrix, (gw, gh), borderMode=cv2.BORDER_TRANSPARENT)
_blend_rgba(img, overlay, landmarks["eyes"][0] - gw // 2, landmarks["eyes"][1] - gh // 2)
return img, status_msg1234567891011121314151617181920212223242526272829303132333435363738394041"""Lazy TensorFlow Hub arbitrary style transfer wrapper."""
from __future__ import annotations
import osimport timefrom functools import lru_cache
import cv2import numpy as np
os.environ.setdefault("TFHUB_MODEL_LOAD_FORMAT", "COMPRESSED")
@lru_cache(maxsize=1)def _load_model(): import tensorflow_hub as hub
return hub.load("https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2")
def _to_tensor(image: np.ndarray, max_size: int): import tensorflow as tf
img = np.asarray(image).astype(np.float32) / 255.0 h, w = img.shape[:2] scale = min(1.0, max_size / max(h, w)) if scale < 1: img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA) return tf.constant(img[None, ...])
def stylize(content: np.ndarray, style: np.ndarray, max_size: int = 512) -> tuple[np.ndarray, float, str]: try: start = time.perf_counter() model = _load_model() output = model(_to_tensor(content, max_size), _to_tensor(style, 256))[0] arr = np.clip(np.array(output[0]) * 255, 0, 255).astype(np.uint8) return arr, time.perf_counter() - start, "Style transfer complete." except Exception as exc: return np.asarray(content).astype(np.uint8), 0.0, f"Style transfer unavailable: {exc}"1234[pytest]pythonpath = .filterwarnings = ignore::DeprecationWarning12345678910gradio>=4.44,<6opencv-python>=4.9,<5numpy>=1.26,<3pillow>=10,<12matplotlib>=3.8,<4tensorflow>=2.15,<2.18tensorflow-hub>=0.16,<1mediapipe>=0.10,<1pytest>=8,<9setuptools<70123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210{ "tiger": { "id": "fa0c305e-44b6-459a-ae32-a1256dc2ecc2", "path": "saved_ar_filters\\fa0c305e-44b6-459a-ae32-a1256dc2ecc2.json", "definition": { "id": "fa0c305e-44b6-459a-ae32-a1256dc2ecc2", "name": "tiger", "filter": { "name": "Royal Tiger", "version": "2.0", "type": "face_mask", "tracking": { "mode": "face_mesh", "landmarks": 468, "smooth_factor": 0.85, "mirror": true }, "elements": [ { "landmark": "full_face", "shape": "tiger_fur", "color": [ 230, 120, 20 ], "scale": 1.12, "opacity": 0.92 }, { "landmark": "forehead", "shape": "tiger_stripes", "color": [ 20, 12, 8 ], "scale": 1.05, "opacity": 0.95, "pattern": "vertical" }, { "landmark": "left_temple", "shape": "tiger_stripes", "color": [ 15, 10, 5 ], "scale": 0.9, "rotation": -18 }, { "landmark": "right_temple", "shape": "tiger_stripes", "color": [ 15, 10, 5 ], "scale": 0.9, "rotation": 18 }, { "landmark": "left_cheek", "shape": "tiger_stripes", "color": [ 20, 12, 6 ], "scale": 0.95, "rotation": -25 }, { "landmark": "right_cheek", "shape": "tiger_stripes", "color": [ 20, 12, 6 ], "scale": 0.95, "rotation": 25 }, { "landmark": "forehead", "shape": "tiger_crown", "color": [ 255, 215, 0 ], "scale": 0.85, "offset_y": -0.18, "glow": true }, { "landmark": "eyes", "shape": "tiger_eyes", "color": [ 255, 180, 30 ], "scale": 1.08, "glow": true, "pupil": "vertical_slit" }, { "landmark": "eyes", "shape": "cyan_eye_outline", "color": [ 0, 255, 255 ], "scale": 1.02, "opacity": 0.7, "glow": true }, { "landmark": "nose", "shape": "tiger_nose", "color": [ 35, 18, 12 ], "scale": 1.0, "opacity": 1.0 }, { "landmark": "mouth", "shape": "tiger_muzzle", "color": [ 245, 220, 190 ], "scale": 1.05, "opacity": 0.9 }, { "landmark": "mouth", "shape": "tiger_mouth", "color": [ 25, 12, 10 ], "scale": 0.85, "offset_y": 0.02 }, { "landmark": "cheeks", "shape": "whisker_dots", "color": [ 30, 20, 15 ], "scale": 0.9, "opacity": 0.9 }, { "landmark": "left_cheek", "shape": "whiskers", "color": [ 255, 245, 225 ], "scale": 1.0, "rotation": -8 }, { "landmark": "right_cheek", "shape": "whiskers", "color": [ 255, 245, 225 ], "scale": 1.0, "rotation": 8 }, { "landmark": "ears", "shape": "tiger_ears", "color": [ 210, 100, 20 ], "scale": 1.15, "opacity": 0.95 } ], "effects": { "face_lighting": true, "fur_texture": true, "stripe_blending": 0.85, "eye_glow_intensity": 0.65, "motion_smoothing": 0.9 } } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204{ "id": "fa0c305e-44b6-459a-ae32-a1256dc2ecc2", "name": "tiger", "filter": { "name": "Royal Tiger", "version": "2.0", "type": "face_mask", "tracking": { "mode": "face_mesh", "landmarks": 468, "smooth_factor": 0.85, "mirror": true }, "elements": [ { "landmark": "full_face", "shape": "tiger_fur", "color": [ 230, 120, 20 ], "scale": 1.12, "opacity": 0.92 }, { "landmark": "forehead", "shape": "tiger_stripes", "color": [ 20, 12, 8 ], "scale": 1.05, "opacity": 0.95, "pattern": "vertical" }, { "landmark": "left_temple", "shape": "tiger_stripes", "color": [ 15, 10, 5 ], "scale": 0.9, "rotation": -18 }, { "landmark": "right_temple", "shape": "tiger_stripes", "color": [ 15, 10, 5 ], "scale": 0.9, "rotation": 18 }, { "landmark": "left_cheek", "shape": "tiger_stripes", "color": [ 20, 12, 6 ], "scale": 0.95, "rotation": -25 }, { "landmark": "right_cheek", "shape": "tiger_stripes", "color": [ 20, 12, 6 ], "scale": 0.95, "rotation": 25 }, { "landmark": "forehead", "shape": "tiger_crown", "color": [ 255, 215, 0 ], "scale": 0.85, "offset_y": -0.18, "glow": true }, { "landmark": "eyes", "shape": "tiger_eyes", "color": [ 255, 180, 30 ], "scale": 1.08, "glow": true, "pupil": "vertical_slit" }, { "landmark": "eyes", "shape": "cyan_eye_outline", "color": [ 0, 255, 255 ], "scale": 1.02, "opacity": 0.7, "glow": true }, { "landmark": "nose", "shape": "tiger_nose", "color": [ 35, 18, 12 ], "scale": 1.0, "opacity": 1.0 }, { "landmark": "mouth", "shape": "tiger_muzzle", "color": [ 245, 220, 190 ], "scale": 1.05, "opacity": 0.9 }, { "landmark": "mouth", "shape": "tiger_mouth", "color": [ 25, 12, 10 ], "scale": 0.85, "offset_y": 0.02 }, { "landmark": "cheeks", "shape": "whisker_dots", "color": [ 30, 20, 15 ], "scale": 0.9, "opacity": 0.9 }, { "landmark": "left_cheek", "shape": "whiskers", "color": [ 255, 245, 225 ], "scale": 1.0, "rotation": -8 }, { "landmark": "right_cheek", "shape": "whiskers", "color": [ 255, 245, 225 ], "scale": 1.0, "rotation": 8 }, { "landmark": "ears", "shape": "tiger_ears", "color": [ 210, 100, 20 ], "scale": 1.15, "opacity": 0.95 } ], "effects": { "face_lighting": true, "fur_texture": true, "stripe_blending": 0.85, "eye_glow_intensity": 0.65, "motion_smoothing": 0.9 } }}1{}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import numpy as np
from cv_ops.morphology import apply_morphologyfrom cv_ops.transforms import reflect, rotate, scale_image, translatefrom filters.builtin import BUILTIN_FILTERSfrom filters.registry import apply_definition
def sample_image(): img = np.zeros((20, 30, 3), dtype=np.uint8) img[5:15, 10:20] = [200, 100, 50] return img
def test_builtin_filter_shapes(): img = sample_image() for name in ["Grayscale", "Sepia", "Invert", "Blur", "Sharpen", "Edge Detection"]: out = BUILTIN_FILTERS[name](img) assert out.shape == img.shape assert out.dtype == np.uint8
def test_transforms_return_matrices(): img = sample_image() out, matrix = translate(img, 2, 3) assert out.shape == img.shape assert matrix == [[1.0, 0.0, 2.0], [0.0, 1.0, 3.0]] assert rotate(img, 15, expand=False)[0].shape == img.shape assert scale_image(img, 2, 2)[0].shape[:2] == (40, 60) assert reflect(img, "both")[0].shape == img.shape
def test_morphology_binary_output(): out, kernel = apply_morphology(sample_image(), "Opening", size=3) assert out.shape == sample_image().shape assert kernel.shape == (3, 3)
def test_pipeline_definition(): img = sample_image() definition = {"type": "pipeline", "steps": [{"operation": "Invert", "params": {}}, {"operation": "Grayscale", "params": {}}]} out = apply_definition(img, definition) assert out.shape == img.shape
def test_export_image(): from os.path import exists from app import export_image
assert export_image(None) is None
img = sample_image() filepath = export_image(img) assert filepath is not None assert isinstance(filepath, str) assert exists(filepath) assert filepath.endswith(".png")
def test_face_filters(): from models.face_filters import BUILTIN_AR_FILTERS, apply_face_filter
img = np.zeros((100, 100, 3), dtype=np.uint8) for filter_name in BUILTIN_AR_FILTERS: res, msg = apply_face_filter(img, filter_name) assert res.shape == img.shape assert res.dtype == np.uint8 assert isinstance(msg, str)
def test_custom_ar_filters(): from models.face_filters import apply_face_filter, ar_filter_names, delete_ar_filter, save_ar_filter
custom_def = { "elements": [ {"landmark": "forehead", "shape": "crown", "color": [255, 215, 0], "scale": 1.0}, {"landmark": "eyes", "shape": "visor", "color": [0, 255, 255], "scale": 1.0}, ] } saved = save_ar_filter("Test Crown Visor", custom_def) assert saved["name"] == "Test Crown Visor" assert "Test Crown Visor" in ar_filter_names(True)
img = np.zeros((100, 100, 3), dtype=np.uint8) res, msg = apply_face_filter(img, "Test Crown Visor") assert res.shape == img.shape
delete_ar_filter("Test Crown Visor") assert "Test Crown Visor" not in ar_filter_names(False)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import tempfilefrom pathlib import Pathimport numpy as npfrom developer_api import load_image, process_image, save_image, generate_python_snippet
def sample_img(): arr = np.zeros((40, 50, 3), dtype=np.uint8) arr[10:30, 10:30] = [100, 150, 200] return arr
def test_developer_api_process_image(): img = sample_img() out, meta = process_image(img, "filter", operation_name="Sepia") assert out.shape == img.shape assert meta["operation"] == "Sepia"
def test_developer_api_transform_and_morph(): img = sample_img() out_t, meta_t = process_image(img, "transform", operation_name="Rotation", params={"angle": 15}) assert out_t.ndim == 3 assert out_t.shape[2] == 3
out_m, meta_m = process_image(img, "morphology", operation_name="Opening", params={"size": 3}) assert out_m.shape == img.shape
def test_developer_api_ar(): img = sample_img() out_ar, meta_ar = process_image(img, "ar", operation_name="Glasses") assert out_ar.shape == img.shape assert "status" in meta_ar
def test_generate_python_snippet(): snippet = generate_python_snippet("Sepia", {"contrast": 1.2}) assert "apply_step" in snippet assert "Sepia" in snippet
def test_save_and_load_image(): img = sample_img() with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f: tmp_path = f.name save_image(img, tmp_path) loaded = load_image(tmp_path) assert loaded.shape == img.shape Path(tmp_path).unlink(missing_ok=True)README.md+122-12
__pycache__/app.cpython-312.pycAdded
__pycache__/conftest.cpython-312-pytest-8.4.2.pycAdded
__pycache__/developer_api.cpython-312.pycAdded
app.pyAdded+471
assets/sample_cells.pngAdded

assets/sample_grid.pngAdded

assets/sample_portrait_placeholder.pngAdded

assets/style_texture_1.pngAdded

assets/style_texture_2.pngAdded

assets/style_texture_3.pngAdded

batch/__init__.pyAdded
batch/__pycache__/__init__.cpython-312.pycAdded
batch/__pycache__/dataset_processor.cpython-312.pycAdded
batch/dataset_processor.pyAdded+61
cli.pyAdded+98
conftest.pyAdded+6
cv_ops/__init__.pyAdded
cv_ops/__pycache__/__init__.cpython-312.pycAdded
cv_ops/__pycache__/analysis.cpython-312.pycAdded
cv_ops/__pycache__/morphology.cpython-312.pycAdded
cv_ops/__pycache__/transforms.cpython-312.pycAdded
cv_ops/analysis.pyAdded+44
cv_ops/morphology.pyAdded+49
cv_ops/transforms.pyAdded+46
developer_api.pyAdded+102
filters/__init__.pyAdded
filters/__pycache__/__init__.cpython-312.pycAdded
filters/__pycache__/builtin.cpython-312.pycAdded
filters/__pycache__/custom.cpython-312.pycAdded
filters/__pycache__/registry.cpython-312.pycAdded
filters/builtin.pyAdded+137
filters/custom.pyAdded+37
filters/registry.pyAdded+98
models/__init__.pyAdded
models/__pycache__/__init__.cpython-312.pycAdded
models/__pycache__/face_filters.cpython-312.pycAdded
models/__pycache__/style_transfer.cpython-312.pycAdded
models/face_filters.pyAdded+352
models/style_transfer.pyAdded+41
pytest.iniAdded+4
requirements.txtAdded+10
saved_ar_filters/ar_filters_registry.jsonAdded+210
saved_ar_filters/fa0c305e-44b6-459a-ae32-a1256dc2ecc2.jsonAdded+204
saved_filters/filters_registry.jsonAdded+1
tests/__pycache__/test_cv_ops.cpython-312-pytest-8.4.2.pycAdded
tests/__pycache__/test_developer_api.cpython-312-pytest-8.4.2.pycAdded
tests/test_cv_ops.pyAdded+90
tests/test_developer_api.pyAdded+51