菜单

python开启录制头以及深度学习达成目标检验方法

2019年5月26日 - 金沙编程资讯

近年想抓实时目的检验,必要使用python开启录制头,小编手上唯有七个uvc免驱的摄像头,质量一般。利用python开启拍戏头费了一番武功,主因是自己的摄像头都无法用cv二的VideCapture展开,那让自己联想到原来opencv也打不开Android手提式有线电话机上的摄像头(后来选取QML的Camera模块完结的)。看来opencv对于录像头的包容性还是否很周到。

本身尝了三种艺术:v四l二,v4l2_capture以及simpleCV,都打不开。最后动用pygame实现了摄像头的采访成效,这里一贯给大家享受具体实当代码(python三.6,cv二,opencv叁.3,ubuntu1六.0四)。中间注释的一部分是自己上述措施展开摄像头的尝试,说不定有契合自个儿的。

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来贯彻,注意这五个函数在opencv三+后就消失了。由此利用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开启录像头以及深度学习完成指标检测方法正是作者分享给大家的全体内容了,希望能给我们一个参照,也期待我们多多协助脚本之家。

你大概感兴趣的稿子:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图