欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python+opencv+caffe+摄像头做目标检测的实例代码

程序员文章站 2022-04-27 23:17:14
首先之前已经成功的使用python做图像的目标检测,这回因为项目最终是需要用摄像头的, 所以实现摄像头获取图像,并且用python调用caffe接口来实现目标识别 首先...

首先之前已经成功的使用python做图像的目标检测,这回因为项目最终是需要用摄像头的,

所以实现摄像头获取图像,并且用python调用caffe接口来实现目标识别

首先是摄像头请选择支持linux万能驱动兼容v4l2的摄像头,

因为之前用学arm的时候使用的smart210,我已经确认我的摄像头是支持的,

我把摄像头插上之後自然就在 /dev 目录下看到多了一个video0的文件,

这个就是摄像头的设备文件了,所以我就没有额外处理驱动的部分

一、检测环境

再来在开始前因为之前按着国嵌的指导手册安装的opencv3.2当时没有开启v4l2及gtk_2.x的支持,

所以後面遇到了一连串的问题,请大家如下面方法检测

$ python

1.检测python的v4l2支持及摄像头驱动是否正常

进入python之後如下命令

python 2.7.12 (default, nov 19 2016, 06:48:10)
[gcc 5.4.0 20160609] on linux2
type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cap = cv2.videocapture(0)
>>> print cap.isopened()
true
>>>

如果 返回true就代表摄像头及你的opencv的v4l2支持就已经完全正常了

如果返回false就代表opencv或是摄像头有问题叁考後面的修改方式

2.再来因为我们要把摄像头的影像生成窗口,所以我们需要检测python的gtk支持如下

>>> import cv2
>>> cv2.namedwindow('test',cv2.window_autosize)
>>> 

如果没有报任何错误就代表gtk也是正常的

如如果出现下面提示

opencv error: unspecified error (the function is not implemented. rebuild the library with windows,
 gtk+ 2.x or carbon support. if you are on ubuntu or debian, install libgtk2.0-dev and pkg-config, 
then re-run cmake or configure script) in cvnamedwindow,

那就代表opencv不支持gtk

如果上面两个测试都是好使的你可以跳过本步骤

首先我发现我不论如何重新编译opencv发现python一直都是有问题的,

最後发现是因为不知道什麽时候已经装过 python-opencv的包了

可以用命令

$ pip list |grep opencv

如果发现有任何跟opencv有关的包都可以利用 pip uninstall xxx 来移除

假设看到 pythom-opencv的包那就 pip uninstall opencv-python 来移除

还有检查dpkg -i |grep opencv 如果跟python的opencv有关的包也得移除

$ sudo apt-get remove python-opencv

然後到你之前安装opencv3.2的那个源码目录,

$ cd build
$ make uninstall

这样就会卸载之前安装的opencv

再来v4l的头文件已经改名了,但是opencv会默认使用linux/videodev.h所以要做个软鍊接

$ ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h

opencv安装过程中会自动的检测相关的包,以及一些依赖,

先列出我安装的包,但是因为环境多少有点不同,下面会教大家如何看缺少的包

$ sudo apt-get install libgphoto2-dev v4l2ucp libv4l-dev dv4l libwebcam0-dev libgtkglext1-dev libunicap2-dev 

再来执行cmake

$ cmake -d cmake_build_type=release -d cmake_install_prefix=/usr/local \
-d with_tbb=on -d with_v4l=on -d with_gtk=on -d with_gtk_2_x -d with_opengl=on \
-d with_cuda=on -d with_cublas=on -d build_python_support=on \
-d opencv_extra_modules_path=../opencv_contrib-3.2.0/modules/ ../opencv-3.2.0

其中如果v4l2使用share库也可以把-d with_v4l: = on 换成

-d with_libv4l=on

在cmake的过程中会有类似如下的提示

detected version of gnu gcc: 54 (504)
fp16: feature disabled
found openexr: /usr/lib/x86_64-linux-gnu/libilmimf.so
checking for module 'libucil'
 no package 'libucil' found
