在相同类OpenCV Python中的两个不同函数中使用VideoCapture()

时间:2018-05-29 09:47:32

标签: python opencv

我正在制作一个GUI,其中一个按钮将显示视频,另一个按钮将开始以特定间隔从该视频捕获帧。

这里是按钮调用的函数: -

def capture(self):
    global img_location
    global camera

    camera = cv2.VideoCapture(1)
    return_value, image = camera.read()
    time.sleep(2)   #set the delay you want in frame
    now_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())

    img_location = './timelapse_focus/'+FolderName+'/'+ now_time +'.jpg'
    cv2.imwrite(img_location, image)
    del(camera)


def display(self):
    # Create a VideoCapture object and read from input file
    # If the input is the camera, pass 0 instead of the video file name

    # Check if camera opened successfully
    camera = cv2.VideoCapture(1)
    if (camera.isOpened()== False): 
      print("Error opening video stream or file")

    # Read until video is completed
    while(camera.isOpened()):
      # Capture frame-by-frame
      ret, frame = camera.read()
      if ret == True:

        # Display the resulting frame
        cv2.imshow('Frame',frame)

        # Press <q> on keyboard to  exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
          break

      # Break the loop
      else: 
        break

    # When everything done, release the video capture object
    camera.release()

    # Closes all the frames
    cv2.destroyAllWindows()
    for i in range (1,5):
        cv2.waitKey(1)

它显示以下错误: -

HIGHGUI ERROR: V4L2: Pixel format of incoming image is unsupported by OpenCV
VIDIOC_STREAMON: Bad file descriptor
Unable to stop the stream.: Bad file descriptor

为了做同样的事情,我试图全局声明相机变量。 但它不起作用。即使我使用self. camera,它也无效。 请提出建议。

1 个答案:

答案 0 :(得分:0)

此处的问题是您尝试在cv2.VideoCapture(1)display(self)中同时打开capture(self)。在frame中将self.frame设置为display(self),并在capture(self)中使用它。像这样:

def capture(self):

    time.sleep(2)   #set the delay you want in frame
    now_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())

    img_location = './timelapse_focus/'+FolderName+'/'+ now_time +'.jpg'
    cv2.imwrite(img_location, self.frame)



def display(self):
    # Create a VideoCapture object and read from input file
    # If the input is the camera, pass 0 instead of the video file name

    # Check if camera opened successfully
    camera = cv2.VideoCapture(1)
    if (camera.isOpened()== False): 
       print("Error opening video stream or file")

    # Read until video is completed
    while(camera.isOpened()):
      # Capture frame-by-frame
      ret, self.frame = self.camera.read()
      if ret == True:

        # Display the resulting frame
        cv2.imshow('Frame',self.frame)

        # Press <q> on keyboard to  exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
          break

      # Break the loop
      else: 
    break

    # When everything done, release the video capture object
    camera.release()

    # Closes all the frames
    cv2.destroyAllWindows()
    for i in range (1,5):
        cv2.waitKey(1)

这仅用于每次调用capture(self)时捕获一帧。否则,您需要在Thread中添加while循环和方法,以免崩溃GUI。