循环在Python中写入需要很多时间。

huangapple go评论72阅读模式
英文:

loops written in Python take a lot of time

问题

我正在使用Python中的OpenCV制作这个蓝色滤镜,它能够工作,但视频输出有延迟。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)  

while True:
    ret, frame = cap.read()  
    for i in range(frame.shape[0]):
        for j in range(frame.shape[1]):
            frame[i][j] = [255,frame[i][j][1],frame[i][j][2]]

    cv2.imshow('frame',frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()  
cv2.destroyAllWindows()
英文:

I was making this blue colored filter using openCV in python and it works but the video output is lagging.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)  

while True:
    ret, frame = cap.read()  
    for i in range(frame.shape[0]):
        for j in range(frame.shape[1]):
            frame[i][j] = [255,frame[i][j][1],frame[i][j][2]]

    cv2.imshow('frame',frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()  
cv2.destroyAllWindows()    

答案1

得分: 1

你可以利用NumPy中的向量化操作来避免显式循环:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    
    frame[:, :, 0] = 255  # 将蓝色通道设为255(全蓝)
    
    cv2.imshow('frame', frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
英文:

You can utilize vectorized operations in NumPy to avoid the explicit loops:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    
    frame[:, :, 0] = 255  # Set blue channel to 255 (full blue)
    
    cv2.imshow('frame', frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

huangapple
  • 本文由 发表于 2023年7月17日 21:45:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定