A new Monte Carlo technique for the simulation of secondary electron (SE) and backscattered electron (BSE) of scanning electron microscopy (SEM) images for an inhomogeneous specimen with a complex geometric structure has been developed. The simulation is based on structure construction modeling with simple geometric structures, as well as on the ray-tracing technique for correction of electron flight-step-length sampling when an electron trajectory crosses the interface of the inhomogeneous structures. This correction is important for the simulation of nanoscale structures of a size comparable with or even less than the electron scattering mean free paths. The physical model for electron transport in solids combines the use of the Mott cross section for electron elastic scattering and a dielectric function approach for electron inelastic scattering, and the cascade SE production is also included.