looking for linux/videodev.h
looking for linux/videodev.h - found
looking for linux/videodev2.h
looking for linux/videodev2.h - found
looking for sys/videoio.h
looking for sys/videoio.h - not found
checking for module 'libavresample'
 no package 'libavresample' found
found tbb: build
found ipp (icv version): 9.0.1 [9.0.1]
at: /mnt/sdb/ubuntu/install/opencv/build/3rdparty/ippicv/ippicv_lnx
cuda detected: 8.0
cuda nvcc target flags: -gencode;arch=compute_20,code=sm_20;-gencode;arch=compute_30,code=sm_30;-gencode;arch=compute_35,code=sm_35;-gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_52,code=sm_52;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_61,code=sm_61;-d_force_inlines
lapack_impl: atlas, lapack_libraries: /usr/lib/liblapack.so;/usr/lib/libcblas.so;/usr/lib/libatlas.so
could not find jni (missing: java_awt_library java_jvm_library java_include_path java_include_path2 java_awt_include_path) 
could not find matlab (missing: matlab_mex_script matlab_include_dirs matlab_root_dir matlab_libraries matlab_library_dirs matlab_mexext matlab_arch matlab_bin) 
vtk is not found. please set -dvtk_dir in cmake to vtk build directory, or to vtk install subdirectory with vtkconfig.cmake file
 
