基于Python实现网页版去图片右下角水印
Python可以用OpenCV去除图片水印,但如何结合web框架去实现网页版去水印,带着这样的疑问,我搜索研究了一下,发现是完全可以实现的,而且考虑到部署服务器,也是可以实现的,这里就不详细说明了。本文采用Pycharm软件。
基于Flask框架实现网页上传图片,执行效果:
打开网页输入以下网址:127.0.0.1:5000,这是来源于后面代码app.run(host='0.0.0.0', port=5000, debug=True)。
代码解析:
(1)Flask框架搭建
新建qushuiyin.py文件,在该文件下输入以下代码。
from flask import Flask, render_template, request, redirect, url_for, make_response, jsonify
from werkzeug.utils import secure_filename
import os
import cv2
import time
import numpy as np
from PIL import Image
from datetime import timedelta
# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)
# @app.route('/upload', methods=['POST', 'GET'])
@app.route('/', methods=['POST', 'GET']) # 添加路由
def upload():
if request.method == 'POST':
f = request.files['file']
if not (f and allowed_file(f.filename)):
return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、PNG、jpg、JPG、bmp"})
user_input = request.form.get("name")
basepath = os.path.dirname(__file__) # 当前文件所在路径
upload_path = os.path.join(basepath, './static/photo', secure_filename(f.filename)) # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
f.save(upload_path)
return render_template('REpicture_ok.html', val1=time.time())
return render_template('REpicture.html')
if __name__ == '__main__':
# app.debug = True
app.run(host='0.0.0.0', port=5000, debug=True)
(2)REpicture_ok.html和Repicture.html搭建
在当前目录下新建Repicture_ok.html和Repicture.html空白文件,输入以下代码。
#REpicture.html
<head>
<meta charset="UTF-8">
<title>图片右下角去水印</title>
</head>
<body>
<h1>请上传图片文件</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file" style="margin-top:20px;"/>
<br>
<input type="submit" value="去水印" class="button-new" style="margin-top:15px;"/>
</form>
</body>
</html>
#REpicture_ok.html
<head>
<meta charset="UTF-8">
<title>图片右下角去水印</title>
</head>
<body>
<h1>请上传图片文件</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file" style="margin-top:20px;"/>
<br>
<input type="submit" value="去水印" class="button-new" style="margin-top:15px;"/>
</form>
<img src="{{ url_for('static', filename= './photo/result.jpg',_t=val1) }}" width="400" height="400" alt="你的图片被外星人劫持了~~"/>
</body>
</html>
注意:filename= './photo/result.jpg',路径要描述准确,否则会报错。
(3)实现右下角去水印
在qushuiyin.py里f.save(upload_path)代码后接着输入以下代码:
# 使用Opencv转换一下图片格式和名称
img = cv2.imread(upload_path,1)
newPath = os.path.join(basepath,'./static/photo','new.jpg')
hight, width, depth = img.shape[0:3]
# 提取
cropped = img[int(hight * 0.8):hight, int(width * 0.5):width] # 剪裁座标为[y0:y1, x0:x1]
cv2.imwrite(newPath, cropped)
imgSY = cv2.imread(newPath, 1)
# 照片二值化解决,把[200,200,200]-[250,250,250]之外的色调变为0
thresh = cv2.inRange(imgSY, np.array([200, 200, 200]), np.array([250, 250, 250]))
# 建立样子和规格的构造原素
kernel = np.ones((3, 3), np.uint8)
# 拓展待修补地区
hi_mask = cv2.dilate(thresh, kernel, iterations=10)
specular = cv2.inpaint(imgSY, hi_mask, 5, flags=cv2.INPAINT_TELEA)
cv2.imwrite(newPath, specular)
# 遮盖照片
imgSY = Image.open(newPath)
img = Image.open(upload_path)
img.paste(imgSY, (int(width * 0.5), int(hight * 0.8), width, hight))
img.save(upload_path)
img=cv2.imread(upload_path)
cv2.imwrite(os.path.join(basepath, './static/photo', 'result.jpg'), img)
os.remove(os.path.join(basepath,'./static/photo','new.jpg'))
os.remove(os.path.join(basepath,'./static/photo', secure_filename(f.filename)))
说明:
1. int(width * 0.5), int(hight * 0.8),两个常数是可以调节的,但要注意前后一致;
2.'./static/photo'注意路径;
3.过程中会产生几个文件,使用os.remove进行删除操作。
总结:
右下角去水印项目已经很成熟了,网上可以找到很多实例,但结合时下服务器的应用还有待开拓,所以本文还有很多拓展空间,留待后面慢慢完善。