python开启摄像头以及深度学习实现目标检测方法
作者:红色未来 发布时间:2023-10-27 03:23:18
标签:python,摄像头,目标,检测
最近想做实时目标检测,需要用到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能够下载到)。
来源:https://blog.csdn.net/guofangxiandaihua/article/details/78066323
0
投稿
猜你喜欢
- 今天在写爬虫程序的时候由于要翻页,做除法分页的时候出现了totalCount = '100' totalPage = int
- Python编写从ZabbixAPI获取信息此脚本用Python3.6执行是OK的。# -*- coding: utf-8 -*-impor
- 由于javascript是一种无类型语言,所以一个数组的元素可以具有任意的数据类型,同一个数组的不同元素可以具有不同的类型,数组的元素设置可
- 条件1、能够上网2、必须是你的好友3、必须能二维码登录网页微信发送示例# 使用微信接口给微信好友发送消息,import itchat&nbs
- 拉勾网面试题1. 你首先说出三个不同的特殊数,要求必须是个位数,比如3、5、7。2. 让所有学生拍成一队,然后按顺序报数。3. 学生报数时,
- 本文实例主要是对turtle的使用,实现Python+turtle动态绘制一棵树的实例,具体代码:# drawtree.pyfrom tur
- mapmap(funcname, list)python的map 函数使得函数能直接以list的每个元素作为参数传递到funcname中,
- 为了使一个MySQL系统安全,强烈要求你考虑下列建议……当你连接一个MySQL服务器时,你通常应
- 基于 Snapchat 的增强现实胡子挂件融合第一个项目中,我们将在检测到的脸上覆盖了一个小胡子。我们可以使用从摄像头捕获的连续视频帧,也可
- 前言这篇文章主要介绍了Python 字符串去除空格的6种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,来
- 一、把一个字符串的内容提取出来,并放到字典中流程如下: 1、得到字符串s,通过分割提取得到s1(是个列表) s=”name=lyy&
- ADO对象: Connection Command Recordset Record Stream ASP支持的对象很多,可以自己编写COM
- 游标(Cursor)是处理数据的一种方法,为了查看或者处理结果集中的数据,游标提供了在结果集中一次以行或者多行前进或向后浏览数据的能力。我们
- Jinja2需要Python2.4以上的版本。 安装 按照Jinja有多种方式,你可以根据需要选择不同的按照方式。 使用easy_insta
- 栈(Stack)在计算机领域是一个被广泛应用的集合,栈是线性集合,访问都严格地限制在一段,叫做顶(top)。 举个例子,栈就想一摞洗干净的盘
- 1. 背景最近在爬取某个站点时,发现在POST数据时,使用的数据格式是request payload,有别于之前常见的 POST数据格式(F
- 第一章:霍夫变换检测圆① 实例演示1这个是设定半径范围 0-50 后的效果。② 实例演示2这个是设定半径范围 50-70 后的效果,因为原图
- 就在前几天还是二十多度的舒适温度,今天一下子就变成了个位数,小编已经感受到冬天寒风的无情了。之前对获取天气都是数据上的搜集,做成了一个数据表
- 1. Python字典的clear()方法(删除字典内所有元素)#!/usr/bin/python# -*- coding: UTF-8 -
- 前言;Python bytes 类型用来表示一个字节串。“字节串“不是编程术语,是我自己&l