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

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

loops written in Python take a lot of time

问题

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

  1. import numpy as np
  2. import cv2
  3. cap = cv2.VideoCapture(0)
  4. while True:
  5. ret, frame = cap.read()
  6. for i in range(frame.shape[0]):
  7. for j in range(frame.shape[1]):
  8. frame[i][j] = [255,frame[i][j][1],frame[i][j][2]]
  9. cv2.imshow('frame',frame)
  10. if cv2.waitKey(1) == ord('q'):
  11. break
  12. cap.release()
  13. cv2.destroyAllWindows()
英文:

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

  1. import numpy as np
  2. import cv2
  3. cap = cv2.VideoCapture(0)
  4. while True:
  5. ret, frame = cap.read()
  6. for i in range(frame.shape[0]):
  7. for j in range(frame.shape[1]):
  8. frame[i][j] = [255,frame[i][j][1],frame[i][j][2]]
  9. cv2.imshow('frame',frame)
  10. if cv2.waitKey(1) == ord('q'):
  11. break
  12. cap.release()
  13. cv2.destroyAllWindows()

答案1

得分: 1

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

  1. import numpy as np
  2. import cv2
  3. cap = cv2.VideoCapture(0)
  4. while True:
  5. ret, frame = cap.read()
  6. frame[:, :, 0] = 255 # 将蓝色通道设为255(全蓝)
  7. cv2.imshow('frame', frame)
  8. if cv2.waitKey(1) == ord('q'):
  9. break
  10. cap.release()
  11. cv2.destroyAllWindows()
英文:

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

  1. import numpy as np
  2. import cv2
  3. cap = cv2.VideoCapture(0)
  4. while True:
  5. ret, frame = cap.read()
  6. frame[:, :, 0] = 255 # Set blue channel to 255 (full blue)
  7. cv2.imshow('frame', frame)
  8. if cv2.waitKey(1) == ord('q'):
  9. break
  10. cap.release()
  11. 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:

确定