Python for generating CFDG files from images
Posted: Mon Jul 11, 2005 10:11 pm
Below is the Python code for converting any kind of image into a set of CFDG rules. It's hardly tested but seems to work alright. It was written under windows and requires the Python Imaging Library to be installed in order to work (you can google for that).
My commandline usage looks like this (from same directory your img2cfdg.py file is):
c:\Python24\python.exe img2cfdg.py mystartrule myprefix inputimage.jpg > out.cfdg
The startrule option is obvious, the prefix is a mechanism to avoid duplicate rule names if you will be including lots of images.
CFDG isn't supposed to be about pixels, but I thought this might be useful to anyone who wanted to import pixel based fonts (and share them with the rest of us).
enjoy
jimmy
My commandline usage looks like this (from same directory your img2cfdg.py file is):
c:\Python24\python.exe img2cfdg.py mystartrule myprefix inputimage.jpg > out.cfdg
The startrule option is obvious, the prefix is a mechanism to avoid duplicate rule names if you will be including lots of images.
CFDG isn't supposed to be about pixels, but I thought this might be useful to anyone who wanted to import pixel based fonts (and share them with the rest of us).
enjoy
jimmy
Code: Select all
import os, sys
import Image
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) < 4:
print "img2cfdg startrule prefix filenametoconvert"
sys.exit()
startrule = argv[1]
prefix = argv[2]
infile = argv[3]
try:
greyimg = Image.open(infile).convert("L")
except IOError:
print "cannot convert", infile
sys.exit()
gwidth, gheight = greyimg.size
print "startshape %s" % startrule
print "rule %s {" % startrule
#Call the rule for each row
for i in range(gheight):
# "gheight - i" because my jpegs were coming out upside down
# if your images come out upside down remove "gheight -"
# there should be a flag for this, but you have the code and i'm lazy
print "%s_row_%d { y %d }" % (prefix, i, gheight - i)
print "}"
#Rules for rows
for i in range(gheight):
print "rule %s_row_%d {" % (prefix, i)
for j in range(gwidth):
tshade = greyimg.getpixel( (j,i) )
print "SQUARE { x %d b %.3f }" % (j, tshade/255.0)
print "}"
if __name__ == "__main__":
main(["img2cfdg", "test", "test2","test1.jpg"])