1.点云转换为二值图像
def point2picture(filename):
pcd=o3d.io.read_point_cloud(filename)
min=pcd.get_min_bound()
max=pcd.get_max_bound()
res=0.5
row=math.ceil((max[1]-min[1])/res)
col=math.ceil((max[0]-min[0])/res)
image=np.zeros((row,col,1),np.uint8)
for i in tqdm(range(len(pcd.points))):
temp_row=math.floor((max[1]-(pcd.points[i])[1])/res)
temp_col=math.floor(((pcd.points[i])[0]-min[0])/res)
image[temp_row][temp_col]=255
cv2.imwrite("/home/zhengxin/PV_System/data/temp.png",image)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bbc1d6808b7c2e67802d4f318a4387ce.png#pic_center)
2.形态学开运算操作
def open_operation(filename):
k=np.ones((10,10),np.uint8)
image=cv2.imread(filename)
cv2.dilate(cv2.erode(image,k),k)
cv2.imwrite("/home/zhengxin/PV_System/data/temp_open.png",image)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1fd8e8e26f06de128ab130412954dd26.png#pic_center)
3.Canny边缘检测并寻找轮廓
def find_contours(val):
threshold = val
canny_output = cv2.Canny(src_gray, threshold, threshold * 2)
contours, hierarchy = cv2.findContours(canny_output, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
for i in range(len(contours)):
color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
cv2.drawContours(drawing, contours, i, color, 2, cv2.LINE_8, hierarchy, 0)
cv2.imshow('Contours', drawing)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0f3ab9865282e4f291939a050f21a58d.png#pic_center)
4.主函数
pc_path="/home/zhengxin/PV_System/data/building.pcd"
img_path="/home/zhengxin/PV_System/data/temp.png"
open_path="/home/zhengxin/PV_System/data/temp_open.png"
point2picture(pc_path)
open_operation(img_path)
src_gray=cv2.imread(open_path,cv2.IMREAD_GRAYSCALE)
src_gray = cv2.blur(src_gray, (3,3))
source_window = 'Source'
cv2.namedWindow(source_window)
cv2.imshow(source_window, src_gray)
max_thresh = 255
thresh = 100
cv2.createTrackbar('Canny Thresh:', source_window, thresh, max_thresh, find_contours)
find_contours(thresh)
cv2.waitKey()