[英]How can I increase performance Python script using numpy and numba?
[英]how can i increase performance in python opencv?
我在 python3 上使用 opencv 4.1。 我需要从垫子上获得平均像素总和。 通过 x 和 y 坐标,但计算速度太慢,平均(我猜是频率、延迟或时间)在 pc 上为 0.06-0.07(在 raspberry pi 3b 0.6 上)
这是我的代码:
import cv2 as cv
import numpy as np
id = 1
cap = cv.VideoCapture(id)
if not cap.isOpened():
print('cannot open camera ' + id)
while True:
e1 = cv.getTickCount()
sx = 0
px = 1
_, frame = cap.read()
frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
_, frame = cv.threshold(frame, 50, 255, cv.THRESH_BINARY)
for x in range(0, 640):
for y in range(230, 250):
if frame[y, x] == 0:
sx += x
px += 1
print(sx / px)
e2 = cv.getTickCount()
print('average = ' + str((e2-e1) / cv.getTickFrequency()))
cv.imshow('video', frame)
if cv.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
我该如何优化?
你的代码可以用numpy
化为:
while True:
e1 = cv.getTickCount()
sx = 0
px = 1
_, frame = cap.read()
frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# note the _INV
_, frame = cv.threshold(frame, 50, 255, cv.THRESH_BINARY_INV)
# count the number of non-zero
xs,_ = np.nonzero(frame)
# if you insist on using cv.THRESH_BINARY
# replace above two lines with
# _, frame = cv.threshold(frame, 50, 255, cv.THRESH_BINARY)
# xs,_ = np.where(frame==0)
# equivalent of those two lines, without thresholding
# xs, _ = np.where(frame < 50)
# sx, px = xs.sum(), len(xs)
# if you only want sx/px:
print(xs.mean())
e2 = cv.getTickCount()
print('average = ' + str((e2-e1) / cv.getTickFrequency()))
cv.imshow('video', frame)
if cv.waitKey(10) & 0xFF == ord('q'):
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.