V4L2采集图片源码分享


把v4l2采集图片测试程序,贴在这和大家共享,在此基础上可以使实现视频的采集,只不过在pc机上写个上位机进行显示或者直接写个Qt在开发板上显示即可。

采集效果如下:

源码如下:

  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <string.h>   
  4. #include <assert.h>   
  5.   
  6. #include <getopt.h>   
  7.   
  8. #include <fcntl.h>   
  9. #include <unistd.h>   
  10. #include <errno.h>   
  11. #include <malloc.h>   
  12. #include <sys/stat.h>   
  13. #include <sys/types.h>   
  14. #include <sys/time.h>   
  15. #include <sys/mman.h>   
  16. #include <sys/ioctl.h>   
  17.   
  18. #include <asm/types.h>   
  19. #include <linux/videodev2.h>   
  20.   
  21. #define CLEAR(x) memset (&(x), 0, sizeof (x))   
  22.   
  23. struct buffer {  
  24. void * start;  
  25. size_t length;  
  26. };  
  27.   
  28. static char * dev_name = "/dev/video0";  
  29. static int fd = -1;  
  30. struct buffer * buffers = NULL;  
  31.   
  32. FILE *file_fd;  
  33. static unsigned long file_length;  
  34. static unsigned char *file_name;  
  35.   
  36. int main (int argc,char ** argv)  
  37. {  
  38. struct v4l2_capability cap;  
  39. struct v4l2_format fmt;  
  40.   
  41. file_fd = fopen("test.jpg""w");  
  42.   
  43. fd = open (dev_name, O_RDWR /* required */ | O_NONBLOCK, 0);  
  44.   
  45. ioctl (fd, VIDIOC_QUERYCAP, &cap);  
  46.   
  47. CLEAR (fmt);  
  48. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;  
  49. fmt.fmt.pix.width = 640;  
  50. fmt.fmt.pix.height = 480;  
  51. fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;  
  52. fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;  
  53. ioctl (fd, VIDIOC_S_FMT, &fmt);  
  54.   
  55. file_length = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;  
  56.   
  57. buffers = calloc (1, sizeof (*buffers));  
  58.   
  59. buffers[0].length = file_length;  
  60. buffers[0].start = malloc (file_length);  
  61.   
  62. for (;;)  
  63. {  
  64. fd_set fds;  
  65. struct timeval tv;  
  66. int r;  
  67.   
  68. FD_ZERO (&fds);  
  69. FD_SET (fd, &fds);  
  70.   
  71. /* Timeout. */  
  72. tv.tv_sec = 3;  
  73. tv.tv_usec = 0;  
  74.   
  75. r = select (fd + 1, &fds, NULL, NULL, &tv);  
  76.   
  77. if (-1 == r) {  
  78. if (EINTR == errno)  
  79. continue;  
  80. printf ("select");  
  81. }  
  82.   
  83. if (0 == r) {  
  84. fprintf (stderr, "select timeout\n");  
  85. exit (EXIT_FAILURE);  
  86. }  
  87.   
  88. if (read (fd, buffers[0].start, buffers[0].length))  
  89. break;  
  90. }  
  91.   
  92. fwrite(buffers[0].start, buffers[0].length, 1, file_fd);  
  93.   
  94. free (buffers[0].start);  
  95. close (fd);  
  96. fclose (file_fd);  
  97. exit (EXIT_SUCCESS);  
  98. return 0;  
  99. }  

相关内容