Hello, I’m Yue Chuang.

I wrote earlier:

  1. Python Universal Code Template: Crawler code
  2. Python Universal Code Template: Data Visualization
  3. Python universal code template: automatic office, increase productivity X10 times
  4. The Python Universal Code Template:

Articles will be published on the official account oh: official account: AI Yue Chuang. Blog: www.aiyc.top/ will also be sent synchronously.

Recently, I was preparing to shoot a short video about programming, so I was delayed. Again, as before, try to write one essay a week, and every essay will help you.

1. Batch watermarks

You need to install OpencV, Pillow first:

pip3 install opencv-python
pip3 install pillow
Copy the code

If we have a lot of pictures and want to protect our copyright, or claim our source, we can put watermarks on the pictures. How do you batch watermark large numbers of images with Python?

Again, take the images folder that we downloaded in bulk in section 3 of the crawler example.

The following code will give of all of the images in the folder (width / 2, height – 30) the coordinate points plus “@ Huang Jiabao | www.aiyc.top” this Chinese personal website. The coordinate points are based on the upper left corner of the image. The specific size and position of the watermark can be adjusted, but the wrong adjustment, may not hit the watermark oh.

# -*- coding: utf-8 -*-
# @author: AI Yue Chuang
# @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="Watermark", 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 "folder{self.output_dir}Created automatically for you, images will be saved to:{self.output_dir}")
		else:
			print(F "folder{self.output_dir}The image will be saved to:{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()
		# draw text
		# 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)
		Convert back to OpenCV type
		img2 = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
		# Save images
		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="@ Huang Jiabao | www.aiyc.top",
		textColor="gray",
		system="Windows",
		winfontfile="JiZiJingDianKaiTiJianFan-.ttf")
	run.main()
Copy the code

After executing the code, you can go to the image_watermark folder to view the images, and you can see that all the images here have been watermarked with text.Replacement instructions:

  1. The position of the text watermark, starting from the upper left corner of the picture;
  2. The name of the image folder you want to process
  3. Save the result folder name after processing, rest assured that this will be created automatically
  4. Watermark font size
  5. Text watermark content
  6. Text watermark color, support color words, RGB, hexadecimal color
  7. Select your operating system and font path, font path does not write also can add this interface is mainly for the convenience of modifying their downloaded font path.

Code link: github.com/AndersonHJB…

Official account: AI Yue Chuang.

V: Jiabcdefh