Reading camera input from /dev/video0 in python or c

时间:2015-06-25 18:55:55

标签: python c linux

I want to read from the file /dev/video0 either through c or python,and store the incoming bytes in a different file. Here is my c code: #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int fd,wfd; fd=open("/dev/video0",O_RDONLY); wfd=open("image",O_RDWR|O_CREAT|O_APPEND,S_IRWXU); if(fd==-1) perror("open"); while(1) { char buffer[50]; int rd; rd=read(fd,buffer,50); write(wfd,buffer,rd); } return 0; } When i run this code and after some time terminate the program nothing happens except a file name "image" is generated which is usual. This is my python code: image=open("/dev/video0","rb") image.read() and this is my error when my run this snippet: Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 22] Invalid argument I want to know how to do this using pure c or python code.Please no external library suggestions.

2 个答案:

答案 0 :(得分:1)

这并不容易。

  1. 大多数相机无法在读/写模式下工作。您需要使用Streaming I/O mode - 例如内存映射。
  2. 您需要设置pixel format - YUYV / RGB / MJPEG,每像素字节数,分辨率。
  3. 你必须开始抓取,阅读并保存至少一帧。

答案 1 :(得分:0)

继我的评论之后,这里有一个从磁盘上的视频显示视频流的示例(请参阅documentation):

import numpy as np
import cv2

video = "../videos/short.avi"

video_capture = cv2.VideoCapture(video)

while(True):
    # Capture frame-by-frame
    ret, frame = video_capture.read()

    # Our operations on the frame comes here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything's done, release the capture
video_capture.release()
cv2.destroyAllWindows()