# Full script for fitting the camera view to the only object in a scene

I have found an answer in this stackexchange website that is supposed to do exactly this:

 for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
override = bpy.context.copy()
override['area'] = area
bpy.ops.view3d.view_selected()
break


assuming a model imported from an *.obj file is selected now. When I run it, nothing happens. However, Shift-C + OpenGL Render does pretty much what I need.

The context: I need to render many models from many viewpoints, but all models have different scale, so I wonder if there is a command that could move camera so that object regardless of its original size fits given specific viewpoint, like, direction in spherical or cylinder coordinates, for example. view_selected() and view_all() seem to do that.

Okay, this is a working script in case anyone might need similar thing:

import mathutils
import bpy
import sys

model_path = '/input/path/file.obj'

scene = bpy.data.scenes.new("OurScene")
camera_data = bpy.data.cameras.new("Camera")
camera = bpy.data.objects.new("Camera", camera_data)
camera.location = (-4.0, -5.0, -1.0)
scene.update()
scene.camera = camera
bpy.context.screen.scene = scene
bpy.data.cameras['Camera.001'].clip_end = 10000
bpy.context.scene.name = 'model.obj'
bpy.ops.import_scene.obj(filepath=model_path, axis_forward='-Z', axis_up='Y', filter_glob="*.obj;*.mtl")
bpy.context.scene.camera = camera
bpy.context.scene.render.filepath = '/output/render.jpg'
bpy.context.scene.world = bpy.data.worlds['World']

# look at origin
loc_camera = camera.matrix_world.to_translation()
direction = mathutils.Vector((0., 0., 0.)) - loc_camera
# point the cameras '-Z' and use its 'Y' as up
rot_quat = direction.to_track_quat('-Z', 'Y')
# assume we're using euler rotation
camera.rotation_euler = rot_quat.to_euler()

bpy.data.worlds['World'].light_settings.use_environment_light = True
bpy.data.scenes['model.obj'].render.alpha_mode = 'TRANSPARENT'
bpy.data.scenes['model.obj'].render.image_settings.color_mode = 'RGBA'

for obj in bpy.context.scene.objects:
obj.select = False

for obj in bpy.context.visible_objects:
if not (obj.hide or obj.hide_render):
obj.select = True

for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for region in area.regions:
if region.type == 'WINDOW':
override = {'area': area, 'region': region}
bpy.ops.view3d.camera_to_view_selected(override)

bpy.ops.render.render(write_still=True)

sys.exit(0)