Beispiel #1
0
 def main(self):
     self.outputBox.delete(1.0,Tkinter.END)
     while self.xmax.get()<=self.xmin.get() or self.ymax.get()<=self.ymin.get() or not self.checkFunction() or not self.saveFileLocation():
         if self.xmax.get()<=self.xmin.get() or self.ymax.get()<=self.ymin.get():
             output='Max must be greater than Min.'
         else:
             output=self.output
         self.outputBox.insert(Tkinter.END,output)
         return
     self.outputBox.insert(Tkinter.END,'Working... ')#This may take a while.')
     root.update()
     #start redirecting stdout:
     sys.stdout = self.StdoutRedirector(self.outputBox)
     heightArray=self.makeHeights()
     # make stl file
     if not heightArray.size:
         return
     else:
         numpy2stl (heightArray, self.fileLocation,
                    scale=self.scaleFactor, 
                    #mask_val=1, 
                    max_width=maxWidth,
                    max_depth=maxDepth,
                    max_height=maxHeight,
                    min_thickness_percent=minThickPct, #helps reduce waste at bottom
                    solid=bottom) #True means it will make a bottom
     self.outputBox.delete(1.0,Tkinter.END)
     self.outputBox.insert(Tkinter.END,'Program is finished.')
     #stop redirecting stdout:
     sys.stdout = sys.__stdout__
Beispiel #2
0
def stl_flat_maker(data, scale=100, width=100, depth=100, height=20):
    '''
	This uses the stl_tools numpy2stl in order to convert an array into a 3D printable
	model. This cannot take xyz dimensions and cannot make the full 3D model. It makes the
	2D image 3D printable.
	
	Parameters:
	
	data : a numpy array that represents some sort of image to be made into a stl file
	
	scale : float, the percent ratio of the actual height vs the original height. A scale
	of 150 turns a height into 1.5 times more when compared to width than originally.
	 
	width : float, max width in mm
	 
	depth : float, max depth in mm
	 
	height : float, max height in mm
	'''

    print('making mesh...')

    data = 4 * data
    data = imresize(data, (512, 512))
    data = gaussian_filter(data, 1)

    numpy2stl(data,
              '~/Desktop/test.stl',
              scale=scale,
              solid=True,
              max_width=width,
              max_depth=depth,
              max_height=height)
Beispiel #3
0
def make_stl_from_image(image_file):

    A = 256 * imread(image_file)
    A = gaussian_filter(A, 1)
    numpy2stl(A, TEXT_STL_FILE, scale=0.25, mask_val=1, solid=True)

    return TEXT_STL_FILE
Beispiel #4
0
def png2stl(fname_png,
            fname_stl,
            should_invert=False,
            smoothing=0,
            red_factor=1,
            scale=0.1,
            min_thickness_percent=0.1,
            max_width=MAX_WIDTH,
            max_height=MAX_HEIGHT,
            max_depth=MAX_DEPTH):
    if should_invert:
        data = invert_image(fname_png)
    else:
        data = 256 * imread(fname_png)

    data = data[:, :,
                2] + red_factor * data[:, :,
                                       0]  # Compose RGBA channels to give depth -> B + red_factor * R
    data = gaussian_filter(data, smoothing)
    numpy2stl(
        data,
        fname_stl,
        scale=scale,
        max_width=max_width,
        max_height=max_height,
        max_depth=max_depth,
        solid=True,
        min_thickness_percent=min_thickness_percent,
    )
def post_process(paras, cwtmatr, b, fs, times, freqs):
	zz = sqrt(cwtmatr**2)

	# Smooth out the output with gaussian kernel
	if paras['filter_gaussian'] != [1, 1]:
		zz = ndimage.filters.gaussian_filter(zz, paras['filter_gaussian'], mode='constant')

	# Downsampling output:
	zz = zz[::paras['downsampling_array'][0],::paras['downsampling_array'][1]]
	times = times[::paras['downsampling_array'][0]]
	freqs = freqs[::paras['downsampling_array'][1]]
	b = b[::paras['downsampling_array'][0]]

	# Save numpy array
	if not paras['output_pic'] is None:
		path = jn(paras['results_dir'], paras['output_pic'])
		print ('Saving .pic file as', path)
		with open(path, 'wb') as f:
			pickle.dump((b, zz, times, freqs), f)

	# Save stl file
	path = jn(paras['results_dir'], paras['output_stl'])
	print ('Saving .stl file as', path)
	numpy2stl(zz, path, **paras['stl_options'])

	# Rescale x/y axis
	the_mesh = mesh.Mesh.from_file(path)
	xsize =	the_mesh.x.max() -	the_mesh.x.min()
	ysize =	the_mesh.y.max() -	the_mesh.y.min()

	the_mesh.y = the_mesh.y*(xsize/ysize)/paras['ratio_xy']

	the_mesh.save(path)

	return b, zz, times, freqs
