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设计】。

相关文章

读取json格式为DataFrame(可转为.csv)的实例讲解

有时候需要读取一定格式的json文件为DataFrame,可以通过json来转换或者pandas中的read_json()。 import pandas as pd import j...

python实现俄罗斯方块

网上搜到一个Pygame写的俄罗斯方块(tetris),大部分看懂的前提下增加了注释,Fedora19下运行OK的 主程序: #coding:utf8 #! /usr/bin/env...

使用OpenCV实现仿射变换—旋转功能

使用OpenCV实现仿射变换—旋转功能

在前面实现了平移和缩放,还有一种常用的坐标变换,那就是旋转。比如拍摄的照片上传到电脑里,再打开时发现人的头在下面脚在上,这样肯定看不了,那么就需要把这个照片旋转180度才可以接受。由于旋...

Python3.6日志Logging模块简单用法示例

Python3.6日志Logging模块简单用法示例

本文实例讲述了Python3.6日志Logging模块简单用法。分享给大家供大家参考,具体如下: Logging是一个很方便的模块,用来打印日志 我直接列出一个最灵活的方法 # -*...

python socket网络编程之粘包问题详解

python socket网络编程之粘包问题详解

一,粘包问题详情 1,只有TCP有粘包现象,UDP永远不会粘包 你的程序实际上无权直接操作网卡的,你操作网卡都是通过操作系统给用户程序暴露出来的接口,那每次你的程序要给远程发数据时,...