在Python中从图像中获取水印掩码

Leo*_*o B 4 python opencv watermark numpy edge-detection

给定一系列带水印的照片,我想隔离水印并生成蒙版。

我正在使用 Python 和 numpy。

我已将图片叠加在一起:

def compare_n_img(array_of_img_paths):

img_float_array = []

for path in array_of_img_paths:
    img_float_array.append(load_img_as_float(path))

additionF = sum(img_float_array)/len(img_float_array)

addition = additionF.astype('uint8')

return addition
Run Code Online (Sandbox Code Playgroud)

转换为灰度后,得到了这个合成图像

水印在该合成图中清晰可见。对于人类来说,很容易追踪。

我想要的结果是一个白色图像,水印的形状填充为黑色。因此,如果我用蒙版覆盖一张带水印的图像,水印将被完全覆盖。

我尝试在合成图像上使用边缘检测和阈值处理。但我一直无法找到一种方法来以编程方式隔离水印内容。更不用说创建透明蒙版了。

如果可能的话,我想在纯 numpy 或 cv2 中执行此操作。

Ann*_*Zen 6

在使用 canny 边缘检测器之前,您可以尝试模糊图像。由于检测到的边缘太薄,膨胀和腐蚀的迭代将解决该问题。

检测到边缘后,背景中很可能存在大量噪声,因此过滤掉小面积的轮廓将是有效的。

事情可能是这样的:

import cv2

def process(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_blur = cv2.GaussianBlur(img_gray, (3, 3), 0)
    img_canny = cv2.Canny(img_blur, 161, 54)
    img_dilate = cv2.dilate(img_canny, None, iterations=1)
    return cv2.erode(img_dilate, None, iterations=1)

def get_watermark(img):
    contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    img.fill(255)
    for cnt in contours:
        if cv2.contourArea(cnt) > 100:
            cv2.drawContours(img, [cnt], -1, 0, -1)

img = cv2.imread("watermark.jpg")
get_watermark(img)
cv2.imshow("Watermark", img)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述