有没有一种方法可以使用Python读取和处理相机的帧,然后将其保存到文件中。没有使用像OpenCV这样的库?

2024-06-16 11:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我目前拥有的,但它的阅读速度非常慢。仅仅用opencv读取帧就需要6-8秒,对于我的项目,我需要能够在读取压力传感器时以特定的间隔获取图片。有没有一种方法可以让这个程序在cv2或can上运行得更快?有没有一种方法可以使用阵列,或者什么方法可以让程序运行得更快

import cv2
import timeit
def main(): #Define camera function
    start = timeit.default_timer() #Starts a runtime timer
    hud_Cam = cv2.VideoCapture(0) #Call camera resource
    gauge_Cam = cv2.VideoCapture(1)
    rval, hud_Img = hud_Cam.read() #Read/Grab camera frame
    rval, gauge_Img = gauge_Cam.read()
    stop = timeit.default_timer() #Stops a runtime timer
    print('Time: ', stop - start) #Calculate runtime timer
    start1 = timeit.default_timer() #Starts a runtime timer
    hud_name = ('HudPicture0.jpg') #Initialize file names
    gauge_name = ('GaugePicture0.jpg')
    cv2.imwrite(hud_name, hud_Img) #Write camera frame to file names
    cv2.imwrite(gauge_name, gauge_Img)
    print("Hud Picture written!") #Log to console
    print("Gauge Picture written!")
    hud_Cam.release() #Release camera resource to clear memory
    gauge_Cam.release()
    stop1 = timeit.default_timer() #Stops a runtime timer
    print('Time: ', stop1 - start1) #Calculate runtime timer```

Tags: to方法nameimportdefaultimgcv2camera
2条回答

这使得时间下降到,时间:2.066412200000059

import timeit
start = timeit.default_timer()
import cv2
hud_Cam = cv2.VideoCapture(0, cv2.CAP_DSHOW) #Call camera resource
gauge_Cam = cv2.VideoCapture(1, cv2.CAP_DSHOW)

def main(hud_Cam, gauge_Cam, start): #Define camera function
    while True:
        rval, hud_Img = hud_Cam.read() #Read/Grab camera frame
        rval, gauge_Img = gauge_Cam.read()
        hud_name = ('HudPicture0.jpg') #Initialize file names
        gauge_name = ('GaugePicture0.jpg')
        cv2.imwrite(hud_name, hud_Img) #Write camera frame to file names
        cv2.imwrite(gauge_name, gauge_Img)
        print("Hud Picture written!") #Log to console
        print("Gauge Picture written!")
        hud_Cam.release() #Release camera resource to clear memory
        gauge_Cam.release()
        stop = timeit.default_timer()
        print('Time: ', stop - start) #Calculate runtime timer
        break
# =============================================================================
    while True:
        img1 = cv2.imread(hud_name)
        img2 = cv2.imread(gauge_name)
        cv2.imshow("Hud Image", img1)
        cv2.imshow("Gauge Image", img2)
        k = cv2.waitKey(60)
        if k%256 == 27:
            cv2.destroyAllWindows()
            break

main(hud_Cam, gauge_Cam, start) #Call camera function```

据我所知,您希望能够在Labview请求后尽快从两个摄像头拍摄两张图像

在Linux或macOS上,我会尽快开始连续捕获,然后使用Unix信号向捕获过程发送信号。不幸的是,您使用的是Windows,信号在那里工作得不太好。因此,我将使用文件系统发出信号——如果Labview想要拍摄照片,它只创建一个名为capture.txt的文件,该文件包含或不包含名为capture.txt的内容,并使Python进程保存当前图像。还有其他更复杂的方法,但这说明了这一概念,随着您了解更多,您可以用套接字写入、MQTT消息或其他方式来替换信令机制

我将两个摄像头放在两个独立的线程中,这样它们可以并行工作,即更快

#!/usr/bin/env python3

import cv2
import threading
import logging
from pathlib import Path

def capture(stream, path):
   """Capture given stream and save to file on demand"""

   # Start capturing to RAM
   logging.info(f'[captureThread]: starting stream {stream}')
   cam = cv2.VideoCapture(stream, cv2.CAP_DSHOW)

   while True:

      # Read video continuously
      _, im = cam.read()

      # Check if Labview wants it
      if CaptureFile.exists():
         # Intermediate filename
         temp = Path(f'saving-{stream}.jpg')

         # Save image with temporary name
         cv2.imwrite(str(temp), im)

         # Rename so Labview knows it is complete and not still being written
         temp.rename(path)

         logging.info(f'[captureThread]: image saved')
         break

   logging.info(f'[captureThread]: done')


if __name__=="__main__":
   # Set up logging - advisable when threading
   format = "%(asctime)s: %(message)s"
   logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
   logging.info("[MAIN]: starting")

   # Labview will create this file when a capture is required, ensure not there already
   CaptureFile = Path('capture.txt')
   CaptureFile.unlink(True)

   # Create a thread for each camera and start them
   HUDthread   = threading.Thread(target=capture, args=(0, Path('HUD.jpg')))
   Gaugethread = threading.Thread(target=capture, args=(1, Path('Gauge.jpg')))
   HUDthread.start()
   Gaugethread.start()

   # Wait for both to exit
   HUDthread.join()
   Gaugethread.join()

   logging.info("[MAIN]: done")

相关问题 更多 >