general configuration for opencv 3.2.0 =====================================
 version control:    unknown
 
 platform:
 timestamp:     2017-08-14t00:31:55z
 host:      linux 4.10.0-30-generic x86_64
 cmake:      3.5.1
 cmake generator:    unix makefiles
 cmake build tool:   /usr/bin/make
 configuration:    release
 
 c/c++:
 built as dynamic libs?:  yes
 c++ compiler:    /usr/bin/c++ (ver 5.4.0)
 c++ flags (release):   -fsigned-char -w -wall -werror=return-type -werror=non-virtual-dtor -werror=address -werror=sequence-point -wformat -werror=format-security -wmissing-declarations -wundef -winit-self -wpointer-arith -wshadow -wsign-promo -wno-narrowing -wno-delete-non-virtual-dtor -wno-comment -fdiagnostics-show-option -wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -o3 -dndebug -dndebug
 c++ flags (debug):   -fsigned-char -w -wall -werror=return-type -werror=non-virtual-dtor -werror=address -werror=sequence-point -wformat -werror=format-security -wmissing-declarations -wundef -winit-self -wpointer-arith -wshadow -wsign-promo -wno-narrowing -wno-delete-non-virtual-dtor -wno-comment -fdiagnostics-show-option -wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -o0 -ddebug -d_debug
 c compiler:     /usr/bin/cc
 c flags (release):   -fsigned-char -w -wall -werror=return-type -werror=non-virtual-dtor -werror=address -werror=sequence-point -wformat -werror=format-security -wmissing-declarations -wmissing-prototypes -wstrict-prototypes -wundef -winit-self -wpointer-arith -wshadow -wno-narrowing -wno-comment -fdiagnostics-show-option -wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -o3 -dndebug -dndebug
 c flags (debug):    -fsigned-char -w -wall -werror=return-type -werror=non-virtual-dtor -werror=address -werror=sequence-point -wformat -werror=format-security -wmissing-declarations -wmissing-prototypes -wstrict-prototypes -wundef -winit-self -wpointer-arith -wshadow -wno-narrowing -wno-comment -fdiagnostics-show-option -wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -g -o0 -ddebug -d_debug
 linker flags (release):
 linker flags (debug):
 ccache:      no
 precompiled headers:   yes
 extra dependencies:   /usr/lib/x86_64-linux-gnu/libpng.so /usr/lib/x86_64-linux-gnu/libtiff.so /usr/lib/x86_64-linux-gnu/libjasper.so /usr/lib/x86_64-linux-gnu/libimath.so /usr/lib/x86_64-linux-gnu/libilmimf.so /usr/lib/x86_64-linux-gnu/libiex.so /usr/lib/x86_64-linux-gnu/libhalf.so /usr/lib/x86_64-linux-gnu/libilmthread.so gtk-x11-2.0 gdk-x11-2.0 pangocairo-1.0 atk-1.0 cairo gdk_pixbuf-2.0 gio-2.0 pangoft2-1.0 pango-1.0 gobject-2.0 glib-2.0 fontconfig freetype gthread-2.0 gtkglext-x11-1.0 gdkglext-x11-1.0 glu gl xmu xt sm ice pangox-1.0 x11 gmodule-2.0 gstbase-1.0 gstreamer-1.0 gstvideo-1.0 gstapp-1.0 gstriff-1.0 gstpbutils-1.0 unicap dc1394 avcodec-ffmpeg avformat-ffmpeg avutil-ffmpeg swscale-ffmpeg gphoto2 gphoto2_port exif dl m pthread rt /usr/lib/x86_64-linux-gnu/libglu.so /usr/lib/x86_64-linux-gnu/libgl.so /usr/lib/liblapack.so /usr/lib/libcblas.so /usr/lib/libatlas.so cudart nppc nppi npps cublas cufft -l/usr/local/cuda-8.0/lib64
 3rdparty dependencies:  libwebp zlib libjpeg tbb
 
 opencv modules:
 to be built:     cudev core cudaarithm flann imgproc ml video cudabgsegm cudafilters cudaimgproc cudawarping imgcodecs photo shape videoio cudacodec highgui objdetect ts features2d calib3d cudafeatures2d cudalegacy cudaobjdetect cudaoptflow cudastereo stitching superres videostab python2
 disabled:     world
 disabled by dependency:  -
 unavailable:     java python3 viz
 
 gui: 
 qt:       no
 gtk+ 2.x:     yes (ver 2.24.30)
 gthread :     yes (ver 2.48.2)
 gtkglext:     yes (ver 1.2.0)
 opengl support:    yes (/usr/lib/x86_64-linux-gnu/libglu.so /usr/lib/x86_64-linux-gnu/libgl.so)
 vtk support:     no
 
 media i/o: 
 zlib:      build (ver 1.2.8)
 jpeg:      libjpeg (ver 90)
 webp:      build (ver 0.3.1)
 png:       /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.2.54)
 tiff:      /usr/lib/x86_64-linux-gnu/libtiff.so (ver 42 - 4.0.6)
 jpeg 2000:     /usr/lib/x86_64-linux-gnu/libjasper.so (ver 1.900.1)
 openexr:      /usr/lib/x86_64-linux-gnu/libimath.so /usr/lib/x86_64-linux-gnu/libilmimf.so /usr/lib/x86_64-linux-gnu/libiex.so /usr/lib/x86_64-linux-gnu/libhalf.so /usr/lib/x86_64-linux-gnu/libilmthread.so (ver 2.2.0)
 gdal:      no
 gdcm:      no
 
 video i/o:
 dc1394 1.x:     no
 dc1394 2.x:     yes (ver 2.2.4)
 ffmpeg:      yes
  avcodec:     yes (ver 56.60.100)
  avformat:     yes (ver 56.40.101)
  avutil:     yes (ver 54.31.100)
  swscale:     yes (ver 3.1.101)
  avresample:    no
 gstreamer:     
  base:      yes (ver 1.8.3)
  video:      yes (ver 1.8.3)
  app:      yes (ver 1.8.3)
  riff:      yes (ver 1.8.3)
  pbutils:     yes (ver 1.8.3)
 openni:      no
 openni primesensor modules: no
 openni2:      no
 pvapi:      no
 gigevisionsdk:    no
 aravis sdk:     no
 unicap:      no
 unicap ucil:     no
 v4l/v4l2:     yes/yes
 ximea:      no
 xine:      no
 gphoto2:      yes
 
 parallel framework:   tbb (ver 4.4 interface 9002)
 
 other third-party libraries:
 use ipp:      9.0.1 [9.0.1]
   at:      /mnt/sdb/ubuntu/install/opencv/build/3rdparty/ippicv/ippicv_lnx
 use ipp async:    no
 use va:      no
 use intel va-api/opencl:  no
 use lapack:     yes (/usr/lib/liblapack.so /usr/lib/libcblas.so /usr/lib/libatlas.so)
 use eigen:     no
 use cuda:     yes (ver 8.0)
 use opencl:     yes
 use openvx:     no
 use custom hal:    no
 
 nvidia cuda
 use cufft:     yes
 use cublas:     yes
 use nvcuvid:     no
 nvidia gpu arch:    20 30 35 37 50 52 60 61
 nvidia ptx archs:
 use fast math:    no
 
 opencl:      <dynamic loading of opencl library>
 include path:    /mnt/sdb/ubuntu/install/opencv/opencv-3.2.0/3rdparty/include/opencl/1.2
 use amdfft:     no
 use amdblas:     no
 
 python 2:
 interpreter:     /usr/bin/python2.7 (ver 2.7.12)
 libraries:     /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.12)
 numpy:      /usr/local/lib/python2.7/dist-packages/numpy/core/include (ver 1.13.1)
 packages path:    lib/python2.7/dist-packages
 
 python 3:
 interpreter:     /usr/bin/python3 (ver 3.5.2)
 
 python (for build):   /usr/bin/python2.7
 
 java:
 ant:       no
 jni:       no
 java wrappers:    no
 java tests:     no
 
 matlab:      matlab not found or implicitly disabled
 
 documentation:
 doxygen:      /usr/bin/doxygen (ver 1.8.11)
 
 tests and samples:
 tests:      yes
 performance tests:   yes
 c/c++ examples:    no
 
 install path:     /usr/local
 
 cvconfig.h is in:    /mnt/sdb/ubuntu/install/opencv/build