def stl_file_maker(file, interval=1.5, threshold=0.35, fname='test.stl', gaussian=1):
	'''
	This uses the stl_tools numpy2stl in order to convert an array into a 3D printable
	model. This cannot take xyz dimensions and cannot make the full 3D model. It makes the
	2D image 3D printable.

	Parameters:

	file : str, name of the file, should be png

	interval : float, rate at which points are taken from the image

	threshold : float, minimum threshold for intensity value

	fname : str, name of exported file

	gaussian : int, number of loops of gaussian filtering data goes through
	'''

	earth_radius = 6371 #km

	scale_factor_percent = 0.3

	#Does not work with cropped image 
	#data = io.read_file('2014_05_27__14_38_31_12__SDO_AIA_AIA_304.jp2')	
	header = io.read_file_header(file+'.jp2')

	image = read_png(file+'.png')

	km_per_pixel = km_per_pixel(arcs_per_pix=header[0].__getitem__('IMSCL_MP'))

	#center points for the earth to scale figure

	earth_scale_y = 35
	earth_scale_x = image.shape[1] - 35 #px
	earth_box = 2
	
	earth_radius_px = earth_radius / km_per_pixel 
	
	for xpoint in range(data.shape[0]):
		for ypoint in range(data.shape[1]):
			if (np.sqrt((xpoint - earth_scale_x)**2 + (ypoint - earth_scale_y)**2) <= earth_radius_px):
				data[xpoint][ypoint] = 0.1
			elif (((np.absolute(xpoint - (earth_scale_x - earth_scale_y)) < earth_box) & (ypoint < (2. * earth_scale_y))) 
				or (((np.absolute(ypoint - (2. * earth_scale_y)) < earth_box)) & (xpoint > (earth_scale_x - earth_scale_y)))):
				data[xpoint][ypoint] = 0.05
			elif (data[xpoint][ypoint] <= threshold):
				data[xpoint][ypoint] = 0
			else:
				data[xpoint][ypoint] = (data[xpoint][ypoint] - threshold) / (1 - threshold)

	data = resize(data, (int(data.shape[0]/interval), int(data.shape[1]/interval)))
	
	data = gaussian_filter(data, gaussian)
	
	#dimensions in mm, if scale = 100, then the dimensions will be exact
	numpy2stl(data, fname, scale=100, solid=True, max_width=228.6, 
	max_depth=228.6, max_height=80, force_python=True)	

	subprocess.call(['bash', 'filemover.sh', fname])
Beispiel #7
0
 def __init__(self, mesh):
     super().__init__(mesh)
     stl_tools.numpy2stl(self.mesh,
                         self.name + '.stl',
                         scale=1,
                         mask_val=0.5,
                         force_python=True,
                         square_corners=True)
Beispiel #8
0
def image2stl():
    """
    Provides a command-line interface to numpy2stl
    """

    parser = ArgumentParser()
    parser.add_argument("f", help='Source image filename')
    parser.add_argument("-o", default="", help='Output filename')

    parser.add_argument("-RGBA_weights", default=[""], nargs=4)
    parser.add_argument("-gaussian_filter", default="")

    float_group = parser.add_argument_group('float inputs:')
    for varname in _float_args:
        float_group.add_argument(''.join(["-", varname]), default="")

    bool_group = parser.add_argument_group('boolean inputs')
    for varname in _bool_args:
        bool_group.add_argument(''.join(["-", varname]), default="")

    args = vars(parser.parse_args())

    f_args = {
        f_arg: float(args[f_arg])
        for f_arg in _float_args if args[f_arg]
    }
    b_args = {
        b_arg: bool(int(args[b_arg]))
        for b_arg in _bool_args if args[b_arg]
    }

    kwargs = dict(f_args, **b_args)

    src = args['f']
    fn = args['o']
    if not fn:
        fn = '.'.join([src.split('.')[0], "stl"])

    A = 256. * imread(src)
    L = len(A.shape)
    w = args['RGBA_weights']
    if L > 2:
        if len(w) >= L:
            A = np.sum([float(w[i]) * A[:, :, i] for i in range(A.shape[-1])],
                       axis=0)
        else:
            A = A.mean(axis=2)

    if args['gaussian_filter']:
        A = gaussian_filter(A, float(args['gaussian_filter']))

    numpy2stl(A, fn, **kwargs)
Beispiel #9
0
    def online_music_3d(self, artist_name, track_name, mode="loudness_max"):
        """ Gets information from The Echo Nest services 
            and creates a 3D model of the input song.

        Args:
            artist_name: name of the artist
            track_name: name of the track
            mode: musical parameter to be used to create the 3D model
                  options: loudness_max, pitches, timbre

        """

        # Interact with The Echo Nest services
        self.en = pyen.Pyen(self.EN_API_KEY)
        print("Searching " + track_name + " by " + artist_name +
              " on The Echo Nest")
        audio_segments = self._get_segments(self.en, artist_name, track_name)
        if audio_segments is not None:
            audio_features = self._get_features_list(audio_segments, mode)

            if mode == 'loudness_max':  # waveform mode
                loudness_list = self._process_loudness_list(audio_features)
                loudness_list = self._rescale_list(loudness_list, 0,
                                                   self.height_Y)
                processed_waveform = self.make_waveform_square(
                    loudness_list, self.n_waveform_bars)
                model_3d = self.make_waveform_3d(processed_waveform,
                                                 self.height_Z)

            else:  # pitches or timbre
                new_features = []
                for af in audio_features:
                    new_features.append(
                        self._rescale_list(af, self.min_absolute_value,
                                           self.height_Z))
                new_features = self._increase_model_depth(
                    new_features, self.depth_factor)
                model_3d = np.array(new_features)

            # Export 3D model
            print("Exporting the 3D file")
            if self.OUTPUT_FOLDER[-1] != '/':
                self.OUTPUT_FOLDER.append('/')
            output_filename = self.OUTPUT_FOLDER + artist_name + " - " + track_name + "_" + mode + ".stl"
            numpy2stl(model_3d,
                      output_filename,
                      scale=self.scale,
                      mask_val=self.mask_val,
                      solid=True)
