Skip to content
The Chat Archive
command-a-03-2025· Cohere LMArena Human Preference 140K

An error occurred while generating or saving the PIL image: 'Image' object has no…

  1. User

    An error occurred while generating or saving the PIL image: 'Image' object has no attribute 'save'

  2. Assistant

    The error 'Image' object has no attribute 'save' occurs because the image object returned by MolsToGridImage in RDKit is not a PIL (Pillow) image object by default. Instead, it's an RDKit-specific image object. To save it as a file, you need to convert it to a PIL image first.

    Here’s the corrected code to generate the molecule grid and save it as a file using PIL (Pillow):

    from rdkit import Chem
    from rdkit.Chem import Draw
    from PIL import Image
    import numpy as np
    
    # Example SMILES list
    smiles_list = ['CCO', 'c1ccccc1O', 'CNC(=O)N', 'CC(=O)Oc1ccccc1C(=O)OH']
    
    # Convert SMILES to RDKit molecule objects
    mol_list = [Chem.MolFromSmiles(s) for s in smiles_list]
    
    # Optional: Create labels (using SMILES in this example)
    label_list = smiles_list
    
    # Generate the grid image
    molsPerRow = 2
    img = Draw.MolsToGridImage(
        mol_list,
        molsPerRow=molsPerRow,
        legends=label_list,
        subImgSize=(300, 300),
        useSVG=False  # Ensure it returns a bitmap image
    )
    
    # Convert RDKit image to PIL Image
    img_np = img.convert('RGB')  # Convert to RGB format
    pil_img = Image.fromarray(np.asarray(img_np))
    
    # Save the PIL image to a file
    pil_img.save("molecule_grid.png")
    

    Explanation of Changes:

    1. Import Pillow and NumPy:

      • PIL.Image is used to handle image saving.
      • numpy is used to convert the RDKit image to a NumPy array, which can then be converted to a PIL image.
    2. Convert RDKit Image to PIL Image:

      • img.convert('RGB') ensures the image is in RGB format.
      • np.asarray(img_np) converts the RDKit image to a NumPy array.
      • Image.fromarray() creates a PIL image from the NumPy array.
    3. Save the PIL Image:

      • pil_img.save("molecule_grid.png") saves the image to a file.

    Alternative: Using Image.frombytes (if needed)

    If the above method doesn't work, you can use Image.frombytes:

    from io import BytesIO
    
    # Convert RDKit image to bytes
    img_bytes = BytesIO()
    img.save(img_bytes, format='PNG')  # RDKit's save method
    img_bytes.seek(0)
    
    # Create PIL image from bytes
    pil_img = Image.open(img_bytes)
    
    # Save the PIL image to a file
    pil_img.save("molecule_grid.png")
    

    This should resolve the error and successfully save the molecule grid as an image file. Let me know if you encounter further issues!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.