-----------------------------------------------------------------
 
configuring done

开始的部份会检查一堆依赖,请仔细看如可有缺包,可以百度一下怎么安装,因为我已经装完了就不提示了,

不过有些包我也找不到我就没解决了如上面的

checking for module 'libucil'
 no package 'libucil' found

这个我还真没找到怎么解决,不过反正问题不大

再来下面的部份一定要注意几个部分一定要有

 gui: 
 gtk+ 2.x:     yes (ver 2.24.30)
video i/o:
 v4l/v4l2:     yes/yes
 ffmpeg:      yes
 python 2:
 interpreter:     /usr/bin/python2.7 (ver 2.7.12)
 libraries:     /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.12)
 numpy:      /usr/local/lib/python2.7/dist-packages/numpy/core/include (ver 1.13.1)
 packages path:    lib/python2.7/dist-packages

主要就是上面几个个非常重要,必須要装上

再来就正常 make

$ make -j8
$ make install

设置nccl的ld环境

$ vi /etc/ld.so.conf.d/nccl.conf

加上下面目录

/usr/local/nccl/lib/

然后执行

$ sudo ldconfig

安装完后回python按步骤一再次检查是否环境都好使了

二、撰写python测试程序

# -*- coding:utf-8 -*-
# 用于模型的单张图像分类操作
import os
os.environ['glog_minloglevel'] = '2' # 将caffe的输出log信息不显示,必须放到import caffe前
import caffe # caffe 模块
from caffe.proto import caffe_pb2
from google.protobuf import text_format
import numpy as np
import cv2
import matplotlib.pyplot as plt
import time
import skimage.io
 
global num
num = 0
 
 
 