Beispiel #10
0
def create_grating(col, row, width, pitch):
    height = pitch // 2
    columnar_matrix = structure_methods.columnar_generator(col, row, width, height)

    # Make a numpy array    
    columnar_matrix_numpy =  numpy.array(columnar_matrix)

    # This line sets the threshold to NaN rather than 0 (flat grating)
    numpy.set_printoptions(threshold = numpy.nan)

    #print(columnar_matrix_numpy)

    # Making the .stl file
    fn = "default.stl"
    stl_tools.numpy2stl(columnar_matrix_numpy, fn, scale=1, mask_val = 1, force_python=True, square_corners=True)
Beispiel #11
0
def image2stl():
    """
    Provides a command-line interface to numpy2stl
    """

    parser = ArgumentParser()
    parser.add_argument("f", help='Source image filename')
    parser.add_argument("-o", default="", help='Output filename')

    parser.add_argument("-RGBA_weights", default=[""], nargs=4)
    parser.add_argument("-gaussian_filter", default="")

    float_group = parser.add_argument_group('float inputs:')
    for varname in _float_args:
        float_group.add_argument(''.join(["-", varname]), default="")

    bool_group = parser.add_argument_group('boolean inputs')
    for varname in _bool_args:
        bool_group.add_argument(''.join(["-", varname]), default="")

    args = vars(parser.parse_args())

    f_args = {f_arg: float(args[f_arg])
              for f_arg in _float_args if args[f_arg]}
    b_args = {b_arg: bool(int(args[b_arg]))
              for b_arg in _bool_args if args[b_arg]}

    kwargs = dict(f_args, **b_args)

    src = args['f']
    fn = args['o']
    if not fn:
        fn = '.'.join([src.split('.')[0], "stl"])

    A = 256. * imread(src)
    L = len(A.shape)
    w = args['RGBA_weights']
    if L > 2:
        if len(w) >= L:
            A = np.sum([float(w[i]) * A[:, :, i]
                       for i in range(A.shape[-1])], axis=0)
        else:
            A = A.mean(axis=2)

    if args['gaussian_filter']:
        A = gaussian_filter(A, float(args['gaussian_filter']))

    numpy2stl(A, fn, **kwargs)
def create_qr(qr_code_string, out_or_in, border_size, length_width, height,
              base_percentage):
    print qr_code_string
    print out_or_in
    print length_width
    print border_size
    print height
    print base_percentage
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=6,
        # This will modify the border default 2
        border=border_size,
    )
    qr.add_data(qr_code_string)
    qr.make(fit=True)
    img = qr.make_image()
    out_or_in_method(out_or_in, img)
    A = imread("img.png") * 256

    stl = numpy2stl(A,
                    "qr.stl",
                    scale=height,
                    mask_val=0.0,
                    solid=True,
                    min_thickness_percent=base_percentage,
                    max_width=length_width,
                    max_depth=length_width,
                    max_height=1000)
    return stl
Beispiel #13
0
    def test_png(self):
        """ Tests creation of an STL from a PNG.
        Covers the numpy2stl function.
        """
        output_name = "OUT_.stl"
        # test ascii output
        A = 100 * np.random.randn(64, 64)
        numpy2stl(A, output_name, scale=0.05, mask_val=3., ascii=True)
        assert os.path.exists(output_name)
        assert os.stat(output_name).st_size > 1e5

        # test binary output
        numpy2stl(A, output_name, scale=0.05, mask_val=3.)
        assert os.path.exists(output_name)
        assert os.stat(output_name).st_size > 1e5
        os.remove(output_name)
Beispiel #14
0
 def main(self):
     self.outputBox.delete(1.0,Tkinter.END)
     try:
         area=float(self.area.get())
     except ValueError:
         output=self.area.get()+' is not a number, try again.'
         self.outputBox.insert(Tkinter.END,output)
         return
     else:
         while self.high.get()<=self.low.get() or area<=0 or not self.fileLocation or self.fileType not in fileTypes:# or area>=100000:
             if self.high.get()<=self.low.get():
                 output='High Point must be greater than Low Point.'
             elif area<=0:#not self.fileLocation:
                 output='Please enter a valid area.'# between 0 and 100,000 square kilometers.'
             else:
                 output='Please choose a .png file.'
             self.outputBox.insert(Tkinter.END,output)
             return
     self.outputBox.insert(Tkinter.END,'Working... ')#This may take a while.')
     root.update()
     #start redirecting stdout:
     sys.stdout = self.StdoutRedirector(self.outputBox)
     fileName,imgSmall=self.prepareImage()
     heightArray=self.makeHeights(imgSmall)
     heightDiffMeters=self.high.get()-self.low.get()
     heightDiffColors=heightArray.max()-heightArray.min()
     #pixels translate to millimeters 
     sqrtAreaMM=(self.height*self.width)**.5
     #user entered area in square kilometers converted to meters
     sqrtAreaM=(float(self.area.get())*1000000)**.5
     #adjusts the height of the model based on the difference in heights
     scaleFactor=self.vertExag.get()*(sqrtAreaMM/sqrtAreaM)*heightDiffMeters/(heightDiffColors*self.imageScale)
     #set minimum thickness
     totalHeight=scaleFactor*heightDiffColors
     minThickPct=minThickHeight/totalHeight
     numpy2stl (heightArray, fileName+".stl",
                scale=scaleFactor, #maximum height?
                #mask_val=1, #cuts off bottom to make islands
                max_width=maxWidth,
                max_depth=maxDepth,
                max_height=maxHeight,
                min_thickness_percent=minThickPct, #helps reduce waste at bottom
                solid=bottom) #True means it will make a bottom
     self.outputBox.delete(1.0,Tkinter.END)
     self.outputBox.insert(Tkinter.END,'Program is finished.')
     #stop redirecting stdout:
     sys.stdout = sys.__stdout__
