使用cv2实现文字及线条的绘制,注意不可以对同一图片多次进行旋转,否则图片会慢慢“融化”,需要保存原图片,并每次旋转一定的角度。
实现效果如图所示:
代码如下:
# 在圆圈上绘制文字并旋转
import time
import tkinter as tk
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageTk
from threading import Thread
width = 100
# # 字体
font_path = "奶酪陷阱体.ttf"
font = ImageFont.truetype(font_path, int(width)) # 第二个参数为size,即正方形的边长
# 显示内容
str = "益禾堂温馨提示:请保持2米安全社交距离"
# 文字所围绕旋转的圆形的半径
radius = 200
# 窗口大小
size_window = (800, 600)
# 旋转的圆心
center_loc = (int(size_window[0]/2), int(size_window[1]/2))
# 创建画布
img = Image.new("RGB", size_window, "black") # 黑色背景
# 角度
angle = 18 # 文字间距
angle_count = 0 # 用于回正角度
# 绘制图标(益禾堂
img_icon = cv2.imread('yht_icon.png')
img_icon = cv2.resize(img_icon, (width, width))
img = np.array(img)
# 将图标绘制到主图
img[int(center_loc[1]-radius-width):int(center_loc[1]-radius),
int(center_loc[0]-width/2):int(center_loc[0]+width/2)] = img_icon # x后y前
# 旋转
M = cv2.getRotationMatrix2D(center_loc, angle, 1.0)
img = cv2.warpAffine(img, M, size_window,
flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
angle_count += angle
# 绘制文字
for c in str:
print(c)
# 文字,需要Image类型
img = Image.fromarray(img)
draw = ImageDraw.Draw(img)
draw.text((center_loc[0]-width/2, center_loc[1] -
radius-width), c, (255, 255, 255), font=font)
# 旋转,需要array类型
img = np.array(img)
M = cv2.getRotationMatrix2D(center_loc, angle, 1.0)
img = cv2.warpAffine(
img, M, size_window, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
angle_count += angle
# 回正角度
img = np.array(img)
M = cv2.getRotationMatrix2D(center_loc, -angle_count+100, 1.0)
img = cv2.warpAffine(img, M, size_window,
flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
# 画图,需要array类型
cv2.circle(img, center_loc, radius, (0, 0, 255), 8)
cv2.line(img, (400, center_loc[1]-radius),
(400, center_loc[1]+radius), (0, 0, 255), 8)
# 当前旋转的角度
angle_realtime = 0
def around():
global img
global angle_realtime
angle = 2 # 每次旋转的角度
while(True):
M = cv2.getRotationMatrix2D(center_loc, angle_realtime, 1.0) # 顺时针转动
img2show = cv2.warpAffine(
img, M, size_window, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
img2show = cv2.cvtColor(img2show, cv2.COLOR_RGB2BGR)
img2show = Image.fromarray(img2show)
img2show = ImageTk.PhotoImage(img2show)
label_picture.config(image=img2show)
label_picture.image = img2show # keep a reference
angle_realtime += angle
angle_realtime %= 360
time.sleep(0.05)
t2 = Thread(target=around)
t2.setDaemon(True)
t2.start()
# 定义窗口
window = tk.Tk('test')
label_picture = tk.Label(window, width=size_window[0], height=size_window[1])
label_picture.grid(row=1, column=1)
img2show = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
img2show = Image.fromarray(img)
img2show = ImageTk.PhotoImage(img2show)
label_picture.config(image=img2show)
label_picture.image = img2show # keep a reference
window.mainloop()