3

enter image description here

Suppose I have the following camera perspective.

As you can see some of the Cube vertices are visible from the camera, others are not.

Is there a way from python to detect if a certain vertex is in the camera field of view or not?

zeffii
  • 39,634
  • 9
  • 103
  • 186
wsfax
  • 396
  • 3
  • 10
  • related http://blender.stackexchange.com/questions/14711/does-cycles-use-a-camera-frustum-check – Chebhou Jun 25 '15 at 17:14

1 Answers1

3
import bpy
import bmesh
from mathutils import Vector
from bpy_extras.object_utils import world_to_camera_view

scene = bpy.context.scene
cam = bpy.data.objects['Camera']
obj = bpy.data.objects['Cube']
mesh = obj.data
mat_world = obj.matrix_world
cs, ce = cam.data.clip_start, cam.data.clip_end

assert obj.mode == "EDIT"
bm = bmesh.from_edit_mesh(mesh)

for v in bm.verts:
    co_ndc = world_to_camera_view(scene, cam, mat_world @ v.co)
    #check wether point is inside frustum
    if (0.0 < co_ndc.x < 1.0 and
        0.0 < co_ndc.y < 1.0 and
        cs < co_ndc.z <  ce):
        v.select = True
    else:
        v.select = False

bmesh.update_edit_mesh(mesh, False, False)
vwvw
  • 133
  • 6
pink vertex
  • 9,896
  • 1
  • 25
  • 44
  • I am trying to run the above code in Blender 2.8, but it throws errors. Is an update possible? – vndep Sep 10 '19 at 20:42
  • For Blender 2.8+ replace the last line with bmesh.update_edit_mesh(mesh). Make sure the object is in Edit mode. – Blunder Dec 06 '22 at 23:36