Beispiel #15
0
def convert_to_stl(image_matrix,
                   output_file_directory,
                   base=False,
                   output_scale=0.1):
    """
    Converts the image matrix into an STL file and save it at output_file_directory
    NOTE: This function currently only supports grayscale

    :required_parameter image_matrix: (numpy.ndarray) A 2D array of pixels representing an image
    :required_parameter output_file_directory: (string) The filename of the resulting STL file
    :optional_parameter output_scale: decides the height scaling of the resulting STL mesh
    :optional_parameter base: (boolean) A boolean value specifying whether or not
        to include a base into the resulting STL file
    """

    make_it_solid = True  # Change this False to make it hollow; True to make the image solid
    exclude_gray_shade_darker_than = 1.0  # Change this to change what colors should be excluded
    # exclude_gray_shade_below = 1.0 should exclude only black pixels; but I'm not sure

    # this option controls whether or not stl_tools uses the c library
    # toggle this on if said c library causes issues
    python_only = False

    if base:
        numpy2stl(image_matrix,
                  output_file_directory,
                  scale=output_scale,
                  solid=make_it_solid,
                  force_python=python_only)
    else:
        numpy2stl(image_matrix,
                  output_file_directory,
                  scale=output_scale,
                  solid=make_it_solid,
                  mask_val=exclude_gray_shade_darker_than,
                  force_python=python_only)
def create_qr(qr_code_string, out_or_in, border_size, length_width, height, base_percentage):
    print qr_code_string
    print out_or_in
    print length_width
    print border_size
    print height
    print base_percentage
    qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=6,
            # This will modify the border default 2
            border=border_size,
    )
    qr.add_data(qr_code_string)
    qr.make(fit=True)
    img = qr.make_image()
    out_or_in_method(out_or_in, img)
    A = imread("img.png") * 256

    stl = numpy2stl(A, "qr.stl", scale=height, mask_val=0.0, solid=True, 
            min_thickness_percent=base_percentage, max_width=length_width, 
            max_depth=length_width, max_height=1000)
    return stl
Beispiel #17
0
from stl_tools import numpy2stl
from scipy.misc import lena, imresize
from scipy.ndimage import gaussian_filter
from pylab import imread
import sys

file_name = str(sys.argv[1])
scale_fl = float(sys.argv[2])
blur_fl = float(sys.argv[3])

img = 350 * imread("./.tmp.img.png")
img = img[:, :, 2] + 1.0*img[:,:, 0] # Compose RGBimg channels to give depth
img = gaussian_filter(img, blur_fl)  # smoothing
numpy2stl(img, file_name, scale=scale_fl, solid=True)
Beispiel #18
0
qr.make(fit=True)
img = qr.make_image()

out_or_in_method(out_or_in, img)
#img = Image.open("test/test.png")
#A = imread("test/test.png")
#rsize = img.resize((img.size[0]/10,img.size[1]/10))
#rsizeArray = np.asarray(rsize)

A = imread("img.png") * 256
# You still need to larn what the line below does
#A = A[:, :, 0] + 1.*A[: ,:, 2] # Compose RGBA channels to give depth
# Default min_thickness_percent = 1.5
# Default scale .05
length_width = float(raw_input("how many mm^2 do you want the qr code to be?"))
# .2 corresponds to about 1 cm
height = float(
    raw_input(
        "what %age of the length do you want to be the height / depth of the black bit?"
    ))
base_percentage = float(raw_input("what % do you want the base to take up?"))
numpy2stl(A,
          "qr.stl",
          scale=height,
          mask_val=0.0,
          solid=True,
          min_thickness_percent=base_percentage,
          max_width=length_width,
          max_depth=length_width)
#image2stl test/test.png -scale 0.04 -mask_val .0 -RGBA_weights 1. 0. 1. 0. -gaussian_filter .0
qr.add_data(qr_code_string)
qr.make(fit=True)
img = qr.make_image()

out_or_in_method(out_or_in, img)
# img = Image.open("test/test.png")
# A = imread("test/test.png")
# rsize = img.resize((img.size[0]/10,img.size[1]/10))
# rsizeArray = np.asarray(rsize)

