想要实现一个功能:
- 输入:目标检测或者跟踪或者车牌识别的结果以及原始图片帧序列
- 输出:将目标检测的bbox框画到图片上以及车牌识别等文字写到图片上,生成结果展示视频,进行可视化,在前端网页中进行展示。
- 因为直接用js在图片中画框,写文字以及合成视频比较麻烦,因此考虑到直接用python实现,写个函数让js调用,返回生成视频的路径,前端获取路径进行展示即可
一、跑通js调用Python函数过程
首先将整个过程跑通,然后再来进行业务代码的书写
1.安装eel及其他
pip install eel # 安装eel
2.把python函数暴露给js
@eel.expose
def my_add(a, b):
return a+b
3.在js中引入eel,调用python函数
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
async function test(){
// 调用python函数
const res = await eel.my_add(3,4)();
console.log(res);
}
</script>
4.启动python程序,为网页开启微型服务器
eel.init('web') #给出包含web文件的文件夹
eel.start('hello.html') #开始进入循环,自动启动你的主页
二、业务代码
1.js
<script type="text/javascript">
const path = "../../";
// 输入图片的路径
const imgpath = path+"img/";
// 输出图片的路径
const imgout_path =path+ "out/";
// 输出视频的路径
const vedio_path = path
// 输入json文件的路径
const resJson = "../../input.json"
async function show(imgpath, imgout_path, vedio_path, resJson){
// 调用python函数
// vedio_name 为返回的生成视频的路径名称
const vedio_name = await eel.vis(imgpath, imgout_path, vedio_path, resJson)();
console.log(vedio_name);
}
// 页面加载即运行函数
window.οnlοad = show(imgpath, imgout_path, vedio_path, resJson);
</script>
2.python函数
(1)处理输入的结果文件 input.json
(2)将内容添加到图片,画矩形框+写车牌号等
(3)将图片合称为视频
# 视频保存
vedio_name = vedio_path+'res.mp4'
writer = cv2.VideoWriter(vedio_name,cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), 25, (size[1], size[0]), True)
# **********设置帧的数量**********
# total_frame = len(os.listdir(imgout_path))
# print(total_frame)
for i in imgout_files:
if i.endswith('.jpg'):
read_img = cv2.imread(imgout_path + '/' + i, cv2.IMREAD_COLOR) # 打开文件
# print(img)
writer.write(read_img)
writer.release()
最后return 生成视频的路径及名称即可。
三、遇到问题
1.运行python文件报错 cannot import name Timer
找到报错文件报错行,注释掉这一行即可
2.使用opencv在图片上写汉字出现乱码情况
(1)定义一个函数
#在图片上写字,解决中文乱码问题
def cv2ImgAddText(img, text, left, top, textColor=(255, 255, 255), textSize=35):
if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# 创建一个可以在给定图像上绘图的对象
draw = ImageDraw.Draw(img)
# 字体的格式
fontStyle = ImageFont.truetype(
"fonts/chinese/simsun.ttc", textSize, encoding="utf-8")
# 绘制文本
draw.text((left, top), text, textColor, font=fontStyle)
# 转换回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
写文字时调用这个函数即可
# 写文字
img = cv2ImgAddText(img,show_list[img_name][rec][1] , show_list[img_name][rec][0][0], show_list[img_name][rec][0][1], (0, 255, 0), 40)
fonts/chinese/simsun.ttc
为字体文件,我是拷贝了本地路径下的文件到此文件夹下。