realsense D455深度相機+YOLO V5結合實作目標檢測(一)
- 1.代碼來源
- 2.環境配置
- 3.代碼分析:
- 3.1如何用realsense在python下面呼叫的問題:
- 3.2 對main_debug.py檔案的分析:
- 4. 結束語
可以實作將D435,D455深度相機和yolo v5結合到一起,在識別物體的同時,還能測到物體相對與相機的距離,
說明一下為什么需要做這個事情?1.首先為什么需要用到realsense D455深度相機? 因為他是普通的相機還加了一個紅外測距的東西,所以其他二維影像一樣,能夠得到三維世界在二維像素平面的投影,也就是圖片,但是我們損失了一個深度的維度以后得到的都是投影的東西,比如說蘋果可以和足球一樣大,因為我們不知道深度也就是物體距離相機的距離資訊,所以我們需要一個深度相機來實作測距離,2.為什么需要用到yolo演算法?因為他在實時性和準確率方面都可以,可以應用于工農業生產當中,所以肯定很需要,所以才會有這二者的結合的必要性!
1.代碼來源
首先感謝github上的yuanyuanyuan killnice大佬將自己的代碼開源出來,這是我第一次用realsense深度相機去實作將其與目標檢測的yolo v5 演算法結合在一起,實作2.5維的檢測吧,首先大家如果想用這個代碼的話可以去這里git clone yuanyuanyuan killnice大佬的代碼 (為了防止鏈接不過去還是再寫在這里 https://github.com/killnice/yolov5-D435i.git),
2.環境配置
首選clone下yuanyuanyuan killnice大佬的代碼后,在命令列運行:
pip install -r requirements.txt
pip install pyrealsense2
然后cd到進入工程檔案夾下執行:
python main_debug.py
第一次運行會自動下載yolov5l6.pt檔案,大約140MB左右,如果由于網速原因不能自動下載,請手動在yolo v5的github上自己下載,運行結果如下:

3.代碼分析:
3.1如何用realsense在python下面呼叫的問題:
這個的來源是從realsense的官方檔案中來的 realsense的官方python檔案,如果你對他的其他應用感興趣可以去這里看一看,
import pyrealsense2 as rs
import numpy as np
import cv2
# Configure depth and color streams
pipeline = rs.pipeline()
config = rs.config()
# config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
# config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
# Start streaming
pipeline.start(config)
try:
while True:
# Wait for a coherent pair of frames: depth and color
frames = pipeline.wait_for_frames()
# 深度圖
depth_frame = frames.get_depth_frame()
# 正常讀取的視頻流
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
continue
# Convert images to numpy arrays
depth_image = np.asanyarray(depth_frame.get_data())
color_image = np.asanyarray(color_frame.get_data())
# print(f"depth_image shape: {depth_image.shape} color_image shape: {color_image.shape}")
print(f"depth_image value: {depth_image}") # 里面0值很多,還有很多1900左右的值 300mm 單位是毫米=30厘米=0.3米
# depth_image shape: (480, 640) color_image shape: (480, 640, 3)
# 深度圖是單通道 顏色圖是三通道的
# Apply colormap on depth image (image must be converted to 8-bit per pixel first)
# 在深度影像上應用colormap(影像必須先轉換為每像素8位)
depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)
# Stack both images horizontally
images = np.hstack((color_image, depth_colormap))
# Show images
cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
cv2.imshow('RealSense', images)
key = cv2.waitKey(1)
if key & 0xFF == ord('q') or key == 27:
cv2.destroyAllWindows()
break
finally:
# Stop streaming
pipeline.stop()
這就是用python呼叫realsense D455深度相機的程式,
3.2 對main_debug.py檔案的分析:
import pyrealsense2 as rs
import numpy as np
import cv2
import random
import torch
import time
#呼叫各種庫
#從檔案的構造中不難看出是用了下面的幾個函式:分別是get_mid_pos(frame,box,depth_data,randnum),dectshow(org_img, boxs,depth_data),
#主函式,
# model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
#
model = torch.hub.load('ultralytics/yolov5', 'yolov5l6')
model.conf = 0.5
def get_mid_pos(frame,box,depth_data,randnum):
#這個函式就是簡單的從給出的圖片、框、深度資料、可以選擇的迭代次數
distance_list = []
mid_pos = [(box[0] + box[2])//2, (box[1] + box[3])//2] #確定索引深度的中心像素位置左上角和右下角相加在/2
min_val = min(abs(box[2] - box[0]), abs(box[3] - box[1])) #確定深度搜索范圍
#print(box,)
for i in range(randnum):
bias = random.randint(-min_val//4, min_val//4)
dist = depth_data[int(mid_pos[1] + bias), int(mid_pos[0] + bias)]
cv2.circle(frame, (int(mid_pos[0] + bias), int(mid_pos[1] + bias)), 4, (255,0,0), -1)
#print(int(mid_pos[1] + bias), int(mid_pos[0] + bias))
if dist:
distance_list.append(dist)
distance_list = np.array(distance_list)
distance_list = np.sort(distance_list)[randnum//2-randnum//4:randnum//2+randnum//4] #冒泡排序+中值濾波
#print(distance_list, np.mean(distance_list))
return np.mean(distance_list)
def dectshow(org_img, boxs,depth_data):
#在原影像上畫框和深度資訊寫在影像上
img = org_img.copy()
for box in boxs:
cv2.rectangle(img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0), 2)
dist = get_mid_pos(org_img, box, depth_data, 24)
cv2.putText(img, box[-1] + str(dist / 1000)[:4] + 'm',
(int(box[0]), int(box[1])), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
cv2.imshow('dec_img', img)
if __name__ == "__main__":
# Configure depth and color streams
#這是主要是將上面1中提到的realsense在python中的呼叫,
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 60)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 60)
# Start streaming
pipeline.start(config)
try:
while True:
# Wait for a coherent pair of frames: depth and color
frames = pipeline.wait_for_frames()
depth_frame = frames.get_depth_frame()
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
continue
# Convert images to numpy arrays
depth_image = np.asanyarray(depth_frame.get_data())
color_image = np.asanyarray(color_frame.get_data())
results = model(color_image)
boxs= results.pandas().xyxy[0].values
#boxs = np.load('temp.npy',allow_pickle=True)
dectshow(color_image, boxs, depth_image)
# Apply colormap on depth image (image must be converted to 8-bit per pixel first)
depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)
# Stack both images horizontally
images = np.hstack((color_image, depth_colormap))
# Show images
cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
cv2.imshow('RealSense', images)
key = cv2.waitKey(1)
# Press esc or 'q' to close the image window
if key & 0xFF == ord('q') or key == 27:
cv2.destroyAllWindows()
break
finally:
# Stop streaming
pipeline.stop()
4. 結束語
從以前在csdn上查找到自己寫,這是第一次,覺得這是一種進步,希望能夠幫助到別人,也感謝yuanyuanyuan killnice大佬,還有yolo v5的作者,反正就是感謝開源吧,對我感興趣的童鞋可以關注我,說不定那一天就可以幫到您!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/296689.html
標籤:其他
上一篇:node ffmpeg swf轉mp4 截取mp4視頻第一幀為jpg圖片
下一篇:淺談音視頻網路通信中的延時優化