A = imread("img.png") * 256
# You still need to larn what the line below does
# A = A[:, :, 0] + 1.*A[: ,:, 2] # Compose RGBA channels to give depth
# Default min_thickness_percent = 1.5
# Default scale .05
length_width = float(raw_input("how many mm^2 do you want the qr code to be?"))
# .2 corresponds to about 1 cm
height = float(raw_input("what %age of the length do you want to be the height / depth of the black bit?"))
base_percentage = float(raw_input("what % do you want the base to take up?"))
numpy2stl(
    A,
    "qr.stl",
    scale=height,
    mask_val=0.0,
    solid=True,
    min_thickness_percent=base_percentage,
    max_width=length_width,
    max_depth=length_width,
)
# image2stl test/test.png -scale 0.04 -mask_val .0 -RGBA_weights 1. 0. 1. 0. -gaussian_filter .0
 def __init__(self, mesh):
     super().__init__(mesh)
     stl_tools.numpy2stl(
         self.mesh, self.name + ".stl", scale=1, mask_val=0.5, force_python=True, square_corners=True
     )
queue = conn.create_queue(queue_name)
# Long Polling Setting
queue.set_attribute('ReceiveMessageWaitTimeSeconds', 20)

i=0
while 1:
    # fetch 10 messages
    msgs = queue.get_messages(10)
    for msg in msgs:
        pythoned_json = json.loads(msg.get_body().encode('utf_8'), encoding='utf-8')
        for corp,resp in pythoned_json.items():
          # sys.stderr.write("recv%s: %s\n" % (str(i), resp['title'].encode('utf_8')))
          text = resp['title'].encode('utf_8')

          # text convert to stl
          # text2png(text, "images/test", fontsize=1) #save png
          shell = "sh convert.sh '" + text + "'"
          os.system(shell)
          A = imread("images/convert.png") # read from rendered png
          A = A.mean(axis=2) #grayscale projection
          #A = gaussian_filter(A.max() - A, 1.)
          filename = "images/" + corp + ".stl"
          numpy2stl(A, filename)

        i = i+1
        # delete message
        queue.delete_message(msg)

    dt = datetime.today().strftime('%Y/%m/%d %H:%M:%S')
    sys.stderr.write("%s loop...\n" % (dt))
import math
import structure_methods
import argparse

if __name__ == "__main__":

    # Processing user input
    parser = argparse.ArgumentParser()
    parser.add_argument("no_columns", type=int, help="Number of columns in total structure")
    parser.add_argument("no_rows", type=int, help="Number of rows in total structure")
    parser.add_argument("slit_width", type=int, help="Width of one slit")
    parser.add_argument("pitch", type=int, help="Diffraction grating pitch")
    parser.add_argument("--strut_width", type=int, help="Specifies slit width, defaults to 1 unit")
    parser.add_argument("--frame_boarder", type=int, help="Specifies frame boarder width, defaults to 1 unit")
    parser.add_argument("--file_name", help="Specifies output file name, defaults to 'default.stl'")
    args = parser.parse_args()

    columnar_matrix = structure_methods.columnar_generator(args.no_columns, args.no_rows, args.slit_width, args.pitch)

    # Make a numpy array
    columnar_matrix_numpy = numpy.array(columnar_matrix)

    # This line sets the threshold to NaN rather than 0 (flat grating)
    numpy.set_printoptions(threshold=numpy.nan)

    # print(columnar_matrix_numpy)

    # Making the .stl file
    fn = "bigger_default.stl"
    stl_tools.numpy2stl(columnar_matrix_numpy, fn, scale=1, mask_val=1, force_python=True, square_corners=True)
#Written by ChocolateBubbles and RobertABT, 2014
#I strongly believe the .whatever format should be universal...

import region,sys

from pylab import imread
from scipy.ndimage import gaussian_filter
from stl_tools import numpy2stl
file = open('out.txt','w')
file.write("begin \n")
# usrselectedcoords = raw_input("Please enter desired Ordnance Survey map reference to be used: ")
usrselectedcoords = sys.argv[1]
usrselectedheight = sys.argv[2]
file.write("got past usr \n")
r = region.Region()
file.write("got past define region \n")
r.readgr (usrselectedcoords)
file.write("got past readgr \n")
filename = str('../public/generated/GENERATED_' + usrselectedcoords + '_scale_' + usrselectedheight + '.stl')
file.write("got to filename \n")
numpy2stl((r.grid / int(usrselectedheight)),filename, solid=True)
file.write("numpy2stl successfull \n")
file.write('finished')
Beispiel #24
0
from scipy.misc import lena
from pylab import imread
from scipy.ndimage import gaussian_filter
from stl_tools import numpy2stl, text2png


"""
Some quick examples
"""

A = lena()  # load Lena image, shrink in half
A = gaussian_filter(A, 1)  # smoothing
numpy2stl(A, "examples/Lena.stl", scale=0.1, solid=False)

A = 256 * imread("examples/example_data/NASA.png")
A = A[:, :, 2] + 1.0*A[:,:, 0] # Compose RGBA channels to give depth
A = gaussian_filter(A, 1)  # smoothing
numpy2stl(A, "examples/NASA.stl", scale=0.05, mask_val=5., solid=True)

