How to place a mesh on segmented plane from an image using Blender python?

So I have a segmented mask of a tabletop, and I need to place an object on that tabletop. The position and orientation of the object have to be randomly sampled, but the object should always lie on the tabletop. The end goal is to generate a bunch of images with the object on the tabletop in various positions and orientations.

  1. Original image
  2. The segmented tabletop
  3. The desired result (this I achieved by positioning the object manually against the background image in the camera view in blender.):

I needed some guidance on how I could utilise the tabletop information to place the objects on it entirely using Blender python. I want to automate this entire process for batch processing using various meshes and background images with tabletops.