foreground color versus background color

Hello,
I have a graphic, that is built with matpotlib facilities. I display some texts with a color for the text and a color for the corresponding background. I want to optimize the lisibility of such texts, then I shall adapted the background color to the foreground color. For example, when background is 'black', a good foreground is 'white' and conversely, but supposing that foreground colors are randomly allocated, it is rather complicated.
Is there any method based on rgb parameters to deduce background color from foreground color ?
Thank you