在使用python中的cv2多线程循环对两个摄像头采集图像的过程中发现各自单线程运转正常,多线程就会TypeError

具体程序如下

import cv2
import numpy as np

def xunhuangetimage1():
    folder_path = 'D:\image2\picture'  # 在image2文件夹生成循环截图成果
    cap = cv2.VideoCapture(1, cv2.CAP_DSHOW)
    i=0
    while i<400:
        ret, frame = cap.read()
        cropped = frame[316:345, 114:141]
        gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
        ret, thresh1 = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
        cv2.imwrite(folder_path + str(i) + '.jpg', thresh1)  # 存储为图像
        i+=1
    cap.release()
    cv2.destroyAllWindows()
def xunhuangetimage2():
    folder_path = 'D:\image3\picture'  # 在image3文件夹生成循环截图成果
    cap2 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    j=0
    while j<400:
        ret2, frame2 = cap2.read()
        cropp2 = frame2[265:300, 161:190]
        cropped2 = np.rot90(cropp2, 3)
        gray2 = cv2.cvtColor(cropped2, cv2.COLOR_BGR2GRAY)
        ret2, thresh2 = cv2.threshold(gray2, 240, 255, cv2.THRESH_BINARY)
        cv2.imwrite(folder_path + str(j) + '.jpg', thresh2)  # 存储为图像
        j+=1
    cap2.release()
    cv2.destroyAllWindows()
import threading
p1 = threading.Thread(target=xunhuangetimage1, args=())#同时运行循环和截图功能,摄像头一进行循环采集图片操作
p2 = threading.Thread(target=xunhuangetimage2, args=())#摄像头二进行循环采集图片操作 
p1.start()
p2.start()

两个函数各自单独运行是能达到预期效果的,但一旦多线程工作就会报如下错误


Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "D:/pythonProject/循环截图.py", line 10, in xunhuangetimage1
    cropped = frame[316:345, 114:141]
TypeError: 'NoneType' object is not subscriptable
Exception in thread Thread-6:
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner
    self.run()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "D:/pythonProject/循环截图.py", line 10, in xunhuangetimage1
    cropped = frame[316:345, 114:141]
TypeError: 'NoneType' object is not subscriptable

Process finished with exit code -1

能请问大家这是哪里出了问题,该怎么修改么?

xunhuangetimage1函数中VideoCapture打开的1通道摄像头存在吗,单独运行xunhuangetimage1报错吗,我这里实验,两个摄像头,不保错

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632