最近想做实时目标检测,需要用到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开启摄像头以及深度学习实现目标检测方法相关推荐

  1. python成绩统计及格学平成_基于深度学习的目标检测算法综述

    导言目标检测的任务是找出图像中所有感兴趣的目标(物体),确定它们的位置和大小,是机器视觉领域的核心问题之一.由于各类物体有不同的外观,形状,姿态,加上成像时光照,遮挡等因素的干扰,目标检测一直是机器视 ...

  2. CV:基于深度学习实现目标检测之GUI界面产品设计并实现图片识别、视频识别、摄像头识别(准确度非常高)

    CV:基于深度学习实现目标检测之GUI界面产品设计并实现图片识别.视频识别.摄像头识别(准确度非常高) 目录 GUI编程设计界面 产品演示 GUI编程设计界面 产品演示 视频演示:https://bl ...

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

    最近想做实时目标检测,需要用到python开启摄像头,我手上只有两个uvc免驱的摄像头,性能一般.利用python开启摄像头费了一番功夫,主要原因是我的摄像头都不能用cv2的VideCapture打开 ...

  4. 深度学习和目标检测系列教程 15-300:在 Python 中使用 OpenCV 执行 YOLOv3 对象检测

    @Author:Runsen 上次讲了yolov3,这是使用yolov3的模型通过opencv的摄像头来执行YOLOv3 对象检测. 导入所需模块: import cv2 import numpy a ...

  5. 【深度学习】目标检测实战:4种YOLO目标检测的C++和Python两种版本实现

    作者丨nihate 审稿丨邓富城 编辑丨极市平台 导读 本文作者使用C++编写一套基于OpenCV的YOLO目标检测,包含了经典的YOLOv3,YOLOv4,Yolo-Fastest和YOLObile ...

  6. 基于深度学习的水果检测与识别系统(Python界面版,YOLOv5实现)

    摘要:本博文介绍了一种基于深度学习的水果检测与识别系统,使用YOLOv5算法对常见水果进行检测和识别,实现对图片.视频和实时视频中的水果进行准确识别.博文详细阐述了算法原理,同时提供Python实现代 ...

  7. python 使用OpenCV2打开本地及网络摄像头本地及网络视频

    ''' python 使用OpenCV2打开本地及网络摄像头&本地及网络视频 by 郑瑞国 ''' import cv2user, pwd, ip, channel = "admin ...

  8. 一个雷达和摄像头融合的3D目标检测方法CenterFusion

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 本文转自:计算机视觉工坊 以前提到过此文(在想法中),WACV'2 ...

  9. 基于深度学习的花卉检测与识别系统(YOLOv5清新界面版,Python代码)

    摘要:基于深度学习的花卉检测与识别系统用于常见花卉识别计数,智能检测花卉种类并记录和保存结果,对各种花卉检测结果可视化,更加方便准确辨认花卉.本文详细介绍花卉检测与识别系统,在介绍算法原理的同时,给出 ...

最新文章

  1. 使用 sched_setaffinity 将线程绑到CPU核上运行
  2. Oracle表分区详细说明
  3. Swift教程Swift语言快速入门(内部资料)
  4. python学精通要多久-python多久能精通
  5. basler相机 ip linux,Linux环境中连接Basler相机(Pylon软件的安装),ROS环境中连接Basler相机...
  6. c html联调,JS与native 交互简单应用
  7. Wireshark笔记-ping,arp相关的实验(2台主机是否能通)
  8. 南京张治中故居违规重建后标价6400万元出售
  9. 9道微服务面试题,你能回答上来几个?
  10. 导航网/广告位/导航分类/可运营
  11. 干涉测量技术的应用_特殊工程的施工测量技术应用分享
  12. iPhone 与 Mac 怎么同步?同步有什么用
  13. 一文了解 TKG 如何使用 GPU 资源池
  14. DBMS_AW_EXP: BIN$XXXXXXX==$0 not AW$
  15. IOTOS通采盒为BIM运维、GIS、CIM、数字孪生及IBMS高效率、低成本打通数据,接入楼宇园区子系统设备
  16. PyTorch 2.0来了!100%向后兼容,一行代码训练提速76%
  17. SVM支持向量机原理
  18. REST是什么(转)
  19. gdpr隐私保护_GDPR来袭,你知道如何保护个人和企业的隐私吗?(第2期)
  20. GISer还有机会屌丝逆袭吗?

热门文章

  1. 致江苏卫视《最强大脑第二季》节目组的一封信
  2. 如何改变视频的MD5值?一分钟让你学会操作
  3. 服务器增加路由的命令行,服务器命令行配置路由和ip
  4. 从零开始开发IM(即时通讯)服务端(一)附源码
  5. Android LCD整理二:mtk平台LCD流程分析(LK部分)
  6. 紫光同创国产FPGA学习之Fabric Configuration
  7. VC++ 防火墙 Win7 XP MFC
  8. C++ string乱码可能解决方案
  9. 电容式咪头气动感应开关工作原理及优点
  10. e480换高分屏_四世同堂,12年一轮回,再赏ThinkPad机型