我是一个使用python的新人,并尝试使用线程捕获屏幕(win32gui)和相机图像(opencv)。但是我的代码速度不够快,无法捕获图像。 当脚本在单个线程上工作时,帧速率正常(大约30fps)。但是当两个线程启动时帧速率下降到10fps。我该怎么做才能将帧速率提高到30 fps? 我的笔记本电脑是赢64,i7-5500U,RAM 32GB,python 2.7(32位)。相机是逻辑网络摄像头C905。
import win32gui, win32ui, win32con
import cv2
import os
import datetime, time
import threading
def screen_capture(saveDC, mfcDC, w, h):
SaveDirectory = r'C:\Users\Desktop\1'
start_time = time.time()
end_time = time.time()
while (end_time - start_time < 8):
saveDC.BitBlt((0, 0), (w, h), mfcDC, (300, 400), win32con.SRCCOPY)
bmpname = os.path.join(SaveDirectory, str(datetime.datetime.now()).replace(':', '-') + '.bmp')
saveBitMap.SaveBitmapFile(saveDC, bmpname)
end_time = time.time()
def camera_image(cap):
dirname = 'C:/Users/Desktop/2'
start_time = time.time()
end_time = time.time()
while(end_time - start_time < 8):
# Capture frame-by-frame
ret, frame = cap.read()
# cv2.imshow('frame', frame)
timestamp = str(datetime.datetime.now()).replace(':', '-')
cv2.imwrite(os.path.join(dirname, timestamp + ".jpg"), frame)
end_time = time.time()
cap = cv2.VideoCapture(0)
ret = cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 960) # width
cap.set(4, 720) # Height
cap.set(cv2.cv.CV_CAP_PROP_FPS, 90) # Frame rate
w = 1500
h = 900
hwnd = win32gui.GetDesktopWindow()
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
t1 = threading.Thread(name=camera_image, target=camera_image, args=(cap,))
t2 = threading.Thread(name=screen_capture, target=screen_capture, args=(saveDC, mfcDC, w, h,))
t1.start()
t2.start()