python开启摄像头以及深度学习实现目标检测方法


Posted in Python onAugust 03, 2018

最近想做实时目标检测,需要用到python开启摄像头,我手上只有两个uvc免驱的摄像头,性能一般。利用python开启摄像头费了一番功夫,主要原因是我的摄像头都不能用cv2的VideCapture打开,这让我联想到原来opencv也打不开Android手机上的摄像头(后来采用QML的Camera模块实现的)。看来opencv对于摄像头的兼容性仍然不是很完善。

我尝了几种办法:v4l2,v4l2_capture以及simpleCV,都打不开。最后采用pygame实现了摄像头的采集功能,这里直接给大家分享具体实现代码(python3.6,cv2,opencv3.3,ubuntu16.04)。中间注释的部分是我上述方法打开摄像头的尝试,说不定有适合自己的。

import pygame.camera
import time
import pygame
import cv2
import numpy as np
 
def surface_to_string(surface):
 """convert pygame surface into string"""
 return pygame.image.tostring(surface, 'RGB')
 
def pygame_to_cvimage(surface):
 """conver pygame surface into cvimage"""
 
 #cv_image = np.zeros(surface.get_size, np.uint8, 3)
 image_string = surface_to_string(surface)
 image_np = np.fromstring(image_string, np.uint8).reshape(480, 640, 3)
 frame = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
 return image_np, frame
 
 
pygame.camera.init()
pygame.camera.list_cameras()
cam = pygame.camera.Camera("/dev/video0", [640, 480])
 
cam.start()
time.sleep(0.1)
screen = pygame.display.set_mode([640, 480])
 
while True:
 image = cam.get_image()
 
 cv_image, frame = pygame_to_cvimage(image)
 
 screen.fill([0, 0, 0])
 screen.blit(image, (0, 0))
 pygame.display.update()
 cv2.imshow('frame', frame)
 key = cv2.waitKey(1)
 if key & 0xFF == ord('q'):
  break
 
 
 #pygame.image.save(image, "pygame1.jpg")
 
cam.stop()

上述代码需要注意一个地方,就是pygame图片和opencv图片的转化(pygame_to_cvimage)有些地方采用cv.CreateImageHeader和SetData来实现,注意这两个函数在opencv3+后就消失了。因此采用numpy进行实现。

至于目标检测,由于现在网上有很多实现的方法,MobileNet等等。这里我不讲解具体原理,因为我的研究方向不是这个,这里直接把代码贴出来,亲测成功了。

from imutils.video import FPS
import argparse
import imutils
 
 
import v4l2
import fcntl
 
import v4l2capture
import select
import image
 
import pygame.camera
import pygame
import cv2
import numpy as np
import time
 
def surface_to_string(surface):
 """convert pygame surface into string"""
 return pygame.image.tostring(surface, 'RGB')
 
def pygame_to_cvimage(surface):
 """conver pygame surface into cvimage"""
 
 #cv_image = np.zeros(surface.get_size, np.uint8, 3)
 image_string = surface_to_string(surface)
 image_np = np.fromstring(image_string, np.uint8).reshape(480, 640, 3)
 frame = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
 return frame
 
 
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True, help="path to caffe deploy prototxt file")
ap.add_argument("-m", "--model", required=True, help="path to caffe pretrained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detection")
args = vars(ap.parse_args())
 
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
   "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
 
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
 
 
print("[INFO] starting video stream ...")
 
###### opencv ########
#vs = VideoStream(src=1).start()
#
#camera = cv2.VideoCapture(0)
#if not camera.isOpened():
# print("camera is not open")
#time.sleep(2.0)
 
 
###### v4l2 ########
 
#vd = open('/dev/video0', 'r')
#cp = v4l2.v4l2_capability()
#fcntl.ioctl(vd, v4l2.VIDIOC_QUERYCAP, cp)
 
#cp.driver
 
 
##### v4l2_capture
#video = v4l2capture.Video_device("/dev/video0")
#size_x, size_y = video.set_format(640, 480, fourcc= 'MJPEG')
#video.create_buffers(30)
 
#video.queue_all_buffers()
 
#video.start()
 
##### pygame ####
pygame.camera.init()
pygame.camera.list_cameras()
cam = pygame.camera.Camera("/dev/video0", [640, 480])
 
cam.start()
time.sleep(1)
 
fps = FPS().start()
 
 
while True:
 #try:
 # frame = vs.read()
 #except:
 # print("camera is not opened")
 
 #frame = imutils.resize(frame, width=400)
 #(h, w) = frame.shape[:2]
 
 
 #grabbed, frame = camera.read()
 #if not grabbed:
 # break
 #select.select((video,), (), ())
 #frame = video.read_and_queue()
 
 #npfs = np.frombuffer(frame, dtype=np.uint8)
 #print(len(npfs))
 #frame = cv2.imdecode(npfs, cv2.IMREAD_COLOR)
 
 image = cam.get_image()
 frame = pygame_to_cvimage(image)
 
 frame = imutils.resize(frame, width=640)
 blob = cv2.dnn.blobFromImage(frame, 0.00783, (640, 480), 127.5)
 
 net.setInput(blob)
 detections = net.forward()
 
 for i in np.arange(0, detections.shape[2]):
 
  confidence = detections[0, 0, i, 2]
 
  if confidence > args["confidence"]:
 
   idx = int(detections[0, 0, i, 1])
   box = detections[0, 0, i, 3:7]*np.array([640, 480, 640, 480])
   (startX, startY, endX, endY) = box.astype("int")
 
   label = "{}:{:.2f}%".format(CLASSES[idx], confidence*100)
   cv2.rectangle(frame, (startX, startY), (endX, endY), COLORS[idx], 2)
   y = startY - 15 if startY - 15 > 15 else startY + 15
 
   cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
 
 cv2.imshow("Frame", frame)
 key = cv2.waitKey(1)& 0xFF
 
 if key ==ord("q"):
  break
 
 
