Skip to content

Instantly share code, notes, and snippets.

@jonasfroeller
Last active July 1, 2024 16:15
Show Gist options
  • Save jonasfroeller/5b08c148ab2192452e555afe0e840283 to your computer and use it in GitHub Desktop.
Save jonasfroeller/5b08c148ab2192452e555afe0e840283 to your computer and use it in GitHub Desktop.
The path mapping to linux style is not working, if emojis are in the filename. Does not work well, if the watermark is white and the background is almost the same color.
@ECHO OFF
REM Set the path to WSL executable
SET WSL_EXECUTABLE=C:\Windows\System32\wsl.exe
REM Get the input and output file paths
SET "INPUT_FILE=%~1"
SET "OUTPUT_FILE=%~1_no_watermark"
REM Debugging output
ECHO Input file: %INPUT_FILE%
ECHO Output file: %OUTPUT_FILE%
REM Convert Windows path to WSL path using wslpath
FOR /F "usebackq tokens=*" %%A IN (`%WSL_EXECUTABLE% wslpath -u "%INPUT_FILE%"`) DO SET WSL_INPUT=%%A
FOR /F "usebackq tokens=*" %%A IN (`%WSL_EXECUTABLE% wslpath -u "%OUTPUT_FILE%"`) DO SET WSL_OUTPUT=%%A
REM Debugging output
ECHO WSL Input: %WSL_INPUT%
ECHO WSL Output: %WSL_OUTPUT%
REM Execute the shell script in WSL
%WSL_EXECUTABLE% bash -c "bash remove_watermark.sh \"%WSL_INPUT%\" \"%WSL_OUTPUT%\""
pause
@jonasfroeller
Copy link
Author

jonasfroeller commented Jul 1, 2024

https://github.com/m3at/video-watermark-removal/tree/main?tab=MIT-1-ov-file

MIT License

Copyright (c) 2021 Paul Willot

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

get_watermark.py:

#!/usr/bin/env python3

import sys
from pathlib import Path

import imageio
import numpy as np
from scipy.ndimage import gaussian_filter


def normalize(x):
    _min = np.min(x)
    _max = np.max(x)
    return (x - _min) / (_max - _min)


if __name__ == "__main__":
    # Load all images
    root = Path(sys.argv[1])
    buff = []
    for p in root.glob("output_*.png"):
        buff.append(imageio.imread(p))
    images = np.array(buff)

    # Compute the gradients
    dx = np.gradient(images, axis=1).mean(axis=3)
    dy = np.gradient(images, axis=2).mean(axis=3)
    mean_dx = np.abs(np.mean(dx, axis=0))
    mean_dy = np.abs(np.mean(dy, axis=0))

    # Filter at a hand picked threshold
    threshold = 10
    salient = ((mean_dx > threshold) | (mean_dy > threshold)).astype(float)
    salient = normalize(gaussian_filter(salient, sigma=3))
    mask = ((salient > 0.2) * 255).astype(np.uint8)

    # Saved the computed mask
    imageio.imsave(root / "mask.png", mask)

remove_watermark.sh:

#!/usr/bin/env bash

set -eo pipefail

if [ "$#" -lt 1 ]; then
    echo "Usage: $0 input_file [output_file] [max_frames]"
    exit 1
fi

input_file="$1"
output_file="${2:-${input_file%.*}_cleaned.mp4}"
max_frames="${3:-50}"

echo "Input file: $input_file"
echo "Output file: $output_file"
echo "Max frames: $max_frames"

# Check if input file exists
if [ ! -f "$input_file" ]; then
    echo "Error: Input file '$input_file' not found."
    exit 1
fi

# Get first few key frames
echo "Getting key frames..."
keyframes_time=$(ffprobe -hide_banner -loglevel warning -select_streams v -skip_frame nokey -show_frames -show_entries frame=pkt_dts_time "$input_file" | grep "pkt_dts_time=" | xargs shuf -n "$max_frames" | awk -F '=' '{print $2}' | tr -cd '[:digit:].\n')

# Save them as images, in a temporary directory
tmpdir=$(mktemp -d 2>/dev/null || mktemp -d -t 'watermark_remove')
counter=0
echo -n "Extracting frames (up to: $max_frames)... "
for i in $keyframes_time; do
    if ! [[ "$i" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
        echo "Skipping unrecognized timing: $i"
        continue
    fi
    ffmpeg -y -hide_banner -loglevel error -ss "$i" -i "$input_file" -vframes 1 "$tmpdir/output_$counter.png"
    echo -n "$counter "
    ((counter=counter+1))
done
echo

# Abort if we couldn't extract frames for some reason
if [[ "$counter" -lt 2 ]]; then
    echo "$counter frames extracted, need at least 2, aborting."
    exit 1
fi

# Extract watermark using Python script
echo "Extracting watermark..."
python3 get_watermark.py "$tmpdir"

# Remove watermark in video and save to new filename
echo "Removing watermark in video..."
ffmpeg -hide_banner -loglevel warning -y -stats -i "$input_file" -acodec copy -vf "removelogo=$tmpdir/mask.png" "$output_file"

rm -rf "$tmpdir"

echo "Done: $output_file"

exit 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment