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中replace方法实例分析

本文以实例形式讲述了Python中replace方法,很有实用价值,具体如下: replace方法主要有两种: last_date = "1/2/3" 目标为"123" 方法一:repa...

Python操作列表的常用方法分享

下面列出列表常用的方法操作列表以及小例子:1.  Append     在列表末尾添加元素,需在列表末尾添加元素,需要注意几个点:&nb...

对于Python深浅拷贝的理解

对于Python深浅拷贝的理解

1,浅拷贝是什么? 浅拷贝是对于一个对象的顶层拷贝,通俗的理解是:拷贝了引用,并没有拷贝内容 通过a=b这种方式赋值只是赋值的引用(内存地址),a和b都指向了同一个内存空间,所...

Python有序字典简单实现方法示例

Python有序字典简单实现方法示例

本文实例讲述了Python有序字典简单实现方法。分享给大家供大家参考,具体如下: 代码: # -*- coding: UTF-8 -*- import collections pri...

对python中的 os.mkdir和os.mkdirs详解

创建目录 在Python中可以使用os.mkdir()函数创建目录(创建一级目录)。 其原型如下所示: os.mkdir(path) 其参数path 为要创建目录的路径。 例如要在...