背景图+小图
键盘监听使用的是pynput 库
保存图片时使用了年月日时分秒命名
原图:
from pynput import keyboard
import cv2
import time
# 键盘监听
def on_press(key):
global jie
global guan
if key.char == 'a':
jie = True
elif key.char == 'd':
jie = False
elif key.char == 'q':
guan = True
listener = keyboard.Listener(on_press=on_press)
listener.start()
img1_1 = cv2.imread("./img1_1.jpg") # 正在截图(准备2张图片)
img1_2 = cv2.imread("./img1_2.jpg") # 没有截图(准备两张图片)
# 保存截图程序
# # 截图 y1 y2 x1 x2
# # # 531 450 644 479
# x1, y1, x2, y2 = 541, 450, 644, 479
# img1_1 = img1_1[y1:y2, x1:x2]
#
# cv2.namedWindow('f2100', cv2.WINDOW_NORMAL)
# cv2.imshow('f2100', img1_1)
# cv2.waitKey(0)
# path_img = "./ce/"
# img_name = "img1_2" + ".jpg"
#
# cv2.imwrite(img_name, img1_1)
img1_h, img1_w, img1_3 = img1_1.shape
img2_h, img2_w, img2_3 = img1_2.shape
cap = cv2.VideoCapture("./data_ce_mp4/9.mp4")
# 命名区分
n1 = 0
# 跳帧计数
zhen = 0
# 截图状态开关
jie = False
# 程序关闭按钮
guan = False
# 绘制文字
font = cv2.FONT_HERSHEY_SIMPLEX
while cap.isOpened():
# 逐帧读取
ret, image = cap.read()
n1 += 1 # 取名字
zhen += 1 # 多少帧截取一次
# 视频结束则关闭程序
if not ret:
break
# 按下则关闭程序
if guan:
break
# 跳帧计数
if zhen >= 20:
# 截图状态开关
if jie:
# tm_year=2024, tm_mon=7, tm_mday=22, tm_hour=11, tm_min=1, tm_sec=53, tm_wday=0
# 按照年月日时分秒来命名
localtime = time.localtime(time.time())
# print(localtime)
tm_year = str(localtime.tm_year)
tm_mon = str(localtime.tm_mon)
tm_mday = str(localtime.tm_mday)
tm_hour = str(localtime.tm_hour)
tm_min = str(localtime.tm_min)
tm_sec = str(localtime.tm_sec)
# 保证年月日时分秒是定长的
# 月
if len(tm_mon) != 2:
tm_mon = "0" + tm_mon
# 日
if len(tm_mday) != 2:
tm_mday = "0" + tm_mday
# 时
if len(tm_hour) != 2:
tm_hour = "0" + tm_hour
# 分s
if len(tm_hour) != 2:
tm_min = "0" + tm_min
# 秒
if len(tm_sec) != 2:
tm_sec = "0" + tm_sec
# print(tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec)
path_img = "./ce/"
img_name = tm_year + tm_mon + tm_mday + tm_hour + tm_min + tm_sec + "_" + str(n1) + ".jpg"
cv2.imwrite(path_img + img_name, image)
print("正在截图")
print(img_name)
zhen = 0
# 将小图片按位置百分比放入大图片中
h, w, _1 = image.shape
# 截图 y1 y2 x1 x2
x1_1, y1_1, x2_1, y2_1 = 0 + int(0.1 * w), 0 + int(0.2 * h), img1_w + int(0.1 * w), img1_h + int(0.2 * h)
x1_2, y1_2, x2_2, y2_2 = 0 + int(0.1 * w), 0 + int(0.2 * h), img2_w + int(0.1 * w), img2_h + int(0.2 * h)
# 按照状态不同,叠加的图片不同
if jie:
string_jie = "yes"
image[y1_1:y2_1, x1_1:x2_1] = img1_1
else:
string_jie = "No!"
print("没有截图")
image[y1_2:y2_2, x1_2:x2_2] = img1_2
# 绘制字母
# 参数:图像、文字、坐标、支持的字体、大小、颜色、粗细
# cv2.putText(image, string_jie, (int(0.1 * w), int(0.17 * h)), font, 2, (0, 0, 255), 3)
# print(x1_1, y1_1, x2_1, y2_1)
# 显示的图像是否可以鼠标拖动缩放
# cv2.namedWindow('f2100', cv2.WINDOW_NORMAL)
cv2.imshow('f2100', image)
cv2.waitKey(1)