Reputation: 775
I am using RDKit in python to draw a molecule, and I want to get a high-definition image
This is my current code
mol = Chem.MolFromSmiles("CCO")
mol = Chem.AddHs(mol)
img = Draw.MolToImage(mol)
I want it to be ~ 2000x1000 pixels
I tried: img = Draw.MolToImage(mol, size = (2000,1000))
but although the canvas increases in size, the line width and font size remains constant.
Scaling with img.resize()
is not ok because I want to get a non-pixelated output.
The closes to an answer is this. However when I try creating its parent class I get an error:
>> a = Draw.rdMolDraw2D.MolDraw2D()
RuntimeError: This class cannot be instantiated from Python
tldr; I am trying to find out a way to scale the image while it is rendering.
I am also ok using an alternative to RDKit, all I need is a way to display chemical structures from SMILES in a high-def (2000x1000) image.
Side question: Is there a way to show carbon atoms too? Can't find any docs for both these questions.
Upvotes: 0
Views: 61
Reputation: 3061
This code works, see RDKit SetScale method for drawing:
import rdkit
print('\n-------------------------------')
print('\n rdkit Version : ', rdkit.__version__)
print('\n-------------------------------')
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Geometry.rdGeometry import Point2D
from PIL import Image
from io import BytesIO
mol = Chem.MolFromSmiles("CCO")
mol = Chem.AddHs(mol)
# drawer = Draw.MolDraw2DSVG(200, 400, 200, 200)
drawer = Draw.MolDraw2DCairo(200, 400, 200, 200)
minv = Point2D(1000, 1000)
maxv = Point2D(-1000, -1000)
drawer.SetScale(10, 10, minv, maxv)
drawer.DrawMolecule(mol)
drawer.SetOffset(0, 200)
drawer.DrawMolecule(mol)
drawer.FinishDrawing()
print('drawer.GetDrawingText() : ', drawer.GetDrawingText() , type(drawer.GetDrawingText()))
bio = BytesIO(drawer.GetDrawingText())
img = Image.open(bio)
img.save('test.png')
img.show()
Output:
But I still don't understand how SetScale works, especially the minv and maxv paramters in:
drawer.SetScale(50, 50, minv, maxv)
Upvotes: 0
Reputation: 775
I ended up first rendering as a svg and then scaling + converting to a png, here is the implementation:
from rdkit import Chem
from rdkit.Chem import Draw
import cairosvg #You can use some toher library to convert svg to png
mol = Chem.MolFromSmiles("CCO")
mol = Chem.AddHs(mol)
drawer = Draw.MolDraw2DSVG(300, 150) #You can adjust this, however to keep it looking good, both width,height should be between 150-400 inclusive.
drawer.DrawMolecule(mol)
drawer.FinishDrawing()
svg_data = drawer.GetDrawingText()
cairosvg.svg2png(bytestring=svg_data.encode('utf-8'), write_to="molecule.png", scale=10) #Adjust scale for higher-def image
Upvotes: 0