|
import cv2 |
|
import numpy as np |
|
import gradio as gr |
|
|
|
|
|
|
|
def apply_watermark(img, logo, mode): |
|
|
|
|
|
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) |
|
logo = cv2.cvtColor(logo, cv2.COLOR_RGBA2BGRA) |
|
|
|
|
|
main_height, main_width = img.shape[:2] |
|
watermark_height, watermark_width = logo.shape[:2] |
|
|
|
|
|
x = main_width - watermark_width |
|
y = main_height - watermark_height |
|
|
|
|
|
padding = 10 |
|
x -= padding |
|
y -= padding |
|
|
|
|
|
roi = img[y : y + watermark_height, x : x + watermark_width] |
|
|
|
|
|
|
|
logo_bgr = logo[:, :, 0:3] |
|
logo_alpha = logo[:, :, 3] |
|
|
|
|
|
|
|
logo_mask = cv2.merge([logo_alpha, logo_alpha, logo_alpha]) |
|
logo_mask_inv = cv2.bitwise_not(logo_mask) |
|
|
|
|
|
masked_roi = cv2.bitwise_and(roi, logo_mask_inv) |
|
|
|
|
|
masked_logo = cv2.bitwise_and(logo_bgr, logo_mask) |
|
|
|
if mode == "Opaque": |
|
|
|
|
|
|
|
roi_final = cv2.bitwise_or(masked_roi, masked_logo) |
|
|
|
|
|
img_1 = img.copy() |
|
|
|
|
|
img_1[y : y + watermark_height, x : x + watermark_width] = roi_final |
|
|
|
|
|
return cv2.cvtColor(img_1, cv2.COLOR_BGR2RGB) |
|
else: |
|
|
|
roi_2 = roi.copy() |
|
|
|
|
|
watermarked = cv2.addWeighted(roi_2, 1, masked_logo, 0.6, 0) |
|
|
|
|
|
img_2 = img.copy() |
|
|
|
|
|
img_2[y : y + watermark_height, x : x + watermark_width] = watermarked |
|
|
|
|
|
return cv2.cvtColor(img_2, cv2.COLOR_BGR2RGB) |
|
|
|
|
|
def main(img, logo, mode): |
|
img_final = apply_watermark(img, logo, mode) |
|
return img_final |
|
|
|
|
|
image_input = gr.Image(type="numpy", label="Input Image") |
|
logo_input = gr.Image(type="numpy", label="Logo Image", image_mode="RGBA") |
|
mode = gr.Radio(["Opaque", "Transparent"], label="Watermark Mode", info="Choose the MODE") |
|
final_output = gr.Image(type="numpy", label="Output Image") |
|
|
|
interface = gr.Interface( |
|
fn=main, |
|
inputs=[image_input, logo_input, mode], |
|
outputs=[final_output], |
|
title="OpenCV Watermark", |
|
description="Upload your Input Image and choose a logo to create your watermark image!", |
|
examples=[["./images/hp-2.jpg", "./images/opencv-logo-rz.png"], ["./images/hp.jpg", "./images/opencv-university-rz.png"]], |
|
cache_examples=False, |
|
) |
|
|
|
interface.launch() |