Is there a way to know (programmatically) how many objects are visibile in a rendering? i'm new here, i browsed a bit before posting but i haven't found any solution yet. I'm writing a small script to create several random
images with spheres of different sizes and i'm looking for a way to know
how many of them are visible in a render. The final idea is to have a dataset to test some computer vision algorithms such as that i have the number of objects present in each image.
I'm attaching the script so far.

#!/usr/bin/python2.7
import bpy
import bpy_extras
import random
import math

def makeMaterial(name, diffuse, specular, alpha):
    mat = bpy.data.materials.new(name)
    mat.diffuse_color = diffuse
    mat.diffuse_shader = 'LAMBERT'
    mat.diffuse_intensity = 1.0
    mat.specular_color = specular
    mat.specular_shader = 'COOKTORR'
    mat.specular_intensity = 0.5
    mat.alpha = alpha
    mat.ambient = 1
    return mat

def setMaterial(ob, mat):
    me = ob.data
    me.materials.append(mat)

def createSphere(loc, siz, material):
    origin = (0,0,0)
    bpy.ops.mesh.primitive_uv_sphere_add(location=loc, size=siz)
    #bpy.ops.transform.translate(value=(1,0,0))
    #bpy.context.object.location = location
    setMaterial(bpy.context.object, material)



def createScene():
    #Cleaning the scene
    bpy.ops.object.select_by_type(type='MESH')
    bpy.ops.object.delete()

    #Create a material
    materials = (makeMaterial('Red',(1,0,0),(1,1,1),1),
                 makeMaterial('Green',(0,1,0),(1,1,1),1),
                 makeMaterial('Blu',(0,0,1),(1,1,1),1))

    rand = random.randrange(50)
    print ("Number of spheres %s" % rand)
    for i in range(rand):
        location = (random.random()*10-5, random.random()*10-5, 0)
        size = random.random()
        createSphere(location, size, materials[int(random.randrange(3))])

def render():
    step_count = 32

    for step in range(0, step_count):
        cam.rotation_euler[2] = math.radians(step * (360.0 / step_count))

        bpy.data.scenes["Scene"].render.filepath = '/home/daniele/VR/vr_shot_%d.jpg' % step
        bpy.ops.render.render( write_still=True )

#Set a seed to make reproducible
random.seed(32)
cam = bpy.data.objects['Camera']
createScene()

render()
You can give each object a unique object ID ("pass index" in the object properties).These can be output as render pass; each pixel will have the ID of the object that's visible there. This will not only give you a count of the number of objects (just count the number of unique values) but also a ground truth for segmentation &amp; shape recognition. 

This Python script will give each selected object another ID:

import bpy

for nr, obj in enumerate(bpy.context.selected_objects):
    obj.pass_index = nr + 1  # reserve pass index 0 for "no object".


For more info, see the ID Mask Node section of the Blender manual.