我们可以通过自定义交互方式来控制相机的运动,例如当我们按下一个按键的时候相机向左或者向右移动一定的角度。
这里我们给出一个示例:
本示例完成了一个功能,当我们按下按键a的时候,相机就会自动自动收集不同方向的运动窗口的画面,将对应的相机位置和姿态的信息保存下来
# 自定义交互风格
class myInteractorStyle(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self, parent=None):
self.AddObserver('KeyPressEvent', self.onKeyPressE)
self.left_press = False
self.start_record = False
self.reader = None
self.conActor = None
self.axes = None
self.pre_pos = ""
self.renwin = None
self.camera = None
def onKeyPressE(self, obj, event):
# 获取按下的键
key = self.GetInteractor().GetKeySym()
if key == 'a':
self.auto_change_camera_savedata()
# print(self.camera.GetOrientation())
self.OnKeyPress()
def auto_change_camera_savedata(self):
print("Recording data".center(60, "="))
labelfile = f"./dataset/test/label_namexyzear.csv"
label_txt = open(labelfile, "w+")
camera_pos = 275
render = vtk.vtkRenderer()
render.AddActor(self.conActor) # 添加 actor
camera = render.GetActiveCamera() # 获取相机
self.renwin.AddRenderer(render) # 获取渲染器
index = 0
while camera_pos <= 380:
random_zoom = np.random.randint(0,25) # 随机相机的位置
camera_pos += random_zoom
azi = -180 # 取值范围-180, 180
while azi <= 180:
random_azi = np.random.randint(0,25)
azi += random_azi
ele = -90 # 取值范围 -90, 90
while ele <= 90:
random_ele = np.random.randint(0,25)
ele += random_ele
roll = -180 # 取值范围-180, 180
while roll <= 180:
index += 1
random_roll = np.random.randint(0,25)
roll += random_roll
camera.SetPosition(0, 0, camera_pos) # 设置相机的位置
camera.SetFocalPoint(0,0,0) # 设置相机的焦点
camera.Elevation(ele) # 绕X轴旋转 垂直 俯仰角度
camera.Azimuth(azi) # 绕Y轴旋转 水平 滚动角
camera.Roll(roll) # 绕Z轴旋转 平行 偏航角
self.renwin.Render()
# 保存图像和标签
imgname = f"./dataset/test/images/{int(time()*1000)+np.random.randint(0,99999)}.jpg"
self.save_window_pic(imgname)
pos = self.getpos(camera)
label_txt.write(f"{imgname},{pos[0]},{pos[1]},{pos[2]},{ele},{-azi},{roll}\n")
if index % 500 == 0: print(f"已经收集了{index}张图片")
def getpos(self, camera):
pos = list(camera.GetPosition())
return pos
def save_window_pic(self, filename):
window_to_image_filter = vtk.vtkWindowToImageFilter()
window_to_image_filter.SetInput(self.renwin) # 获取当前窗口
window_to_image_filter.SetInputBufferTypeToRGB()
# window_to_image_filter.Update()
# writer = vtk.vtkBMPWriter() # 将图片保存为BMP格式
writer = vtk.vtkJPEGWriter() # 将图片保存为JPEG格式
writer.SetFileName(filename)
writer.SetInputConnection(window_to_image_filter.GetOutputPort())
writer.SetQuality(100)
writer.Write()
关于动态设置相机的代码在auto_change_camera_savedata函数中。这段代码是一个用于自动采集相机视角的功能。
该函数用于自动改变相机的位置并保存图像和标签。