python opencv捕获摄像头并显示内容的实现

yipeiwu_com5年前Python基础

1、捕获摄像头和实时显示

import cv2
import numpy as np
import pickle
import matplotlib.pyplot as plt
 
cap = cv2.VideoCapture(0)
 
while True:
  ret,frame = cap.read()
  # Our operations on the frame come 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 done, release the capture
cap.release()
cv2.destroyAllWindows() 

2、从摄像头内抓拍图片

import cv2
import numpy as np
import pickle
import matplotlib.pyplot as plt
 
cap = cv2.VideoCapture(0)
index = 0
while True:
  ret,frame = cap.read()
  # Our operations on the frame come here
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  # Display the resulting frame
  cv2.imshow('frame',gray)
  if cv2.waitKey(1) & 0xFF == ord('p'):
    cv2.imwrite("kk.jpg",frame)
    index = index + 1
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break
 
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows() 

补充:python-----从本地摄像头和网络摄像头截取图片

import cv2

# 获取本地摄像头
# folder_path 截取图片的存储目录
def get_img_from_camera_local(folder_path):
  cap = cv2.VideoCapture(0)
  i = 1
  while True:
    ret, frame = cap.read()
    cv2.imshow("capture", frame)
    print str(i)
    cv2.imwrite(folder_path + str(i) + '.jpg', frame) # 存储为图像
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
    i += 1
  cap.release()
  cv2.destroyAllWindows()

# 获取网络摄像头,格式:rtsp://username:pwd@ip/
# folder_path 截取图片的存储目录
def get_img_from_camera_net(folder_path):
  cap = cv2.VideoCapture('rtsp://username:pwd@ip/')
  i = 1
  while True:
    ret, frame = cap.read()
    cv2.imshow("capture", frame)
    print str(i)
    cv2.imwrite(folder_path + str(i) + '.jpg', frame) # 存储为图像
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
    i += 1
  cap.release()
  cv2.destroyAllWindows()

# 测试
if __name__ == '__main__':
  folder_path = 'D:\\img_from_camera\\'
  get_img_from_camera_local(folder_path)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python素数检测实例分析

本文实例讲述了Python素数检测的方法。分享给大家供大家参考。具体如下: 该程序实现了素数检测器功能,如果结果是true,则是素数,如果结果是false,则不是素数。 def fn...

Python利用matplotlib生成图片背景及图例透明的效果

Python利用matplotlib生成图片背景及图例透明的效果

前言 最近工作中遇到一个需求,在使用matplotlib生成图片,想要背景透明,而且图例部分也显示透明效果,通过查找相关资料找到了大概的设置方法,特此记录,方便自己或者有需要的朋友们参考...

对YOLOv3模型调用时候的python接口详解

对YOLOv3模型调用时候的python接口详解

需要注意的是:更改完源程序.c文件,需要对整个项目重新编译、make install,对已经生成的文件进行更新,类似于之前VS中在一个类中增加新函数重新编译封装dll,而python接口...

python实现飞机大战小游戏

python实现飞机大战小游戏

本文实例为大家分享了python实现飞机大战的具体代码,供大家参考,具体内容如下 初学Python,写了一个简单的Python小游戏。 师出bilibili某前辈 pycharm自带了第...

Python 最大概率法进行汉语切分的方法

要求: 1 采用基于语言模型的最大概率法进行汉语切分。 2 切分算法中的语言模型可以采用n-gram语言模型,要求n >1,并至少采用一种平滑方法; 代码: 废话不说,代码是最好的...