import matplotlib.pyplot as plt import kerasocr import cv2 import math import numpy as…
- User
import matplotlib.pyplot as plt import keras_ocr import cv2 import math import numpy as np
def midpoint(x1, y1, x2, y2): x_mid = int((x1 + x2)/2) y_mid = int((y1 + y2)/2) return (x_mid, y_mid)
def inpaint_text(img_path, pipeline):
codeimg = keras_ocr.tools.read(img_path) prediction_groups = pipeline.recognize([img]) mask = np.zeros(img.shape[:2], dtype="uint8") for box in prediction_groups[0]: x0, y0 = box[1][0] x1, y1 = box[1][1] x2, y2 = box[1][2] x3, y3 = box[1][3] x_mid0, y_mid0 = midpoint(x1, y1, x2, y2) x_mid1, y_mi1 = midpoint(x0, y0, x3, y3) thickness = int(math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)) cv2.line(mask, (x_mid0, y_mid0), (x_mid1, y_mi1), 255, thickness) inpainted_img = cv2.inpaint(img, mask, 7, cv2.INPAINT_NS) return (inpainted_img)pipeline = keras_ocr.pipeline.Pipeline()
img_text_removed = inpaint_text('jizhan_watermark2.png', pipeline)
plt.imshow(img_text_removed)
cv2.imwrite('text_removed_image.jpg', cv2.cvtColor(img_text_removed, cv2.COLOR_BGR2RGB)) 将上述代码改为使用paddle ocr
- Assistant
要使用PaddleOCR替换Keras-OCR,首先需要安装PaddleOCR库:
bash!pip install paddlepaddle-gpu==2.1.0.post101 -f https://paddlepaddle.org.cn/whl/mkl/avx/stable.html !pip install paddleocr然后修改代码如下:
python - User
python 如何给图片添加多行文字水印
- Assistant
你可以使用Python的PIL(Python Imaging Library,也称为Pillow)库来向图片添加多行文字水印。以下是一个示例:
pythonfrom PIL import Image, ImageDraw, ImageFont def add_watermark(image_path, output_path, watermark_text_list, font_path, font_size): # 加载图片 image = Image.open(image_path).convert('RGBA') txt = Image.new('RGBA', image.size, (255, 255, 255, 0)) # 加载字体 font = ImageFont.truetype(font_path, font_size) # 创建绘画对象 draw = ImageDraw.Draw(txt) # 设置水印文字颜色和透明度 text_color = (255, 255, 255, 200) # white color with alpha 200 # 计算每行文字的位置 x, y = 10, 10 # 从图片的左上角10,10开始 line_height = font_size + 10 # 每行文字之间的间距 for text in watermark_text_list: draw.text((x, y), text, font=font, fill=text_color) y += line_height # 合并图片和文字层 watermarked_image = Image.alpha_composite(image, txt) # 保存添加了水印的图片 watermarked_image.save(output_path) # 示例使用 image_path = 'input_image.jpg' output_path = 'output_image.jpg' watermark_text_list = ['Line 1', 'Line 2', 'Line 3'] font_path = 'Arial.ttf' # 你可以选择任何一个合适的字体(TTF)文件 font_size = 20 add_watermark(image_path, output_path, watermark_text_list, font_path, font_size)