如何为OpenCV imshow窗口中的每个分块添加自定义名称?
为拼接后的多路视频流分块添加名称的实现方法
你可以通过OpenCV的cv2.putText()函数给每路传感器的图像单独添加标签后再拼接,或者在拼接完成后的整图上按分块位置添加文字。前者更直观,不易出错,具体实现如下:
方法1:先给单路图像加标签再拼接
先定义一个复用的辅助函数来处理文字添加(可选,也可以直接逐图处理):
def add_image_label(image, label): # 配置文字参数 font = cv2.FONT_HERSHEY_SIMPLEX font_scale = 1.2 text_color = (255, 255, 255) # 白色文字 text_thickness = 2 # 计算文字尺寸,用于定位到左上角(留出边距) text_width, text_height = cv2.getTextSize(label, font, font_scale, text_thickness)[0] pos_x, pos_y = 15, text_height + 15 # 给文字加黑色背景(提升可读性,可省略) cv2.rectangle(image, (pos_x-5, pos_y-text_height-5), (pos_x+text_width+5, pos_y+5), (0,0,0), -1) # 添加文字 cv2.putText(image, label, (pos_x, pos_y), font, font_scale, text_color, text_thickness) return image
然后修改原拼接代码:
cv2.namedWindow('All cameras', cv2.WINDOW_AUTOSIZE) # 给每路传感器图像添加对应标签(用copy避免修改原始数据) labeled_img1 = add_image_label(sensor_data1['rgb_image'].copy(), 'Sensor 1') labeled_img4 = add_image_label(sensor_data4['rgb_image'].copy(), 'Sensor 4') labeled_img2 = add_image_label(sensor_data2['rgb_image'].copy(), 'Sensor 2') labeled_img3 = add_image_label(sensor_data3['rgb_image'].copy(), 'Sensor 3') # 执行拼接 top_row = np.concatenate((labeled_img1, labeled_img4), axis=1) lower_row = np.concatenate((labeled_img2, labeled_img3), axis=1) tiled = np.concatenate((top_row, lower_row), axis=0) cv2.imshow('All cameras', tiled) cv2.waitKey(1)
方法2:拼接后在整图上添加标签
如果想直接在拼接好的大图上添加文字,需要先计算每个分块的坐标范围:
cv2.namedWindow('All cameras', cv2.WINDOW_AUTOSIZE) # 原拼接逻辑不变 top_row = np.concatenate((sensor_data1['rgb_image'], sensor_data4['rgb_image']), axis=1) lower_row = np.concatenate((sensor_data2['rgb_image'], sensor_data3['rgb_image']), axis=1) tiled = np.concatenate((top_row, lower_row), axis=0) # 获取单帧图像的尺寸(假设所有传感器图像尺寸一致) h, w = sensor_data1['rgb_image'].shape[:2] # 定义标签和对应位置(左上角坐标) labels = [ ('Sensor 1', (15, 30)), ('Sensor 4', (w + 15, 30)), ('Sensor 2', (15, h + 30)), ('Sensor 3', (w + 15, h + 30)) ] # 添加所有标签 font = cv2.FONT_HERSHEY_SIMPLEX for label, (x, y) in labels: # 可选:添加黑色背景 text_size = cv2.getTextSize(label, font, 1.2, 2)[0] cv2.rectangle(tiled, (x-5, y-text_size[1]-5), (x+text_size[0]+5, y+5), (0,0,0), -1) cv2.putText(tiled, label, (x, y), font, 1.2, (255,255,255), 2) cv2.imshow('All cameras', tiled) cv2.waitKey(1)
注意事项
- 使用
copy()处理原始图像是为了避免修改传感器返回的原始数据,防止影响其他逻辑 - 可以根据实际需求调整字体类型、大小、颜色和文字位置
- 黑色背景是可选操作,若视频画面本身对比度足够,也可以直接添加白色文字
内容的提问来源于stack exchange,提问作者Rony Shaji
相关产品推荐
相关产品推荐

