python - OpenCV 太慢了
问题描述
我想将网络摄像头捕获的视频叠加在另一个实时视频上。所以我尝试了上面的代码,但它太慢了。
我应该切换到另一种语言或 lib 还是什么?
任何建议或帮助将不胜感激。
import numpy as np
from cv2 import cv2
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation = inter)
# return the resized image
return resized
cap2 = cv2.VideoCapture('http://192.168.43.1:8080/video')
cap = cv2.VideoCapture('test.mp4')
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('sample3.mp4',fourcc,30, (640,480))
# watermark = logo
# cv2.imshow("watermark",watermark)
while(cap.isOpened()):
ret, frame = cap.read()
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2BGRA)
ret2 ,frame2 = cap2.read()
frame2 = cv2.cvtColor(frame2,cv2.COLOR_BGR2BGRA)
watermark = image_resize(frame2,height=177)
if ret==True:
frame_h, frame_w, frame_c = frame.shape
overlay = np.zeros((frame_h, frame_w, 4), dtype='uint8')
overlay[543:543+177,1044:1044+236] = watermark
cv2.addWeighted(frame, 0.25, overlay, 1.0, 0, frame)
frame = cv2.cvtColor(frame,cv2.COLOR_BGRA2BGR)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
要求是将网络摄像头实时视频平滑地覆盖在底部的另一个视频上。
谢谢。
解决方案
基本上,如果您希望它更快,您可能不会使用 python 循环迭代图像。您正在尝试使用 2 个嵌套循环将按比例缩小的图像复制到空叠加层中,这非常慢。我不明白这个条件
if watermark[i,j][3] != 0:
还有这部分:
offset = 0
h_offset = frame_h - watermark_h -offset
w_offset = frame_w - watermark_w - offset
应该脱离循环——它们都是常数。
但最重要的是,您可以执行以下操作,而不是在图像上循环:
offset[h_offset:h_offset+watermark_h,w_offset:w_offset+watermark_w] = watermark
在此之后,我从 9 fps 提高到 28 fps。
推荐阅读
- mongodb - 如何使用 Mongoose Schema 修复 GraphQL Mutation 中的构造函数错误
- safari - Safari v12+(MacOS 和 iOS)上的跨源服务器推送额外请求问题
- azure - 如何使用 Powershell 从订阅中获取 Cosmos DB 的数据大小
- swiftui - swiftui 文本,如何将布尔值传递给 func hidden ()
- sql - R Markdown:创建一个 SQL 表,然后将其作为数据框输出
- javascript - 编译 Angular 1.x 项目
- c# - 如何使用 C# 捕获流式传输到 Thunderbolt (3) 端口的视频?
- javascript - JavaScript 文件不使用 HTML 执行
- javascript - 如何使用所述列表项上的按钮删除列表项
- acumatica - Acumatica 的 OData 层是否支持 $count 或 $inlinecount