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中设置变量作为默认值时容易遇到的错误
Apr 03 Python
Python实现优先级队列结构的方法详解
Jun 02 Python
Python搭建FTP服务器的方法示例
Jan 19 Python
python中的随机函数小结
Jan 27 Python
Python用for循环实现九九乘法表
May 31 Python
Django进阶之CSRF的解决
Aug 01 Python
python2.7和NLTK安装详细教程
Sep 19 Python
Python使用random.shuffle()打乱列表顺序的方法
Nov 08 Python
对python中大文件的导入与导出方法详解
Dec 28 Python
Python功能点实现:函数级/代码块级计时器
Jan 02 Python
Python列表删除元素del、pop()和remove()的区别小结
Sep 11 Python
python 调用API接口 获取和解析 Json数据
Sep 28 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 显示客户端IP与服务器IP的代码
2010/10/12 PHP
php中让人头疼的浮点数运算分析
2016/10/10 PHP
Yii实现微信公众号场景二维码的方法实例
2020/08/30 PHP
用javascript获取地址栏参数
2006/12/22 Javascript
jquery下利用jsonp跨域访问实现方法
2010/07/29 Javascript
初窥JQuery(一)jquery选择符 必备知识点
2010/11/25 Javascript
checkbox全选所涉及到的知识点介绍
2013/12/31 Javascript
Javascript中的apply()方法浅析
2015/03/15 Javascript
jQuery操作表单常用控件方法小结
2015/03/23 Javascript
简介JavaScript中fixed()方法的使用
2015/06/08 Javascript
由浅入深讲解Javascript继承机制与simple-inheritance源码分析
2015/12/13 Javascript
javascript中错误使用var造成undefined
2016/03/31 Javascript
javascript加减乘除的简单实例
2016/07/12 Javascript
利用Jquery队列实现根据输入数量显示的动画
2016/09/01 Javascript
写给vue新手们的vue渲染页面教程
2017/09/01 Javascript
简单的Vue SSR的示例代码
2018/01/12 Javascript
快速搭建vue2.0+boostrap项目的方法
2018/04/09 Javascript
微信小程序实现页面浮动导航
2019/01/28 Javascript
python开发之文件操作用法实例
2015/11/13 Python
Python随手笔记之标准类型内建函数
2015/12/02 Python
python简单线程和协程学习心得(分享)
2017/06/14 Python
Python iter()函数用法实例分析
2018/03/17 Python
Python Pandas中根据列的值选取多行数据
2019/07/08 Python
查看Python依赖包及其版本号信息的方法
2019/08/13 Python
python 基于selenium实现鼠标拖拽功能
2020/12/24 Python
《跟踪台风的卫星》教学反思
2014/04/10 职场文书
干部鉴定材料
2014/05/18 职场文书
四风自我剖析材料
2014/09/30 职场文书
党支部反对四风思想汇报
2014/10/10 职场文书
旷课检讨书500字
2014/10/14 职场文书
工作作风建设心得体会
2014/10/22 职场文书
门面房租房协议书
2014/12/01 职场文书
幼儿园开学通知
2015/04/24 职场文书
观看《信仰》心得体会
2016/01/15 职场文书
小数乘法教学反思
2016/02/22 职场文书
详解如何使用Nginx解决跨域问题
2022/05/06 Servers