A = 256 * imread("examples/example_data/openmdao.png")
A =  A[:, :, 0] + 1.*A[:,:, 3] # Compose some elements from RGBA to give depth
A = gaussian_filter(A, 2)  # smoothing
numpy2stl(A, "examples/OpenMDAO-logo.stl",
          scale=0.05, mask_val=1., min_thickness_percent=0.005, solid=True)

text = ("$\oint_{\Gamma} (A\, dx + B\, dy) = \iint_{U} \left(\\frac{\partial "
        "B}{\partial x} - \\frac{\partial A}{\partial y}\\right)\ dxdy$ \n\n "
        "$\\frac{\partial \\rho}{\partial t} + \\frac{\partial}{\partial x_j}"
        "\left[ \\rho u_j \\right] = 0$")
# save png
text2png(text, "examples/Greens-Theorem_Navier-Stokes", fontsize=50)
Beispiel #25
0
from PIL import Image
from stl_tools import numpy2stl

from scipy.misc import imresize
from scipy.ndimage import gaussian_filter

import numpy as np

A = np.array(
    Image.open('/home/charmmaria/Pictures/IMG_20180513_131704.jpg').convert(
        'LA'))
A = np.array(
    Image.open('/home/charmmaria/Pictures/IMG_20180702_091844.jpg').convert(
        'LA'))
temp_shape = A.shape
A = imresize(A[:, :, 0], (256, 256))  # load Lena image, shrink in half
A = gaussian_filter(A, 1)  # smoothing
A.shape
A = np.reshape(A, temp_shape[0:2])
numpy2stl(A,
          "/home/charmmaria/Pictures/temp_black_mich.stl",
          scale=0.1,
          solid=False)
Beispiel #26
0
from stl_tools import numpy2stl
import numpy as np


def monkey_function(x, y):
    output = (x**3 - 3 * x * (y**2))
    if output < -4500:
        return -4500
    else:
        return output


z_array = np.zeros((300, 260))

for y in range(-130, 130, 1):
    line_of_z_values = []
    for x in range(-150, 150, 1):
        z_array[x + 150][y + 130] = monkey_function(x / 10, y / 10)

numpy2stl(z_array, "monkey_saddle.stl", scale=0.05, mask_val=5., solid=True)
Beispiel #27
0
def convert():
    A = cv2.imread('inverted_final.bmp')
    A = A.mean(axis=2)
    A = gaussian_filter(A.max() - A, 1.)

    numpy2stl(A, "CONVERTED_STL.stl", scale=0.2, mask_val=5.)
Beispiel #28
0
                        type=int,
                        help="Specifies slit width, defaults to 1 unit")
    parser.add_argument(
        "--frame_boarder",
        type=int,
        help="Specifies frame boarder width, defaults to 1 unit")
    parser.add_argument(
        "--file_name",
        help="Specifies output file name, defaults to 'default.stl'")
    args = parser.parse_args()

    columnar_matrix = structure_methods.columnar_generator(
        args.no_columns, args.no_rows, args.slit_width, args.pitch)

    # Make a numpy array
    columnar_matrix_numpy = numpy.array(columnar_matrix)

    # This line sets the threshold to NaN rather than 0 (flat grating)
    numpy.set_printoptions(threshold=numpy.nan)

    #print(columnar_matrix_numpy)

    # Making the .stl file
    fn = "bigger_default.stl"
    stl_tools.numpy2stl(columnar_matrix_numpy,
                        fn,
                        scale=1,
                        mask_val=1,
                        force_python=True,
                        square_corners=True)
Beispiel #29
0
    def local_audio_3d(self, filepath, mode="waveform"):
        """ Converts a local audio file into a 3D model.

        Args:
            filepath: string containing the path to the audio file
            mode: musical parameter to be used to create the 3D model
                  options: waveform, stft
        """

        print "Loading audio file " + filepath
        waveform, sr = librosa.load(filepath)

        if mode == "waveform":  # time domain analysis
            # Downsample waveform and store positive values only
            if len(waveform) > 1000:
                m = len(str(len(waveform)))
                downsample_factor = (10 ** (m-1-3) * int(str(len(waveform))[0]))  # 1k (i.e. 10^3) magnitude
            else:
                downsample_factor = 1
            half_waveform = [waveform[i] for i in xrange(len(waveform)) if waveform[i]>0 and i%downsample_factor==0]

            # Reshape and rescale waveform
            processed_waveform = self._movingaverage(half_waveform, self.ma_window_size)
            # processed_waveform = self._limit_spikes(half_waveform, np.mean(half_waveform), 5)
            processed_waveform = self._rescale_list(processed_waveform, 0, self.height_Y)
            processed_waveform = self.make_waveform_square(processed_waveform, self.n_waveform_bars)  # make waveform "square"

            # Convert 2D waveform into 3D
            print "Creating 3D model"
            model_3d = self.make_waveform_3d(processed_waveform, self.height_Z)

        else:  # frequency domain analysis
            self.mask_val /= 100
            # Get STFT magnitude
            print "Analyzing frequency components"
            stft = librosa.stft(waveform, n_fft=256)
            stft, phase = librosa.magphase(stft)
            # Downsample and rescale STFT
            if len(stft[0]) > 1000:
                m = len(str(len(stft[0])))
                downsample_factor = (10 ** (m-1-3)) * int(str(len(stft[0]))[0])  # 1k (i.e. 10^3) magnitude
            else:
                downsample_factor = 1
            new_stft = []
            for curr_fft in stft:
                min_loudness_value = max(curr_fft)
                ds_fft = [curr_fft[j] + min_loudness_value for j in xrange(len(curr_fft)) if j%downsample_factor==0]
                ds_fft = self._rescale_list(ds_fft, self.min_absolute_value, self.height_Z)
                new_stft.append(ds_fft)
            print "Creating 3D model"
            model_3d = np.array(new_stft)

        print "Exporting the 3D file"
        if self.OUTPUT_FOLDER[-1] != '/':
            self.OUTPUT_FOLDER.append('/')
        output_filename = self.OUTPUT_FOLDER + filepath.split('/')[-1][:-4] + "_" + mode + ".stl"
        numpy2stl(model_3d, 
                  output_filename, 
                  scale=self.scale, 
                  mask_val=self.mask_val, 
                  solid=True)
