效果如图,只识别一定距离内的物体
哈哈哈哈哈哈哈哈哈,但我不知道这有什么用
import pyrealsense2 as rs
import numpy as np
import cv2
# 排除背景色
WIDTH = 848
HEIGHT = 480
# 初始化
config = rs.config()
config.enable_stream(rs.stream.color, WIDTH, HEIGHT, rs.format.bgr8, 30)
config.enable_stream(rs.stream.depth, WIDTH, HEIGHT, rs.format.z16, 30)
# 开始
pipeline = rs.pipeline()
profile = pipeline.start(config)
# 距离[m] = depth * depth_scale
depth_sensor = profile.get_device().first_depth_sensor()
depth_scale = depth_sensor.get_depth_scale()
clipping_distance_in_meters = 0.4 # 40cm以内
clipping_distance = clipping_distance_in_meters / depth_scale
# 对齐图像
align_to = rs.stream.color
align = rs.align(align_to)
threshold = (WIDTH * HEIGHT * 3) * 0.95
try:
while True:
frames = pipeline.wait_for_frames()
aligned_frames = align.process(frames)
color_frame = aligned_frames.get_color_frame()
depth_frame = aligned_frames.get_depth_frame()
if not depth_frame or not color_frame:
continue
color_image = np.asanyarray(color_frame.get_data())
depth_image = np.asanyarray(depth_frame.get_data())
# clipping_distance_in_metersm以以内形成画像
white_color = 255 # 背景色
depth_image_3d = np.dstack((depth_image, depth_image, depth_image))
bg_removed = np.where((depth_image_3d > clipping_distance) | (depth_image_3d <= 0), white_color, color_image)
# 计算具有背景颜色的像素数
white_pic = np.sum(bg_removed == 255)
# 当背景颜色低于某个值时显示“检测到”
if(threshold > white_pic):
print("检测到 {}".format(white_pic))
else:
print("{}".format(white_pic))
images = np.hstack((bg_removed, color_image))
cv2.imshow('Frames', images)
if cv2.waitKey(1) & 0xff == 27:
break
finally:
# 停止
pipeline.stop()
cv2.destroyAllWindows()