This error suggests we need to convert the image object to a PIL Image first. Here's the corrected code:
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D
from PIL import Image
import io
# Your provided data
smiles_list = ['CCO', 'c1ccccc1O', 'CNC(=O)N', 'CC(=O)Oc1ccccc1C(=O)OH']
mol_list = [Chem.MolFromSmiles(s) for s in smiles_list]
# Parameters
label_list = [f"Mol {i+1}: {smiles_list[i]}" for i in range(len(mol_list))]
molsPerRow = 2
subImgSize = (300, 300)
# Drawing options
opts = rdMolDraw2D.MolDrawOptions()
opts.legendFontSize = 18
opts.useBWAtomPalette()
# Generate and save the image
try:
# Method 1: Using Draw.MolsToImage
img = Draw.MolsToGridImage(
mol_list,
molsPerRow=molsPerRow,
legends=label_list,
subImgSize=subImgSize,
drawOptions=opts
)
# Convert to bytes
img_data = img.data
# Convert bytes to PIL Image
pil_img = Image.open(io.BytesIO(img_data))
# Save the image
output_filename = "molecule_grid.png"
pil_img.save(output_filename)
print(f"Image saved as: {output_filename}")
except Exception as e:
print(f"An error occurred: {e}")
# Alternative Method 2: Using Draw.MolsToImage directly to file
try:
output_filename2 = "molecule_grid2.png"
Draw.MolsToGridImage(
mol_list,
molsPerRow=molsPerRow,
legends=label_list,
subImgSize=subImgSize,
drawOptions=opts,
returnPNG=True
).save(output_filename2)
print(f"Image saved as: {output_filename2}")
except Exception as e:
print(f"An error occurred with method 2: {e}")
If you're still having issues, here's an even simpler version that should definitely work:
from rdkit import Chem
from rdkit.Chem import Draw
# Your provided data
smiles_list = ['CCO', 'c1ccccc1O', 'CNC(=O)N', 'CC(=O)Oc1ccccc1C(=O)OH']
mol_list = [Chem.MolFromSmiles(s) for s in smiles_list]
# Save directly to file
output_filename = "molecule_grid.png"
Draw.MolsToGridImage(mol_list, molsPerRow=2).save(output_filename)
print(f"Image saved as: {output_filename}")
If you're still getting errors, please let me know what error message you see and I can help troubleshoot further. Also, make sure you have both RDKit and Pillow (PIL) installed:
pip install rdkit pillow