Beispiel #30
0
from scipy.misc import lena
from pylab import imread
from scipy.ndimage import gaussian_filter
from stl_tools import numpy2stl, text2png
import qrcode

#img = Image.open("test/test.png")
#A = imread("test/test.png") #rsize = img.resize((img.size[0]/10,img.size[1]/10))
#rsizeArray = np.asarray(rsize)

A = imread("test/eric_qr_neg.png") * 256
# You still need to larn what the line below does
#A = A[:, :, 0] + 1.*A[: ,:, 2] # Compose RGBA channels to give depth
numpy2stl(A,
          "test/eric_qr_out.stl",
          scale=0.05,
          mask_val=0.0,
          solid=True,
          min_thickness_percent=1.5,
          max_width=40.,
          max_depth=40.)
#image2stl test/test.png -scale 0.04 -mask_val .0 -RGBA_weights 1. 0. 1. 0. -gaussian_filter .0
Beispiel #31
0
#height = int(sys.argv[2])
height = 65535
print "max height: %d" % height

filesize = os.path.getsize("canberra-s1s.bin")

with open("canberra-s1s.bin", "rb") as f:
    a = []
    y = []
    bytes_read = 0
    word = f.read(2)
    while word != "":
	raw = float(unpack('h',word)[0])
	value = abs(raw /height * 100)
	
	#print '%d,%d,%f' % (x,y,value)
	y.append(value)

	if len(y) >= width:
	    a.append(y)
	    y = []
        word = f.read(2)
	bytes_read = bytes_read + 2
	if floor(bytes_read / 10000) % 10 == 0:
		sys.stdout.write("\r %d / %d (%f)" % (bytes_read, filesize, ((bytes_read/filesize)*100 )))
		sys.stdout.flush()

A=array(a)

numpy2stl(A, "out.stl", scale=0.5, solid=False)
Beispiel #32
0
# Company: Hexastorm
# Author: Henri Starmans
# Date: 17-3-2017

from stl_tools import numpy2stl
from scipy.ndimage import gaussian_filter
from pylab import imread

img = 256 * imread("freecadlogo.png")
img = img[:, :, 0] + 1. * img[:, :, 3]
img = gaussian_filter(img, 2)
numpy2stl(img, 'hexastorm.stl', scale=0.2, mask_val=5, solid=True)
Beispiel #33
0
                while (cap.isOpened()):
                    ret, frame = cap.read()
                    frame_counter += 1
                    cv2.imshow('timer', frame)
                    if cv2.waitKey(27) & 0xFF == ord('q'):
                        break
                    if frame_counter == cap.get(cv2.CAP_PROP_FRAME_COUNT):
                        break

                cap.release()
                cv2.destroyAllWindows()

            if (mse > 5 and mse < 400):
                stl = numpy2stl(
                    depth,
                    os.getcwd() +
                    "/SimpleFoam/constant/triSurface/depth_img.stl",
                    scale=1.5,
                    solid=False)

                folder_names = []
                orij_dir = ['constant', 'system', '0']
                for entry_name in os.listdir(os.getcwd() + '/SimpleFoam/'):
                    entry_path = os.path.join(os.getcwd() + '/SimpleFoam/',
                                              entry_name)
                    if os.path.isdir(entry_path):
                        folder_names.append(entry_name)

                for i in folder_names:
                    if i not in orij_dir:
                        f = os.path.join(os.getcwd() + '/SimpleFoam/' + i)
                        shutil.rmtree(f)
Beispiel #34
0
# from scipy.misc import lena, imresize
# from scipy.ndimage import gaussian_filter
# import scipy

#A = 256 * imread("NASA.png")
# https://github.com/thearn/stl_tools

# A = 256 * imread("macro5.png")
# print A.size
# print A.shape

# A = A[:, :, 0]+ A[:, :, 1]+ A[:, :, 2] #+ 1.0*A[:,:, 0] # Compose RGBA channels to give depth
#A =   A[:, :, 1] #+ 1.0*A[:,:, 0] # Compose RGBA channels to give depth
#print A
# A = gaussian_filter(A, 1)  # smoothing
#A = A[:, :, 0]
# A = -A # inverse the colors
#A = A+10

# print 'max '+ str(scipy.amax(A))
# print  'min '+ str(scipy.amin(A))
# print  'average '+ str(scipy.average(A))
# print  'median '+ str(scipy.median(A))

