Vispy中使用PanZoomCamera时如何获取SceneCanvas内图像点的2D坐标(x,y)
可以实现,你需要通过坐标变换把屏幕点击坐标映射到图像的本地像素坐标,具体实现逻辑如下:
实现步骤
- 为
SceneCanvas绑定鼠标点击事件监听 - 在点击事件回调中,通过图像节点的
get_transform方法,将画布坐标系下的点击坐标转换为图像节点的本地坐标 - 对转换后的坐标做范围校验,合法即可直接读取对应位置的像素强度
完整示例代码
import numpy as np from vispy import app, scene from vispy.scene.visuals import Image # 初始化画布和PanZoomCamera canvas = scene.SceneCanvas(keys='interactive', show=True) cam = scene.PanZoomCamera(aspect=1) canvas.camera = cam # 生成测试灰度图像并添加到场景 test_img = np.random.randint(0, 255, (200, 300), dtype=np.uint8) image_node = Image(test_img, parent=canvas.scene) # 适配相机视角到图像完整范围 cam.set_range(margin=0) def on_mouse_press(event): # 仅响应鼠标左键点击 if event.button != 1: return # 坐标变换:从画布坐标系转换为图像节点本地坐标系 transform = image_node.get_transform('canvas', 'local') local_pos = transform.map(event.pos) # 提取图像x、y像素坐标,转为整数 img_x, img_y = int(local_pos[0]), int(local_pos[1]) # 校验坐标在图像合法范围内 if 0 <= img_x < test_img.shape[1] and 0 <= img_y < test_img.shape[0]: # 输出坐标和对应像素强度值 print(f"图像坐标:x={img_x}, y={img_y},强度值:{test_img[img_y, img_x]}") # 绑定点击事件回调 canvas.events.mouse_press.connect(on_mouse_press) if __name__ == '__main__': app.run()
注意事项
- 坐标维度对应关系:转换得到的本地坐标第一个值为图像的水平方向坐标(对应数组的列索引),第二个值为垂直方向坐标(对应数组的行索引),读取像素值时不要颠倒顺序
- 该转换逻辑会自动适配
PanZoomCamera的平移、缩放操作,无需手动计算相机的偏移量和缩放比例 - 如果点击位置不在图像范围内,转换得到的坐标会超出图像尺寸,需要做边界校验避免数组索引报错
内容的提问来源于stack exchange,提问作者Loc Tran
相关产品推荐
相关产品推荐

