簡體   English   中英

如何提高python opencv的性能?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM