我正在python3上使用opencv 4.1。我需要从垫子上获得像素的平均和。通过x和y坐标,但是它在PC上的平均计数(我猜是频率,延迟或时间)太慢,平均为0.06-0.07(在树莓派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