歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> V4L2采集圖片源碼分享

V4L2采集圖片源碼分享

日期:2017/3/1 10:30:00   编辑:Linux編程

把v4l2采集圖片測試程序,貼在這和大家共享,在此基礎上可以使實現視頻的采集,只不過在pc機上寫個上位機進行顯示或者直接寫個Qt在開發板上顯示即可。

采集效果如下:

源碼如下:

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