当前位置:   article > 正文

nvidia jetson nano 操作指南

nvidia jetson nano

硬件购买以及注意点

        购买硬件之后在网卡后面有个短路帽要加上,否则无法开机。

系统安装

nvidia jetson nano系统安装在SD卡中,请预先准备一个32G的SD卡

系统安装步骤请参考官网

Getting Started With Jetson Nano Developer Kit | NVIDIA Developer

注意:烧录完成会弹出好多个窗口,请求格式化,此处一定要点  取消 不要格式化,因为这是软件在为系统分盘。

开发前准备

检查opencv是否安装

命令行:opencv_version

输出:4.1.1

检查显卡驱动和cuda是否安装

命令行:nvcc -V

输出:bash: nvcc command not found

解决:驱动其实已经安装了,我们需要加入环境变量

sudo vim ~./bashrc

或者也可以直接到本地电脑的Home文件夹中找到.bashrc文件,直接打开文件,在文件的最后位置添加上三行命令。(若进到Home文件夹没看有.bashrc文件,则点击一下Ctrl + H就可以显示出.bashrc

在文件最后添加

export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
export CUDA_HOME=/usr/local/cuda

设置完成后可以正常看到nvcc -V 的信息

安装jtop以便查看设备信息

  1. sudo apt-get install git cmake
  2. sudo apt-get install python3-dev
  3. sudo apt-get install libhdf5-serial-dev hdf5-tools
  4. sudo apt-get install libatlas-base-dev gfortran
  5. sudo apt-get install python3-pip
  6. sudo -H pip3 install -U jetson-stats
  7. sudo systemctl restart jetson_stats.service
  8. reboot
  9. jtop

 安装opencv

sys Update

sudo apt-get update
sudo apt-get full-upgrade

sudo add-apt-repository "deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ xenial main multiverse restricted universe"

sudo apt update

set nvcc

sudo vim ~/.bashrc
export CUDA_HOME=/usr/local/cuda-10.2
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH
export PATH=/usr/local/cuda-10.2/bin:$PATH
source ~/.bashrc
# test

nvcc -V

安装OpenCV with CUDA

sudo apt-get install build-essential

sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev

sudo apt-get install python3-dev python3-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev

sudo apt-get install pkg-config

sudo apt-get install opencv3-pip

unzip opencv4.6-contrib-xfture

  1. build> cmake
  2. -D CMAKE_INSTALL_PREFIX=/usr/local
  3. -D CMAKE_BUILD_TYPE=Release
  4. -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules
  5. -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-10.2
  6. -D CUDA_ARCH_BIN=5.3
  7. -D CUDA_ARCH_PTX=""
  8. -D BUILD_PNG=OFF
  9. -D BUILD_TIFF=OFF
  10. -D BUILD_TBB=OFF
  11. -D BUILD_JPEG=OFF
  12. -D BUILD_JASPER=OFF
  13. -D BUILD_ZLIB=OFF
  14. -D BUILD_EXAMPLES=ON
  15. -D BUILD_opencv_java=OFF
  16. -D BUILD_opencv_python2=OFF
  17. -D BUILD_opencv_python3=ON
  18. -D ENABLE_PRECOMPILED_HEADERS=OFF
  19. -D WITH_OPENCL=OFF
  20. -D WITH_OPENMP=OFF
  21. -D WITH_FFMPEG=ON
  22. -D WITH_GSTREAMER=OFF
  23. -D WITH_GSTREAMER_0_10=OFF
  24. -D WITH_CUDA=ON
  25. -D WITH_GTK=ON
  26. -D WITH_VTK=OFF
  27. -D WITH_TBB=ON
  28. -D PYTHON_DEFAULT_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
  29. -D PYTHON3_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)")
  30. -D PYTHON3_NUMPY_INCLUDE_DIRS=$(python3 -c "import numpy; print (numpy.get_include())")
  31. -D PYTHON3_PACKAGES_PATH=$(python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")
  32. -D WITH_1394=OFF
  33. -D WITH_OPENEXR=OFF
  34. -D INSTALL_C_EXAMPLES=ON -D INSTALL_TESTS=OFF
  35. ..
  1. build> make -j4
  2. build> sudo make install
  3. build> sudo python3 setup.py install

if "sudo python3 setup.py install " error :

pip3 install setuptools

pip3 install --upgrade setuptools

pip3 install --upgrade pip

do sudo python3 setup.py install again!

pip3 install Pillow
pip3 install pygame -i https://pypi.tuna.tsinghua.edu.cn/simple/

  1. CameraCall.py
  2. # encoding: utf-8
  3. import cv2 as cv
  4. import subprocess
  5. class CameraCallTool(object):
  6. cap = None
  7. def __init__(self, width, height, CamIndex):
  8. print(f'Init Camera Tool!')
  9. if CamIndex == -1:
  10. self.CallCameraOnBoard(width, height)
  11. elif CamIndex == 0:
  12. self.CallCameraOnCSI(width, height)
  13. else:
  14. print('no usb camera!')
  15. def CallCameraOnCSI(self, width, height):
  16. self.cap = cv.VideoCapture(0) #设置摄像头 0是默认的摄像头 如果你有多个摄像头的话呢,可以设置1,2,3....
  17. self.cap.set(cv.CAP_PROP_FRAME_WIDTH, width)
  18. self.cap.set(cv.CAP_PROP_FRAME_HEIGHT, height)
  19. self.cap.set(cv.CAP_PROP_EXPOSURE, 0.1)
  20. def Test(self):
  21. print('CameraCallTool Test')
  22. def CameraStatus(self):
  23. return self.cap.isOpened()
  24. def CallCameraOnBoard(self, width, height):
  25. gst_elements = str(subprocess.check_output('gst-inspect-1.0'))
  26. if 'nvcamerasrc' in gst_elements:
  27. # On versions of L4T prior to 28.1, add 'flip-method=2' into gst_str
  28. gst_str = ('nvcamerasrc ! '
  29. 'video/x-raw(memory:NVMM), '
  30. 'width=(int)2592, height=(int)1458, '
  31. 'format=(string)I420, framerate=(fraction)30/1 ! '
  32. 'nvvidconv ! '
  33. 'video/x-raw, width=(int){}, height=(int){}, '
  34. 'format=(string)BGRx ! '
  35. 'videoconvert ! appsink').format(width, height)
  36. elif 'nvarguscamerasrc' in gst_elements:
  37. gst_str = ('nvarguscamerasrc ! '
  38. 'video/x-raw(memory:NVMM), '
  39. 'width=(int)1920, height=(int)1080, '
  40. 'format=(string)NV12, framerate=(fraction)30/1 ! '
  41. 'nvvidconv flip-method=2 ! '
  42. 'video/x-raw, width=(int){}, height=(int){}, '
  43. 'format=(string)BGRx ! '
  44. 'videoconvert ! appsink').format(width, height)
  45. else:
  46. raise RuntimeError('onboard camera source not found!')
  47. # return cv.VideoCapture(gst_str, cv.CAP_GSTREAMER)
  48. self.cap = cv.VideoCapture(gst_str, cv.CAP_GSTREAMER)
  49. def GetOneFrame(self):
  50. if self.cap.isOpened():
  51. ret, frame = self.cap.read()
  52. if ret is True:
  53. # 摄像头是和人对立的,将图像左右调换回来正常显示。
  54. frame = cv.flip(frame, 1)
  55. frame = cv.flip(frame, 0)
  56. return frame
  57. else:
  58. return None
  59. else:
  60. return None
  61. def __del__(self):
  62. if self.cap is not None:
  63. self.cap.release()
  64. print('CameraCallTool del')
  1. DnnClass.py
  2. # encoding: utf-8
  3. import numpy as np
  4. import cv2 as cv
  5. import os
  6. import time
  7. class MyDnn(object):
  8. # YOLO文件路径 G:\vs2017Project\yolov2-tiny-voc
  9. yolo_dir = './yolov3-tiny'
  10. # 过滤弱检测的最小概率
  11. CONFIDENCE = 0.5
  12. # 非最大值抑制阈值
  13. THRESHOLD = 0.4
  14. def __init__(self):
  15. print('import Dnn Tool Calss!')
  16. # YOLO文件路径
  17. self.yolo_dir_name = self.yolo_dir
  18. # 权重文件
  19. self.weightsPath = os.path.join(self.yolo_dir, 'yolov3.weights')
  20. # 配置文件
  21. self.configPath = os.path.join(self.yolo_dir, 'yolov3.cfg')
  22. # label名称
  23. self.labelsPath = os.path.join(self.yolo_dir_name, 'coco.names')
  24. # 加载网络、配置权重
  25. self.net = cv.dnn.readNetFromDarknet(self.configPath, self.weightsPath)
  26. # intel gpu
  27. # self.net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
  28. # self.net.setPreferableTarget(cv.dnn.DNN_TARGET_OPENCL)
  29. # cpu
  30. # self.net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
  31. # self.net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)
  32. # nvidia gpu
  33. self.net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)
  34. self.net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)
  35. print("[INFO] loading YOLO from disk...") # # 可以打印下信息
  36. def importTest(self):
  37. print('dnn import test!')
  38. def DecodeImage(self, img):
  39. start = time.time()
  40. # 加载图片、转为blob格式、送入网络输入层
  41. # img = imagePath
  42. # net需要的输入是blob格式的,用blobFromImage这个函数来转格式
  43. blobImg = cv.dnn.blobFromImage(img, 1.0/255.0, (416, 416), None, True, False)
  44. # 调用setInput函数将图片送入输入层
  45. self.net.setInput(blobImg)
  46. # 前面的yolov3架构也讲了,yolo在每个scale都有输出,outInfo是每个scale的名字信息,供net.forward使用
  47. outInfo = self.net.getUnconnectedOutLayersNames()
  48. # 得到各个输出层的、各个检测框等信息,是二维结构。
  49. layerOutputs = self.net.forward(outInfo)
  50. end = time.time()
  51. print("[INFO] YOLO took {:.6f} seconds".format(end - start))
  52. # 拿到图片尺寸
  53. (H, W) = img.shape[:2]
  54. # 过滤layerOutputs
  55. # layerOutputs的第1维的元素内容: [center_x, center_y, width, height, objectness, N-class score data]
  56. # 过滤后的结果放入:
  57. # 所有边界框(各层结果放一起)
  58. boxes = []
  59. # 所有置信度
  60. confidences = []
  61. # 所有分类ID
  62. classIDs = []
  63. # # 1)过滤掉置信度低的框框
  64. # 各个输出层
  65. for out in layerOutputs:
  66. # 各个框框
  67. for detection in out:
  68. # 拿到置信度
  69. # 各个类别的置信度
  70. scores = detection[5:]
  71. # 最高置信度的id即为分类id
  72. classID = np.argmax(scores)
  73. # 拿到置信度
  74. confidence = scores[classID]
  75. # 根据置信度筛查
  76. if confidence > self.CONFIDENCE:
  77. # 将边界框放会图片尺寸
  78. box = detection[0:4] * np.array([W, H, W, H])
  79. (centerX, centerY, width, height) = box.astype("int")
  80. x = int(centerX - (width / 2))
  81. y = int(centerY - (height / 2))
  82. boxes.append([x, y, int(width), int(height)]) # 框
  83. confidences.append(float(confidence)) # 置信度
  84. classIDs.append(classID) # 分类ID
  85. # # 2)应用非最大值抑制(non-maxima suppression,nms)进一步筛掉
  86. # boxes中,保留的box的索引index存入idxs
  87. idxs = cv.dnn.NMSBoxes(boxes, confidences, self.CONFIDENCE, self.THRESHOLD)
  88. # 得到labels列表
  89. with open(self.labelsPath, 'rt') as f:
  90. labels = f.read().rstrip('\n').split('\n')
  91. np.random.seed(42)
  92. # 框框显示颜色,每一类有不同的颜色,每种颜色都是由RGB三个值组成的,所以size为(len(labels), 3)
  93. COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")
  94. if len(idxs) > 0:
  95. # alarm pic
  96. for i in idxs.flatten(): # indxs是二维的,第0维是输出层,所以这里把它展平成1
  97. (x, y) = (boxes[i][0], boxes[i][1])
  98. (w, h) = (boxes[i][2], boxes[i][3])
  99. color = [int(c) for c in COLORS[classIDs[i]]]
  100. # 线条粗细为2px
  101. cv.rectangle(img, (x, y), (x+w, y+h), color, 2)
  102. cv.rectangle(img, (x, y), (x+w, y+h), color, 2)
  103. # 线条粗细为2px
  104. text = "{}: {:.4f}".format(labels[classIDs[i]], confidences[i])
  105. # cv.FONT_HERSHEY_SIMPLEX字体风格、0.5字体大小、粗细2px
  106. cv.putText(img, text, (x, y-5), cv.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
  107. print('alarm pic!')
  108. cv.imshow('decode', img)
  109. return img
  110. else:
  111. # normal pic
  112. print('normal pic!')
  113. return None
  1. DnnMain.py
  2. # encoding: utf-8
  3. import cv2 as cv
  4. from DnnClass import MyDnn
  5. from CameraCall import CameraCallTool
  6. import pygame
  7. from PIL import Image, ImageDraw, ImageFont
  8. import threading
  9. import subprocess
  10. def LoadMusic():
  11. pygame.mixer.init()
  12. pygame.mixer.music.load('./audio/succ.wav')
  13. pygame.mixer.music.set_volume(0.5)
  14. def PlaySuccess():
  15. pygame.mixer.music.play()
  16. def DrawTextOnImage(img, text1, text2, left, top, textColor=(0,255,0), textSize=20):
  17. if(isinstance(img, np.ndarray)):
  18. img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  19. # create a draw to draw text
  20. draw = ImageDraw.Draw(img)
  21. fontstyle = ImageFont.truetype('./font/simsun.ttc', textSize, encoding='utf-8')
  22. draw.text((left,top), text1, textColor, font=fontstyle)
  23. draw.text((left,int(top + textSize + 2)), text2, textColor, font=fontstyle)
  24. return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
  25. def CallCameraOnBoard(width, height):
  26. gst_elements = str(subprocess.check_output('gst-inspect-1.0'))
  27. if 'nvcamerasrc' in gst_elements:
  28. # On versions of L4T prior to 28.1, add 'flip-method=2' into gst_str
  29. gst_str = ('nvcamerasrc ! '
  30. 'video/x-raw(memory:NVMM), '
  31. 'width=(int)2592, height=(int)1458, '
  32. 'format=(string)I420, framerate=(fraction)30/1 ! '
  33. 'nvvidconv ! '
  34. 'video/x-raw, width=(int){}, height=(int){}, '
  35. 'format=(string)BGRx ! '
  36. 'videoconvert ! appsink').format(width, height)
  37. elif 'nvarguscamerasrc' in gst_elements:
  38. gst_str = ('nvarguscamerasrc ! '
  39. 'video/x-raw(memory:NVMM), '
  40. 'width=(int)1920, height=(int)1080, '
  41. 'format=(string)NV12, framerate=(fraction)30/1 ! '
  42. 'nvvidconv flip-method=2 ! '
  43. 'video/x-raw, width=(int){}, height=(int){}, '
  44. 'format=(string)BGRx ! '
  45. 'videoconvert ! appsink').format(width, height)
  46. else:
  47. raise RuntimeError('onboard camera source not found!')
  48. return cv.VideoCapture(gst_str, cv.CAP_GSTREAMER)
  49. if __name__ == "__main__":
  50. print('camera onboard')
  51. DnnTool = MyDnn()
  52. cameraCallTool = CameraCallTool(1024, 768, 0)
  53. t = 0
  54. try:
  55. while cameraCallTool.CameraStatus():
  56. CameraFrame = cameraCallTool.GetOneFrame()
  57. if CameraFrame is not None:
  58. cv.imshow('Video', CameraFrame)
  59. if t == 0 or t.is_alive() is False:
  60. # image_np = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  61. t = threading.Thread(target=DnnTool.DecodeImage, args=(CameraFrame, ))
  62. t.start()
  63. #判断退出的条件 当按下'Q'键的时候呢,就退出
  64. c = cv.waitKey(1)
  65. # 如果按下q 就截图保存并退出
  66. if c == ord('q'):
  67. saveFile = "Capture.jpg" # 带有中文的保存文件路径
  68. img_write = cv.imencode(".jpg", CameraFrame)[1].tofile(saveFile)
  69. break
  70. except:
  71. print('Camera Show Exception!')
  72. finally:
  73. del cameraCallTool
  74. cv.destroyAllWindows()

lost : audo  font  yolov3-tiny

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/144374?site
推荐阅读
相关标签
  

闽ICP备14008679号