parser=ArgumentParser(description='Convert image to a surface for OpenSCAD and a .stl if desired.')
parser.add_argument('imagefile',metavar='IMAGEFILE',type=str,help='The path to the image file you want to convert to a surface.')
parser.add_argument('-i',dest='inverse',action='store_const',const=True,default=False,help='Defaults to white as a background, this option makes black the background.')
parser.add_argument('-r',dest='removebase',action='store_const',const=True,default=False,help='Remove base layer from surface. Only applies if exporting to .scad and/or .stl.')
parser.add_argument('-d',dest='maxdim',type=int,default=150,help='The maximum size in mm to make the x or y dimension. Only applies if exporting to .scad and/or .stl.')
parser.add_argument('-z',dest='zheight',type=int,default=5,help='The max z-height of the text, defaults to 5')
parser.add_argument('-o',dest='filename',type=str,default='image2surface.dat',help='By default, this script just outputs textsurface.dat, which can be imported into an OpenSCAD document. If you specify a .scad filename for this parameter, the script will also output a .scad file which imports the surface. If you specify a .stl filename, the script will go further and generate a .stl file.')
returnparser.parse_args()
defget_image_data(imagefile):
im=Image.open(imagefile)
return[list(im.getdata()),im.size[0],im.size[1]]
defcreate_dat(data,zheight,filename,inverse):
white=255*len(data[0])
textbuffer=''
line=[]
lines=[]
foriinrange(len(data)):
ifi%width==0andi!=0:
line.reverse()
lines.append(line)
line=[]
line.append(data[i])
# To data
forlineinlines:
textbuffer+='\n'
forpixelinline:
ratio=float(sum(pixel))/white
ifnotinverse:
ratio=1-ratio
# Numbers (with decimal places) must be reversed so
# that when the entire textbuffer is reversed later,