1

I've noticed that when I create an image from a molecule in RDKit, the size argument leads to inconsistent scaling of the bond width and element labels. The bigger the size, the thinner the lines and the smaller the element labels.

I've run a test by generating an image for the same molecule using MolToImage at progressively bigger sizes. I rescaled those images to size=(600,600) and then concatenated them into a GIF. This is the result.

Resulting GIF

Here's my code

from glob import glob
from rdkit import Chem
from rdkit.Chem import Draw
from PIL import Image,ImageDraw,ImageFont


def make_frames_from_smi(smi):

    mol = Chem.MolFromSmiles(smi)

    for i in range(10):
        s = (i+3)*100
        mol = Chem.MolFromSmiles(smi)
        img = Draw.MolToImage(mol,size=(s,s))
        img = img.resize((600,600))
        draw = ImageDraw.Draw(img)

        text = '%d: Initial Size: (%d,%d)'%(i+1,s,s)

        font_size = 40
        font = ImageFont.truetype("arial.ttf", font_size)  # Use your desired font


        # Calculate text position
        image_width, image_height = img.size
        text_x = (image_width - (bbox[2] - bbox[0])) // 2
        text_y = 20  # Adjust the vertical position as needed

        draw.text((text_x, text_y), text, font=font, fill='black')
        img.save('%03dtest.png'%i)


def make_gif_from_frames(paths):

    frames_paths = glob(paths)
    frames = [Image.open(imgp) for imgp in frames_paths]

    frames[0].save("mols.gif", format="GIF", append_images=frames, save_all=True, duration=500, loop=False)



# make RDKit mol obj.
smi = 'CN(C)CC1CCCCC1(C2=CC(=CC=C2)OC)O'
make_frames_from_smi(smi)
make_gif_from_frames('*.png')

Is this expected behaviour? Is the bond width held constant for a certain absolute value of pixels? How can I generate these images with consistent proportions regardless of width/height of pixels?

J.Doe
  • 224
  • 1
  • 4
  • 19

0 Answers0