python开启摄像头以及深度学习实现目标检测方法开启摄像头以及深度学习实现目标检测方法
今天小编就为大家分享一篇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
评论0