Python 萬能代碼模版:批量搞圖,秀翻全場(上)
“閱讀本文大概需要6分鐘”
你好,我是悅創(chuàng)。
前面我寫了:
最近在準備拍攝編程類的短視頻,所以耽擱了。接下來還是和之前一樣,爭取一周一篇,每一篇希望都對你們有所幫助。
1. 批量給照片加水印
需要首先安裝 opencv、pillow:
pip3 install opencv-python
pip3 install pillow
如果手中有非常多的圖片,想保護自己版權,或者申明來源,我們可以在圖片上加水印。那如何用 Python 給非常多的圖片批量加上文字水印呢?
還是以我們在爬蟲示例的 3 小節(jié)中批量下載的圖片文件夾為例。
下述代碼會給該文件夾下所有圖片的 (width/2, height-30) 這個坐標點加上 “@黃家寶|www.aiyc.top” 這個中文加個人網址。坐標點是以圖片左上角為基準的。具體的水印大小和位置可以自行調整,不過調錯,有可能打不上水印噢。
# -*- coding: utf-8 -*-
# @Author: AI悅創(chuàng)
# @Date: 2021-10-02 10:26:52
# @Last Modified by: aiyc
# @Last Modified time: 2021-10-04 20:15:13
import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont
import os
class WaterMark(object):
def __init__(self, OperationFilename=".", output_dir="watermark", textSize=10, watermarkText="水印", textColor="#ffffff", system=False, winfontfile=r"C:\Windows\Fonts\STZHONGS.ttf", macfontfile="/System/Library/Fonts/PingFang.ttc"):
self.OperationFilename = OperationFilename
self.output_dir = output_dir
self.textSize = textSize
self.watermarkText = watermarkText
self.textColor = textColor
self.system = system
self.winfontfile = winfontfile
self.macfontfile = macfontfile
def mkdirs(self):
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
print(f"文件夾 {self.output_dir} 已經自動為你創(chuàng)建,圖片將保存到:{self.output_dir}")
else:
print(f"文件夾 {self.output_dir} 已經存在,圖片將保存到:{self.output_dir}")
def system_font(self):
if not self.system:
return ImageFont.truetype(self.textSize, encoding="utf-8")
if self.system.upper() == "MAC":
# FontFilePath = "/System/Library/Fonts/PingFang.ttc"
return ImageFont.truetype(font=self.macfontfile, size=self.textSize, encoding="utf-8")
elif self.system.upper() == "WINDOWS":
# FontFilePath = r"C:\Windows\Fonts\STZHONGS.ttf"
return ImageFont.truetype(font=self.winfontfile, size=self.textSize, encoding="utf-8")
def parsepath(self):
path_lst = []
# a = os.walk("tips_3/")
root, dirs, files = next(os.walk(self.OperationFilename))
# root, dirs, files = next(os.walk("tips_3/"))
# print(list(a))
for item in files:
file_path = os.path.join(root, item)
# self.process_file(file_path)
path_lst.append(file_path)
return path_lst
def process_file(self, file_path):
img = cv2.imread(file_path)
image_shape = img.shape
height = image_shape[0]
width = image_shape[1]
# print(img.size)
if (isinstance(img, numpy.ndarray)):
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fontStyle = self.system_font()
# 繪制文本
# textColor = (168, 121, 103)
draw.text((width/2, height-30), self.watermarkText, self.textColor, font=fontStyle)
# draw.text((width/2, height-30), self.watermarkText, fill=self.textColor, font=fontStyle)
# 轉換回 OpenCV 類型
img2 = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
# 保存圖片
file_name = file_path.split("/")[-1]
cv2.imwrite(os.path.join(self.output_dir, file_name), img2)
print(f"proceed {file_path}")
def main(self):
self.mkdirs()
path_lst = self.parsepath()
# print(path_lst)
for path in path_lst:
self.process_file(path)
if __name__ == '__main__':
run = WaterMark(
OperationFilename="tips_3/",
output_dir="image_watermark",
textSize=10,
watermarkText="@黃家寶|www.aiyc.top",
textColor="gray",
system="Windows",
winfontfile="JiZiJingDianKaiTiJianFan-.ttf")
run.main()
代碼執(zhí)行完后,可以去 image_watermark 這個文件夾中查看圖片,可以看到這里的所有圖片都已經被打上了文字水印。

替換說明:


文字水印的位置,以圖片左上角為原點; 想要處理的圖片文件夾名稱 處理完后保存結果的文件夾名稱,放心這個會自動創(chuàng)建 水印字體大小 文字水印的內容 文字水印的顏色,支持顏色單詞、RGB、十六進制顏色 選擇你的操作系統(tǒng)和字體路徑,字體路徑不寫也可以,添加這個接口主要是為了方便修改自己下載的字體路徑。
代碼連接:https://github.com/AndersonHJB/AIYC_DATA/tree/main/04-批量搞圖,秀翻全場/1.%20批量給照片加水印
“AI悅創(chuàng)·推出輔導班啦,包括「Python 語言輔導班、C++輔導班、算法/數據結構輔導班、少兒編程、pygame 游戲開發(fā)」,全部都是一對一教學:一對一輔導 + 一對一答疑 + 布置作業(yè) + 項目實踐等。QQ、微信在線,隨時響應!V:Jiabcdefh
”
黃家寶丨AI悅創(chuàng)
隱形字
攝影公眾號「悅創(chuàng)攝影研習社」
在這里分享自己的一些經驗、想法和見解。
長按識別二維碼關注
評論
圖片
表情


