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 正则表达式操作指南
May 04 Python
python类型强制转换long to int的代码
Feb 10 Python
浅谈python 里面的单下划线与双下划线的区别
Dec 01 Python
python实现爬取图书封面
Jul 05 Python
对python内置map和six.moves.map的区别详解
Dec 19 Python
pyqt5 删除layout中的所有widget方法
Jun 25 Python
使用 Python 处理3万多条数据只要几秒钟
Jan 19 Python
flask 框架操作MySQL数据库简单示例
Feb 02 Python
matplotlib.pyplot.plot()参数使用详解
Jul 28 Python
Anaconda使用IDLE的实现示例
Sep 23 Python
python制作抽奖程序代码详解
Jan 15 Python
python 可视化库PyG2Plot的使用
Jan 21 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
Pain 全世界最小最简单的PHP模板引擎 (普通版)
2011/10/23 PHP
php删除页面记录 同时刷新页面 删除条件用GET方式获得
2012/01/10 PHP
使用PHP下载CSS文件中的图片的代码
2013/09/24 PHP
PHP中使用虚代理实现延迟加载技术
2014/11/05 PHP
PHP如何实现阿里云短信sdk灵活应用在项目中的方法
2019/06/14 PHP
csdn 博客的css样式 v3
2009/02/24 Javascript
简易js代码实现计算器操作
2013/04/15 Javascript
node.js不得不说的12点内容
2014/07/14 Javascript
js cookie实现记住密码功能
2017/01/17 Javascript
javascript中mouseenter与mouseover的异同
2017/06/06 Javascript
Vue2.0基于vue-cli+webpack父子组件通信(实例讲解)
2017/09/14 Javascript
详解vue组件基础
2018/05/04 Javascript
Vue使用高德地图搭建实时公交应用功能(地图 + 附近站点+线路详情 + 输入提示+换乘详情)
2018/05/16 Javascript
layui点击按钮添加可编辑的一行方法
2018/08/15 Javascript
详解Nuxt.js 实战集锦
2019/11/19 Javascript
[01:04:32]DOTA2-DPC中国联赛 正赛 Aster vs LBZS BO3 第二场 2月23日
2021/03/11 DOTA
使用Python解析JSON数据的基本方法
2015/10/15 Python
python如何派生内置不可变类型并修改实例化行为
2018/03/21 Python
python实现狄克斯特拉算法
2019/01/17 Python
解决pycharm的Python console不能调试当前程序的问题
2019/01/20 Python
对pandas通过索引提取dataframe的行方法详解
2019/02/01 Python
python网络爬虫 Scrapy中selenium用法详解
2019/09/28 Python
Pytorch中实现只导入部分模型参数的方式
2020/01/02 Python
python让函数不返回结果的方法
2020/06/22 Python
Tensorflow全局设置可见GPU编号操作
2020/06/30 Python
详解HTML5布局和HTML5标签
2020/10/26 HTML / CSS
美体小铺加拿大官方网站:The Body Shop加拿大
2016/10/30 全球购物
应届生个人求职信模板
2013/11/26 职场文书
教师考核材料
2014/05/21 职场文书
国庆节演讲稿
2014/05/27 职场文书
党建工作目标管理责任书
2015/01/29 职场文书
家长意见和建议怎么写
2015/06/04 职场文书
欧也妮葛朗台读书笔记
2015/06/30 职场文书
2016年秋季运动会加油稿
2015/12/21 职场文书
教你怎么用python实现字符串转日期
2021/05/24 Python
mysq启动失败问题及场景分析
2021/07/15 MySQL