def detect(image1,net):
 # 传进来的image1的dtype为uint8
 # print image1.shape
 # print image1.dtype
 # print image1.size
 
 # image = np.array(image1, dtype=np.float32)
 # image = caffe.io.resize_image(image1, (480, 640))
 image = skimage.img_as_float(image1).astype(np.float32)
 # image = caffe.io.resize_image(image2, (300, 300))
 
 # skimage.io.imsave("photo.png", image)
 # cv2.imwrite("photo.png", image)
 # image = caffe.io.load_image(caffe_root + 'examples/images/bird.jpg')
 # 以下方式读取的imaged的dtype为float32
 # image = caffe.io.load_image(caffe_root + 'photo.png')
 # image = caffe.io.load_image(image1)
 
 # 改变dtype
 # image.dtype = 'float32'
 # print 'mode:'+image.mode
 # print image.shape
 # print image.dtype
 # print image.size
 
 # plt.imshow(image)
 
 # * run the net and examine the top_k results
 # in[5]:
 global num
 num += 1
 print 'image num:' + str(num)
 
 transformed_image = transformer.preprocess('data', image)
 net.blobs['data'].data[...] = transformed_image
 
 time_start=time.time()
 # forward pass.
 net.forward()
	
 time_end=time.time() 
 print 'time:' + str(time_end-time_start) + ' s'
 
 
 
 loc = net.blobs['bbox-list'].data[0]
 print(loc)
 #查看了结构文件发现在caffe一开始图像输入的时候就已经将图片缩小了,宽度1248高度384
 #然后我们在net.blobs['bbox-list'].data得到的是侦测到的目标座标,但是是相对于1248*384的
 #所以我们要把座标转换回相对原大小的位置,下面im.shape是保存在原尺寸的宽高,
 for l in range(len(loc)):
		xmin = int(loc[l][0] * image.shape[1] / 1248)
		ymin = int(loc[l][1] * image.shape[0] / 384)
		xmax = int(loc[l][2] * image.shape[1] /1248)
		ymax = int(loc[l][3] * image.shape[0] / 384)
		#在该座标位置画一个方框
		cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (55 / 255.0, 255 / 255.0, 155 / 255.0), 2)
 # 显示结果
 
 #plt.imshow(image, 'brg')
 #plt.show()
 cv2.imshow('img', image)
 
 
 
def show_info(cam):
 print 'pos_frames:'+str(cam.get(1))
 print 'frame_count:'+str(cam.get(7))
 print 'format:'+str(cam.get(8))
 print 'mode:'+str(cam.get(9))
 print 'saturation:'+str(cam.get(12))
 print 'fps:'+str(cam.get(5))
 
#cpu或gpu模型转换
caffe.set_mode_gpu()
#caffe.set_mode_cpu()
#caffe.set_device(0)
 
caffe_root = '/var/smb/work/mycode/'
# 网络参数(权重)文件
caffemodel = caffe_root + 'module/detectnet/snapshot_iter_2391.caffemodel'
# 网络实施结构配置文件
deploy = caffe_root + 'module/detectnet/deploy.prototxt'
 
 
img_root = caffe_root + 'data/'
 
# 网络实施分类
net = caffe.net(deploy, # 定义模型结构
    caffemodel, # 包含了模型的训练权值
    caffe.test) # 使用测试模式(不执行dropout)
 
# 加载imagenet图像均值 (随着caffe一起发布的)
print(os.environ['pythonpath'])
#mu = np.load(os.environ['pythonpath'] + '/caffe/imagenet/ilsvrc_2012_mean.npy')
#mu = mu.mean(1).mean(1) # 对所有像素值取平均以此获取bgr的均值像素值
 
# 图像预处理
transformer = caffe.io.transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1))
#transformer.set_mean('data', mu)
transformer.set_raw_scale('data', 255)
transformer.set_channel_swap('data', (2,1,0))
 
# 处理图像
cam = cv2.videocapture(0) 
if cam.isopened():
 cam.set(3, 400)
 cam.set(4, 300)
 cam.set(5, 3)
 time.sleep(6)
 cam.set(15, -8.0)
 size = (int(cam.get(3)), int(cam.get(4)))
 print 'size:'
 print size
 
cv2.namedwindow('img', cv2.window_normal)
 
# cnt=2
# while cnt:
#  cnt -= 1
while cam.isopened():
 ret, img = cam.read()
 if ret:
  #show_info(cam)
  detect(img,net)
 
 if 0xff == ord('q') & cv2.waitkey(5) == 27:
  break
 # time.sleep(0.033)
cam.release()
cv2.destroyallwindows()

介面上会打印bbox也就是侦测到的目标在图像的座标,另外请自行修改python代码里的相关目录,

python+opencv+caffe+摄像头做目标检测的实例代码

我用自己训练的kitti数据集,用于侦测车辆,因为拍不到车子拿手机欺骗一下,好使

以上这篇python+opencv+caffe+摄像头做目标检测的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。