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 相关文章推荐
pandas 实现将重复表格去重,并重新转换为表格的方法
Apr 18 Python
Python在groupby分组后提取指定位置记录方法
Apr 20 Python
python通过zabbix api获取主机
Sep 17 Python
python 处理数字,把大于上限的数字置零实现方法
Jan 28 Python
Django自定义全局403、404、500错误页面的示例代码
Mar 08 Python
Python读写操作csv和excle文件代码实例
Mar 16 Python
动态设置django的model field的默认值操作步骤
Mar 30 Python
Python将二维列表list的数据输出(TXT,Excel)
Apr 23 Python
让Django的BooleanField支持字符串形式的输入方式
May 20 Python
如何基于Python Matplotlib实现网格动画
Jul 20 Python
python opencv实现图像配准与比较
Feb 09 Python
详解pandas apply 并行处理的几种方法
Feb 24 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从数组中删除元素的四种方法实例
2017/05/12 PHP
基于jquery+thickbox仿校内登录注册框
2010/06/07 Javascript
JS控制文本框textarea输入字数限制的方法
2013/06/17 Javascript
jQuery中RadioButtonList的功能及用法实例介绍
2013/08/23 Javascript
使用js检测浏览器是否支持html5中的video标签的方法
2014/03/12 Javascript
JQuery EasyUI 日期控件如何控制日期选择区间
2014/05/05 Javascript
jquery引用方法时传递参数原理分析
2014/10/13 Javascript
jQuery子窗体取得父窗体元素的方法
2015/05/11 Javascript
JQuery标签页效果的两个实例讲解(4)
2015/09/17 Javascript
快速学习jQuery插件 Form表单插件使用方法
2015/12/01 Javascript
基于Vue2的移动端开发环境搭建详解
2016/11/03 Javascript
js自制图片放大镜功能
2017/01/24 Javascript
利用Vue.js实现求职在线之职位查询功能
2017/07/03 Javascript
JavaScript+HTML5实现的日期比较功能示例
2017/07/12 Javascript
js中getBoundingClientRect的作用及兼容方案详解
2018/02/01 Javascript
Node.js+Vue脚手架环境搭建的方法步骤
2020/03/08 Javascript
JS实现选项卡插件的两种写法(jQuery和class)
2020/12/30 jQuery
[01:12:40]DOTA2-DPC中国联赛 正赛 DLG vs XG BO3 第三场 1月25日
2021/03/11 DOTA
Python实现读取邮箱中的邮件功能示例【含文本及附件】
2017/08/05 Python
python logging重复记录日志问题的解决方法
2018/07/12 Python
Python Flask前后端Ajax交互的方法示例
2018/07/31 Python
详解python websocket获取实时数据的几种常见链接方式
2019/07/01 Python
python mysql断开重连的实现方法
2019/07/26 Python
Python列表list常用内建函数实例小结
2019/10/22 Python
利用Python裁切tiff图像且读取tiff,shp文件的实例
2020/03/10 Python
pip已经安装好第三方库但pycharm中import时还是标红的解决方案
2020/10/09 Python
详解通过HTML5 Canvas实现图片的平移及旋转变化的方法
2016/03/22 HTML / CSS
丝芙兰加拿大官方网站:SEPHORA加拿大
2018/11/20 全球购物
Vita Fede官网:在意大利手工制作,在纽约市设计
2019/10/25 全球购物
将"引用"作为函数返回值类型的格式、好处和需要遵守的规则
2016/02/09 面试题
个人素质的自我评价分享
2013/12/16 职场文书
室内设计专业个人的自我评价
2013/12/18 职场文书
2014学雷锋活动心得体会
2014/03/10 职场文书
产品设计开发计划书
2014/05/07 职场文书
安全生产标语
2014/06/06 职场文书
Golang全局变量加锁的问题解决
2021/05/08 Golang