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实现ID3决策树算法
Dec 20 Python
Python实现的堆排序算法示例
Apr 29 Python
python实现反转部分单向链表
Sep 27 Python
python采集微信公众号文章
Dec 20 Python
感知器基础原理及python实现过程详解
Sep 30 Python
python实现XML解析的方法解析
Nov 16 Python
Django Path转换器自定义及正则代码实例
May 29 Python
Python3 socket即时通讯脚本实现代码实例(threading多线程)
Jun 01 Python
python Cartopy的基础使用详解
Nov 01 Python
Python之qq自动发消息的示例代码
Feb 18 Python
Python将CSV文件转化为HTML文件的操作方法
Jun 30 Python
基于PyQT5制作一个桌面摸鱼工具
Feb 15 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
mcrypt启用 加密以及解密过程详细解析
2013/08/07 PHP
ThinkPHP实现二级循环读取的方法
2014/11/03 PHP
thinkPHP删除前弹出确认框的简单实现方法
2016/05/16 PHP
YII2框架中excel表格导出的方法详解
2017/07/21 PHP
基于JS实现简单的样式切换效果代码
2015/09/04 Javascript
JS修改地址栏参数实例代码
2016/06/14 Javascript
BootStrap+Angularjs+NgDialog实现模式对话框
2016/08/24 Javascript
javascript实现用户点击数量统计
2016/12/25 Javascript
浅谈js中function的参数默认值
2017/02/20 Javascript
jquery Easyui Datagrid实现批量操作(编辑,删除,添加)
2017/02/20 Javascript
js获取文件里面的所有文件名(实例)
2017/10/17 Javascript
vue的token刷新处理的方法
2018/07/17 Javascript
解决vue中post方式提交数据后台无法接收的问题
2018/08/11 Javascript
JavaScript实现动态添加、移除元素或属性的方法分析
2019/01/03 Javascript
微信小程序开发实现的选项卡(窗口顶部/底部TabBar)页面切换功能图文详解
2019/05/14 Javascript
详解Vue项目引入CreateJS的方法(亲测可用)
2019/05/30 Javascript
Vue 开发必须知道的36个技巧(小结)
2019/10/09 Javascript
详解Django中的ifequal和ifnotequal标签使用
2015/07/16 Python
Python如何实现文本转语音
2016/08/08 Python
django定期执行任务(实例讲解)
2017/11/03 Python
Python实现替换文件中指定内容的方法
2018/03/19 Python
Python爬取视频(其实是一篇福利)过程解析
2019/08/01 Python
python3中使用__slots__限定实例属性操作分析
2020/02/14 Python
keras .h5转移动端的.tflite文件实现方式
2020/05/25 Python
详解Python IO口多路复用
2020/06/17 Python
Nike比利时官网:Nike.com (BE)
2019/02/07 全球购物
四年的大学生生活自我评价
2013/12/09 职场文书
党员教师工作决心书
2014/03/13 职场文书
走群众路线学习笔记
2014/11/06 职场文书
2014年销售助理工作总结
2014/12/01 职场文书
2014年教研室工作总结
2014/12/06 职场文书
2014年留守儿童工作总结
2014/12/10 职场文书
语文教师求职信范文
2015/03/20 职场文书
2015仓库保管员年终工作总结
2015/05/13 职场文书
上诉答辩状范文
2015/05/22 职场文书
2015年四年级班主任工作总结
2015/10/22 职场文书