import cv2
import numpy as np
# 读取深度图像和原图
depth_image = cv2.imread("C:\\Users\\86199\\Desktop\\0331\\depth_image_00007.tiff", -1).astype(np.float32)
image = cv2.imread("C:\\Users\\86199\\Desktop\\0331\\rgb_image_00007.png")
# 深度值反转处理
max_depth, min_depth = depth_image.max(), depth_image.min()
processed_depth = np.where(depth_image != 0, max_depth - depth_image, 0)
# 二值化
thresh = processed_depth.max() - 16
_, binary_img = cv2.threshold(processed_depth, thresh, 255, cv2.THRESH_BINARY)
binary_img = binary_img.astype(np.uint8)
# 腐蚀
kernel = np.ones((20, 20), np.uint8)
eroded_img = cv2.erode(binary_img, kernel, iterations=1)
cv2.imwrite("eroded_img.png", eroded_img)
# 查找轮廓
contours, _ = cv2.findContours(eroded_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 过滤和绘制矩形参数
min_dimension = 20 # 最小长宽阈值(用以过滤非砖块区域)
#绘制中心点
marker_size = 10 # 中心点标记大小
marker_thickness = 2 # 中心点标记粗细
for contour in contours:
# 获取最小外接矩形
rect = cv2.minAreaRect(contour)
width, height = rect[1]
# 过滤小尺寸矩形(考虑旋转因素取最小边)
if min(width, height) < min_dimension:
continue
# 绘制矩形
print([rect[0]])
box = cv2.boxPoints(rect).astype(int)
cv2.drawContours(image, [box], 0, (0, 255, 0), 2)
# 绘制中心点
center = tuple(map(int, rect[0])) # 将中心坐标转换为整数
# 绘制标记
cv2.drawMarker(image, center, (0,0,255), markerType=cv2.MARKER_CROSS, markerSize=marker_size, thickness=marker_thickness)
# 保存结果
cv2.imwrite('final_result.jpg', image)
print("砖块位置已保存为 final_result.jpg")
完善为在第一张图中找到的效果较好的轮廓,第二张图以第一张图找到的轮廓为模板轮廓去匹配
最新发布