fps.stop()
print("[INFO] elapsed time :{:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS :{:.2f}".format(fps.fps()))
 
 
 
cv2.destroyAllWindows()
 
#vs.stop()

上面的实现需要用到两个文件,是caffe实现好的模型,我直接上传(文件名为MobileNetSSD_deploy.caffemodel和MobileNetSSD_deploy.prototxt,上google能够下载到)。

以上这篇python开启摄像头以及深度学习实现目标检测方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
简单介绍Python中的try和finally和with方法
May 05 Python
在Python中使用mechanize模块模拟浏览器功能
May 05 Python
Python中的pass语句使用方法讲解
May 14 Python
Python科学计算之NumPy入门教程
Jan 15 Python
python ddt实现数据驱动
Mar 14 Python
使用python读取csv文件快速插入数据库的实例
Jun 21 Python
如何用C代码给Python写扩展库(Cython)
May 17 Python
python flask几分钟实现web服务的例子
Jul 26 Python
python数据持久存储 pickle模块的基本使用方法解析
Aug 30 Python
给 TensorFlow 变量进行赋值的方式
Feb 10 Python
Python中使用aiohttp模拟服务器出现错误问题及解决方法
Oct 31 Python
pycharm配置python 设置pip安装源为豆瓣源
Feb 05 Python
Python函数参数操作详解
Aug 03 #Python
利用python打开摄像头及颜色检测方法
Aug 03 #Python
numpy添加新的维度:newaxis的方法
Aug 02 #Python
numpy.ndarray 交换多维数组(矩阵)的行/列方法
Aug 02 #Python
对numpy中的transpose和swapaxes函数详解
Aug 02 #Python
Numpy 改变数组维度的几种方法小结
Aug 02 #Python
python 字典中取值的两种方法小结
Aug 02 #Python
You might like
一篇不错的PHP基础学习笔记
2007/03/18 PHP
thinkphp分页集成实例
2017/07/24 PHP
使用 laravel sms 构建短信验证码发送校验功能
2017/11/06 PHP
datePicker——日期选择控件(with jquery)
2007/02/20 Javascript
jquery下json数组的操作实现代码
2010/08/09 Javascript
JavaScript/jQuery 表单美化插件小结
2012/02/14 Javascript
js Date概念详细介绍
2013/11/22 Javascript
JS获取屏幕,浏览器窗口大小,网页高度宽度(实现代码)
2013/12/17 Javascript
浏览器窗口加载和大小改变事件示例
2014/02/27 Javascript
js触发onchange事件的方法说明
2014/03/08 Javascript
jQuery控制网页打印指定区域的方法
2015/04/07 Javascript
jquery制作属于自己的select自定义样式
2015/11/23 Javascript
nodejs redis 发布订阅机制封装实现方法及实例代码
2016/12/15 NodeJs
js实现导航栏中英文切换效果
2017/01/16 Javascript
ajax 提交数据到后台jsp页面及页面跳转问题
2017/01/19 Javascript
微信小程序 滚动到某个位置添加class效果实现代码
2017/04/19 Javascript
基于jQuery Ajax实现下拉框无刷新联动
2017/12/06 jQuery
create-react-app 修改为多入口编译的方法
2018/08/01 Javascript
在vue中使用setInterval的方法示例
2019/04/16 Javascript
Vue.js中该如何自己维护路由跳转记录
2019/05/19 Javascript
JavaScript变量作用域及内存问题实例分析
2019/06/10 Javascript
JavaScript迭代器的含义及用法
2019/06/21 Javascript
微信小程序页面渲染实现方法
2019/11/06 Javascript
微信小程序地图绘制线段并且测量(实例代码)
2020/01/02 Javascript
Python实现对文件进行单词划分并去重排序操作示例
2018/07/10 Python
python暴力解压rar加密文件过程详解
2019/07/05 Python
使用matlab 判断两个矩阵是否相等的实例
2020/05/11 Python
Python在centos7.6上安装python3.9的详细教程(默认python版本为2.7.5)
2020/10/15 Python
曼城官方网上商店:Manchester City
2019/09/10 全球购物
路德维希•贝克(LUDWIG BECK)中文官网:德国大型美妆百货
2020/09/19 全球购物
C#如何调用Word并打开一个Word文档
2013/05/08 面试题
销售人员自我评价怎么写
2013/09/19 职场文书
钱学森电影观后感
2015/06/04 职场文书
追悼会悼词大全
2015/06/23 职场文书
教师远程培训心得体会
2016/01/09 职场文书
详解如何用Python实现感知器算法
2021/06/18 Python