以下是几种常见的图片去水印方法及代码示例,适用于不同场景:
一、基础去水印(半透明蒙版)
```python
from PIL import Image, ImageChops
def remove_transparent_watermark(input_path, output_path):
打开图片
img = Image.open(input_path)
创建透明蒙版(根据水印位置调整)
mask = Image.new('alpha', img.size, 0)
绘制蒙版区域(示例:去除右下角水印)
mask.paste(Image.new('L', (300, 200), 255).resize((300, 200)), (img.size[0]-300, img.size[1]-200))
应用蒙版
result = ImageChops.darker(img, mask)
result.save(output_path)
使用示例
remove_transparent_watermark("watermarked.jpg", "clean.jpg")
```
二、基于OpenCV的边缘检测(文字水印)
```python
import cv2
def remove_text_watermark(input_path, output_path):
img = cv2.imread(input_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
假设水印在图片顶部for cnt in contours:
if cv2.contourArea(cnt) > 1000 and cv2.contourArea(cnt) < 10000:
x,y,w,h = cv2.boundingRect(cnt)
if y < 100 and h < 50: 调整阈值
cv2.rectangle(img, (x,y), (x+w,y+h), (255,255,255), -1)
cv2.imwrite(output_path, img)
使用示例
remove_text_watermark("watermarked.jpg", "clean.jpg")
```
三、基于深度学习的专业去水印(推荐)
使用预训练的Stable Diffusion模型:
```python
from diffusers import StableDiffusionPipeline
def remove_watermark_with_stable_diffusion(input_path, output_path):
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16
).to("cuda")
四、在线API方案(无需本地安装)
```python
import requests
def remove_watermark在线(input_url, output_path):
使用Remove.bg API(需注册获取API Key)
headers = {
"Authorization": "Bearer YOUR_API_KEY"