# numpy2stl(A, "leafHole2.stl", scale=2, mask_val=80, solid=True, max_width=150, max_depth=150,max_height=2)

from numpy import genfromtxt
my_data = genfromtxt('completeStucture1.000000_macroIteration_1.csv', delimiter=',')
numpy2stl(my_data, "caketopper.stl", solid=True)
Beispiel #35
0
#Written by ChocolateBubbles, 2014
#I strongly believe the .whatever format should be universal...

import region,sys

from pylab import imread
from scipy.ndimage import gaussian_filter
from stl_tools import numpy2stl
print 'Format required is as HP40 not hp40'
#usrselectedcoords = raw_input("Please enter desired Ordnance Survey map reference to be used: ")
print "Running " + sys.argv[1]
usrselectedcoords = sys.argv[1]
#usrselectedheight = raw_input('Choose scale to divide height by (5 is a good start point)')
print "Running " + sys.argv[2]
usrselectedheight = sys.argv[2]
#linus's updates
#usrselectedcoords = usrselectedcoords.replace(" ","")
#usrselectedcoords = usrselectedcoords.upper()

r = region.Region()
r.readgr (usrselectedcoords)

print "Generating STL file from map data..."
filename = str('GENERATED_' + usrselectedcoords +'_scale_' + usrselectedheight + '.stl')
numpy2stl((r.grid / int(usrselectedheight)), 'generatedstl/' + filename, solid=True)
print 'Done! ' + filename + ' is now ready to print!'
Beispiel #36
0
from pylab import imread
from stl_tools import numpy2stl
from scipy.misc import imresize
from scipy.ndimage import gaussian_filter

A = 256 * imread("cantcatchme-2-fs.png")
A = imresize(A, (256, 256))
A = A[:, :, 2] + 1.0 * A[:, :, 0]  # Compose RGBA channels to give depth
A = gaussian_filter(A, 1)  # smoothing
numpy2stl(A, "gary2.stl", scale=0.1, mask_val=5., solid=True)
from scipy.misc import lena
from pylab import imread
from scipy.ndimage import gaussian_filter
from stl_tools import numpy2stl, text2png
import qrcode

#img = Image.open("test/test.png")
#A = imread("test/test.png") #rsize = img.resize((img.size[0]/10,img.size[1]/10))
#rsizeArray = np.asarray(rsize)


A = imread("test/eric_qr_neg.png") * 256
# You still need to larn what the line below does
#A = A[:, :, 0] + 1.*A[: ,:, 2] # Compose RGBA channels to give depth
numpy2stl(A, "test/eric_qr_out.stl", scale=0.05, mask_val=0.0, solid=True, min_thickness_percent=1.5, max_width=40., max_depth=40.)
#image2stl test/test.png -scale 0.04 -mask_val .0 -RGBA_weights 1. 0. 1. 0. -gaussian_filter .0
Beispiel #38
0
# from scipy.misc import lena, imresize
# from scipy.ndimage import gaussian_filter
# import scipy

#A = 256 * imread("NASA.png")
# https://github.com/thearn/stl_tools

# A = 256 * imread("macro5.png")
# print A.size
# print A.shape

# A = A[:, :, 0]+ A[:, :, 1]+ A[:, :, 2] #+ 1.0*A[:,:, 0] # Compose RGBA channels to give depth
#A =   A[:, :, 1] #+ 1.0*A[:,:, 0] # Compose RGBA channels to give depth
#print A
# A = gaussian_filter(A, 1)  # smoothing
#A = A[:, :, 0]
# A = -A # inverse the colors
#A = A+10

# print 'max '+ str(scipy.amax(A))
# print  'min '+ str(scipy.amin(A))
# print  'average '+ str(scipy.average(A))
# print  'median '+ str(scipy.median(A))

# numpy2stl(A, "leafHole2.stl", scale=2, mask_val=80, solid=True, max_width=150, max_depth=150,max_height=2)

from numpy import genfromtxt
my_data = genfromtxt('completeStucture1.000000_macroIteration_1.csv',
                     delimiter=',')
numpy2stl(my_data, "caketopper.stl", solid=True)
Beispiel #39
0
# Long Polling Setting
queue.set_attribute('ReceiveMessageWaitTimeSeconds', 20)

i = 0
while 1:
    # fetch 10 messages
    msgs = queue.get_messages(10)
    for msg in msgs:
        pythoned_json = json.loads(msg.get_body().encode('utf_8'),
                                   encoding='utf-8')
        for corp, resp in pythoned_json.items():
            # sys.stderr.write("recv%s: %s\n" % (str(i), resp['title'].encode('utf_8')))
            text = resp['title'].encode('utf_8')

            # text convert to stl
            # text2png(text, "images/test", fontsize=1) #save png
            shell = "sh convert.sh '" + text + "'"
            os.system(shell)
            A = imread("images/convert.png")  # read from rendered png
            A = A.mean(axis=2)  #grayscale projection
            #A = gaussian_filter(A.max() - A, 1.)
            filename = "images/" + corp + ".stl"
            numpy2stl(A, filename)

        i = i + 1
        # delete message
        queue.delete_message(msg)

    dt = datetime.today().strftime('%Y/%m/%d %H:%M:%S')
    sys.stderr.write("%s loop...\n" % (dt))