Ejemplo n.º 1
0
 def fromPCMString(self, buffer):
     from numarray import fromstring, Int16, Float32
     #print("buffer", len(buffer))
     b = fromstring(buffer, Int16)
     b = b.astype(Float32)
     b = ( b + 32768/2 ) / self.SCALE
     return b
Ejemplo n.º 2
0
 def detect(self, sample):
     """ Test for DTMF in a sample. Returns either a string with the
         DTMF digit, or the empty string if none is present. Accepts
         a string of length 640, representing 320 16 bit signed PCM
         samples (host endianness). This is _two_ samples at normal
         shtoom sampling rates.
     """
     import numarray
     from sets import Set
     a = numarray.fromstring(sample, numarray.Int16)
     if len(a) != 320:
         raise ValueError("samples length %d != 320 (40ms)"%len(a))
     peaks = self.getpeaks(a)
     matched = Set()
     for p in peaks:
         m = self.freqmatch.get(p)
         if m is None:
             if p-1 in self.freqmatch:
                 m = self.freqmatch.get(p-1)
             elif p+1 in self.freqmatch:
                 m = self.freqmatch.get(p+1)
         matched.add(m)
     # If we got a None, that means there was a significant component
     # that wasn't a DTMF frequency.
     if None in matched:
         return ''
     else:
         m = list(matched)
         m.sort()
         return self.dtmf.get(tuple(m), '')
Ejemplo n.º 3
0
 def detect(self, sample):
     """ Test for DTMF in a sample. Returns either a string with the
         DTMF digit, or the empty string if none is present. Accepts
         a string of length 640, representing 320 16 bit signed PCM
         samples (host endianness). This is _two_ samples at normal
         shtoom sampling rates.
     """
     import numarray
     from sets import Set
     a = numarray.fromstring(sample, numarray.Int16)
     if len(a) != 320:
         raise ValueError("samples length %d != 320 (40ms)"%len(a))
     peaks = self.getpeaks(a)
     matched = Set()
     for p in peaks:
         m = self.freqmatch.get(p)
         if m is None:
             if p-1 in self.freqmatch:
                 m = self.freqmatch.get(p-1)
             elif p+1 in self.freqmatch:
                 m = self.freqmatch.get(p+1)
         matched.add(m)
     # If we got a None, that means there was a significant component
     # that wasn't a DTMF frequency.
     if None in matched:
         return ''
     else:
         m = list(matched)
         m.sort()
         return self.dtmf.get(tuple(m), '')
Ejemplo n.º 4
0
 def fromPCMString(self, buffer):
     from numarray import fromstring, Int16, Float32
     #print "buffer", len(buffer)
     b = fromstring(buffer, Int16)
     b = b.astype(Float32)
     b = ( b + 32768/2 ) / self.SCALE
     return b
Ejemplo n.º 5
0
    def __xmlEndTagFound(self, in_name):
        if in_name == "adcdata":

            # ADC_Result
            if self.__filetype == ResultReader.ADCDATA_TYPE:
                if self.try_base64:
                    tmp_string=base64.standard_b64decode(self.adc_result_trailing_chars)
                    self.adc_result_trailing_chars=""
                    tmp=numarray.fromstring(tmp_string, numarray.Int16,(len(tmp_string)/2))
                    del tmp_string
                    self.result.x[self.adc_result_sample_counter:]=(numarray.arange(tmp.size()/2)+self.adc_result_sample_counter)/self.result.get_sampling_rate()
                    self.result.y[0][self.adc_result_sample_counter:]=tmp[::2]
                    self.result.y[1][self.adc_result_sample_counter:]=tmp[1::2]
                    self.adc_result_sample_counter+=tmp.size()/2
                else:
                    if self.adc_result_trailing_chars!="":
                        self.__xmlCharacterDataFound(" ")
            return

        elif in_name == "result":
            pass

        # Error_Result
        elif self.__filetype == ResultReader.ERROR_TYPE:
            pass

        # Temp_Result
        elif self.__filetype == ResultReader.TEMP_TYPE:
            pass

        # Config_Result
        elif self.__filetype == ResultReader.CONFIG_TYPE:
            pass
Ejemplo n.º 6
0
 def write(self, in_array):
     """ prepare at least 'items' samples.
     """
     fragment, self.state = audioop.ratecv(in_array,
                                           2,
                                           CHANNELS,
                                           self.in_hz,
                                           self.out_hz,
                                           self._state)
     ar = numarray.fromstring(fragment, type=numarray.Int16)
     ringbuffer.RingBuffer.write(self, ar)
Ejemplo n.º 7
0
    def __xmlEndTagFound(self, in_name):
        if in_name == "adcdata":

            # ADC_Result
            if self.__filetype == ResultReader.ADCDATA_TYPE:
                if self.try_base64:
                    tmp_string=base64.standard_b64decode(self.adc_result_trailing_chars)
                    self.adc_result_trailing_chars = ""
                    tmp=numarray.fromstring(tmp_string, numarray.Int16)
                    del tmp_string
                    
                    expected_samples=self.result.index[-1][1]-self.result.index[-1][0]+1
                    if len(tmp)/2 != expected_samples:
                        self.__gui.new_log_message("ResultReader Warning: size missmatch %d!=%d samples"%(len(tmp)/2, expected_samples), "DH")

                    size_used=min(expected_samples,len(tmp)/2)
                    self.result.x[self.adc_result_sample_counter:]=(numarray.arange(expected_samples)+self.adc_result_sample_counter)/self.result.get_sampling_rate()
                    self.result.y[0][self.adc_result_sample_counter:self.adc_result_sample_counter+size_used]=tmp[0:size_used*2:2]
                    self.result.y[1][self.adc_result_sample_counter:self.adc_result_sample_counter+size_used]=tmp[1:size_used*2:2]
                    del tmp
                    if size_used<expected_samples:
                        # zero padding...
                        self.result.y[0][self.adc_result_sample_counter+size_used:self.adc_result_sample_counter+samples_expected]=numarray.zeros((samples_expected-size_used,))
                        self.result.y[1][self.adc_result_sample_counter+size_used:self.adc_result_sample_counter+samples_expected]=numarray.zeros((samples_expected-size_used,))
                    self.adc_result_sample_counter+=expected_samples
                        
                else:
                    if self.adc_result_trailing_chars!="":
                        self.__xmlCharacterDataFound(" ")
            return

        elif in_name == "result":
            self.__gui.new_log_message("Result Reader: Successfully parsed and saved %s" % os.path.join(self.path, self.filename % self.files_read), "DH")

        # Error_Result
        elif self.__filetype == ResultReader.ERROR_TYPE:
            self.__gui.new_log_message("Result Reader: Error Result parsed! (%s)" % os.path.join(self.path, self.filename % self.files_read), "DH")

        # Temp_Result
        elif self.__filetype == ResultReader.TEMP_TYPE:
            self.__gui.new_log_message("ResultReader: Temperature Result parsed!", "DH")

        # Config_Result
        elif self.__filetype == ResultReader.CONFIG_TYPE:
            self.__gui.new_log_message("ResultReader: Config Result parsed!", "DH")

        self.result_queue.append(self.result)   
        self.result=None
Ejemplo n.º 8
0
	def calc_array(self):
		wave_object = self._get_wave()
		wave_object.setpos(0)
		self.frames = wave_object.readframes(self.number_of_frames)
		wave_object.close()
		w = wave_object.getsampwidth()
		if w == 2: #16 bits
			arr = numarray.fromstring(self.frames, numarray.Int16)

		#http://www.pythonapocrypha.com/Chapter32/Chapter32.shtml
		elif w == 1: #8 bits
			arr = numarray.array(self.frames, typecode = numarray.UnsignedInt8, savespace = 1)

		else:
			print "Not handled: samples are", w * 8, "bit"
			raise Error
		self.array = arr
Ejemplo n.º 9
0
 def sharpenImage(self, image, alpha):
     # FIXME: support RGB images
     rep = image.representations()[0]
     height = rep.pixelsHigh()
     width = rep.pixelsWide()  
     samplesPerPixel = rep.samplesPerPixel()
     bytesPerRow = rep.bytesPerRow()
     bitmapData = rep.bitmapData()
 
     # Convert the image to a numarray array
     size = (width, height)
     
     imgData = numarray.fromstring(datastring=bitmapData,
                                   type=numarray.UInt8,
                                   shape=size)
     
     # Convert to double and do a FFT2D
     G = numarray.fft.fft2d(imgData.astype(numarray.Float64))
     
     # Compute the power spectrum
     SG = (numarray.abs(G)**2.) / (width * height)
     
     # KD = 0.14711
     D1 = (numarray.abs(SG)**(alpha / 2.))
     
     # Find the normalization constant KD by requiring ||D1|| <= 1
     firstPass = numarray.add.reduce(D1**2)
     norm = math.sqrt(numarray.add.reduce(firstPass))
     KD = 1. / norm
     D1 *= KD
     
     # Divide the fft by its power spectrum and go back to real space.
     F1 = G / D1
     f2 = numarray.fft.inverse_fft2d(F1).real
     
     # Bring f2 into the [0, 255] range
     min = f2.min()
     if (min != 0):
         f2 -= min
     
     max = f2.max()
     if (max != 0):
         f2 /= max
         f2 *= 255.
     return(f2.astype(numarray.UInt8))
Ejemplo n.º 10
0
    def __call__(self,lon,lat,inverse=False):
        """
 Calling a Proj class instance with the arguments lon, lat will
 convert lon/lat (in degrees) to x/y native map projection 
 coordinates (in meters).  If optional keyword 'inverse' is
 True (default is False), the inverse transformation from x/y
 to lon/lat is performed.

 Example usage:
 >>> from proj import Proj
 >>> params = {}
 >>> params['proj'] = 'lcc' # lambert conformal conic
 >>> params['lat_1'] = 30.  # standard parallel 1
 >>> params['lat_2'] = 50.  # standard parallel 2
 >>> params['lon_0'] = -96  # central meridian
 >>> map = Proj(params)
 >>> x,y = map(-107,40)     # find x,y coords of lon=-107,lat=40
 >>> print x,y
 -92272.1004461 477477.890988


 lon,lat can be either scalar floats or numarray arrays.
        """
	npts = 1
        # if inputs are numarray arrays, get shape and total number of pts.
	try:
	    shapein = lon.shape
	    npts = reduce(lambda x, y: x*y, shapein)
	    lontypein = lon.typecode()
	    lattypein = lat.typecode()
	except:
            shapein = False
        # make sure inputs have same shape.
	if shapein and lat.shape != shapein:
            raise ValueError, 'lon, lat must be scalars or numarray arrays with the same shape'
        # make a rank 1 array with x/y (or lon/lat) pairs.
        xy = numarray.zeros(2*npts,'d')
        xy[::2] = numarray.ravel(lon)
        xy[1::2] = numarray.ravel(lat)
        # convert degrees to radians, meters to cm.
	if not inverse:
           xy = _dg2rad*xy
        else:
           xy = 10.*xy
        # write input data to binary file.
        xyout = array.array('d')
        xyout.fromlist(xy.tolist())
	# set up cmd string, scale factor for output.
	if inverse:
            cmd = self.projcmd+' -I'
	    scale = _rad2dg
        else:
            cmd = self.projcmd
	    scale = 0.1
	# use pipes for input and output if amount of 
	# data less than default buffer size (usually 8192).
	# otherwise use pipe for input, tempfile for output
	if 2*npts*8 > 8192:
            fd, fn=tempfile.mkstemp(); os.close(fd); stdout=open(fn,'rb')
            cmd = cmd+' > '+fn
            stdin=os.popen(cmd,'w')
	    xyout.tofile(stdin)
	    stdin.close()
            outxy = scale*numarray.fromstring(stdout.read(),'d')
	    stdout.close()
	    os.remove(fn)
        else:
            stdin,stdout=os.popen2(cmd,mode='b')
	    xyout.tofile(stdin)
	    stdin.close()
            outxy = scale*numarray.fromstring(stdout.read(),'d')
	    stdout.close()
        # return numarray arrays or scalars, depending on type of input.
	if shapein:
            outx = numarray.reshape(outxy[::2],shapein).astype(lontypein)
            outy = numarray.reshape(outxy[1::2],shapein).astype(lattypein)
        else:
            outx = outxy[0]; outy = outxy[1]
        return outx,outy
Ejemplo n.º 11
0
    def __call__(self, lon, lat, inverse=False):
        """
 Calling a Proj class instance with the arguments lon, lat will
 convert lon/lat (in degrees) to x/y native map projection 
 coordinates (in meters).  If optional keyword 'inverse' is
 True (default is False), the inverse transformation from x/y
 to lon/lat is performed.

 Example usage:
 >>> from proj import Proj
 >>> params = {}
 >>> params['proj'] = 'lcc' # lambert conformal conic
 >>> params['lat_1'] = 30.  # standard parallel 1
 >>> params['lat_2'] = 50.  # standard parallel 2
 >>> params['lon_0'] = -96  # central meridian
 >>> map = Proj(params)
 >>> x,y = map(-107,40)     # find x,y coords of lon=-107,lat=40
 >>> print x,y
 -92272.1004461 477477.890988


 lon,lat can be either scalar floats or numarray arrays.
        """
        npts = 1
        # if inputs are numarray arrays, get shape and total number of pts.
        try:
            shapein = lon.shape
            npts = reduce(lambda x, y: x * y, shapein)
            lontypein = lon.typecode()
            lattypein = lat.typecode()
        except:
            shapein = False
        # make sure inputs have same shape.
        if shapein and lat.shape != shapein:
            raise ValueError, 'lon, lat must be scalars or numarray arrays with the same shape'
        # make a rank 1 array with x/y (or lon/lat) pairs.
        xy = numarray.zeros(2 * npts, 'd')
        xy[::2] = numarray.ravel(lon)
        xy[1::2] = numarray.ravel(lat)
        # convert degrees to radians, meters to cm.
        if not inverse:
            xy = _dg2rad * xy
        else:
            xy = 10. * xy
        # write input data to binary file.
        xyout = array.array('d')
        xyout.fromlist(xy.tolist())
        # set up cmd string, scale factor for output.
        if inverse:
            cmd = self.projcmd + ' -I'
            scale = _rad2dg
        else:
            cmd = self.projcmd
            scale = 0.1

# use pipes for input and output if amount of
# data less than default buffer size (usually 8192).
# otherwise use pipe for input, tempfile for output
        if 2 * npts * 8 > 8192:
            fd, fn = tempfile.mkstemp()
            os.close(fd)
            stdout = open(fn, 'rb')
            cmd = cmd + ' > ' + fn
            stdin = os.popen(cmd, 'w')
            xyout.tofile(stdin)
            stdin.close()
            outxy = scale * numarray.fromstring(stdout.read(), 'd')
            stdout.close()
            os.remove(fn)
        else:
            stdin, stdout = os.popen2(cmd, mode='b')
            xyout.tofile(stdin)
            stdin.close()
            outxy = scale * numarray.fromstring(stdout.read(), 'd')
            stdout.close()
        # return numarray arrays or scalars, depending on type of input.
        if shapein:
            outx = numarray.reshape(outxy[::2], shapein).astype(lontypein)
            outy = numarray.reshape(outxy[1::2], shapein).astype(lattypein)
        else:
            outx = outxy[0]
            outy = outxy[1]
        return outx, outy
Ejemplo n.º 12
0
def main():
    if len(sys.argv) > 1:
        im_name = sys.argv[1]
    else:
        import tkFileDialog, Tkinter
        im_name = tkFileDialog.askopenfilename(defaultextension=".png",
            filetypes = (
                (_("Depth images"), ".gif .png .jpg"),
                (_("All files"), "*")))
        if not im_name: raise SystemExit
        Tkinter._default_root.destroy()
        Tkinter._default_root = None
    im = Image.open(im_name)
    size = im.size
    im = im.convert("L") #grayscale
    w, h = im.size

    nim = numarray.fromstring(im.tostring(), 'UInt8', (h, w)).astype('Float32')
    options = ui(im, nim, im_name)

    step = options['pixelstep']
    depth = options['depth']

    if options['normalize']:
        a = nim.min()
        b = nim.max()
        if a != b:
            nim = (nim - a) / (b-a)
    else:
        nim = nim / 255.0

    maker = tool_makers[options['tool_type']]
    tool_diameter = options['tool_diameter']
    pixel_size = options['pixel_size']
    tool = make_tool_shape(maker, tool_diameter, pixel_size)

    if options['expand']:
        if options['expand'] == 1: pixel = 1
        else: pixel = 0
        tw, th = tool.shape
        w1 = w + 2*tw
        h1 = h + 2*th
        nim1 = numarray.zeros((w1, h1), 'Float32') + pixel
        nim1[tw:tw+w, th:th+w] = nim
        nim = nim1
        w, h = w1, h1
    nim = nim * depth

    if options['invert']:
        nim = -nim
    else:
        nim = nim - depth

    rows = options['pattern'] != 1
    columns = options['pattern'] != 0
    columns_first = options['pattern'] == 3
    spindle_speed = options['spindle_speed']
    if rows: convert_rows = convert_makers[options['converter']]()
    else: convert_rows = None
    if columns: convert_cols = convert_makers[options['converter']]()
    else: convert_cols = None

    if options['bounded'] and rows and columns:
        slope = tan(options['contact_angle'] * pi / 180)
        if columns_first:
            convert_rows = Reduce_Scan_Lace(convert_rows, slope, step+1)
        else:
            convert_cols = Reduce_Scan_Lace(convert_cols, slope, step+1)
        if options['bounded'] > 1:
            if columns_first:
                convert_cols = Reduce_Scan_Lace(convert_cols, slope, step+1)
            else:
                convert_rows = Reduce_Scan_Lace(convert_rows, slope, step+1)

    units = unitcodes[options['units']]
    convert(nim, units, tool, pixel_size, step,
        options['safety_height'], options['tolerance'], options['feed_rate'],
        convert_rows, convert_cols, columns_first, ArcEntryCut(options['plunge_feed_rate'], .125),
        spindle_speed, options['roughing_offset'], options['roughing_depth'], options['feed_rate'])
Ejemplo n.º 13
0
def main():
    if len(sys.argv) > 1:
        im_name = sys.argv[1]
    else:
        import tkFileDialog, Tkinter
        im_name = tkFileDialog.askopenfilename(defaultextension=".png",
                                               filetypes=((_("Depth images"),
                                                           ".gif .png .jpg"),
                                                          (_("All files"),
                                                           "*")))
        if not im_name: raise SystemExit
        Tkinter._default_root.destroy()
        Tkinter._default_root = None
    im = Image.open(im_name)
    size = im.size
    im = im.convert("L")  #grayscale
    w, h = im.size

    nim = numarray.fromstring(im.tostring(), 'UInt8', (h, w)).astype('Float32')
    options = ui(im, nim, im_name)

    step = options['pixelstep']
    depth = options['depth']

    if options['normalize']:
        a = nim.min()
        b = nim.max()
        if a != b:
            nim = (nim - a) / (b - a)
    else:
        nim = nim / 255.0

    maker = tool_makers[options['tool_type']]
    tool_diameter = options['tool_diameter']
    pixel_size = options['pixel_size']
    tool = make_tool_shape(maker, tool_diameter, pixel_size)

    if options['expand']:
        if options['expand'] == 1: pixel = 1
        else: pixel = 0
        tw, th = tool.shape
        w1 = w + 2 * tw
        h1 = h + 2 * th
        nim1 = numarray.zeros((w1, h1), 'Float32') + pixel
        nim1[tw:tw + w, th:th + w] = nim
        nim = nim1
        w, h = w1, h1
    nim = nim * depth

    if options['invert']:
        nim = -nim
    else:
        nim = nim - depth

    rows = options['pattern'] != 1
    columns = options['pattern'] != 0
    columns_first = options['pattern'] == 3
    spindle_speed = options['spindle_speed']
    if rows: convert_rows = convert_makers[options['converter']]()
    else: convert_rows = None
    if columns: convert_cols = convert_makers[options['converter']]()
    else: convert_cols = None

    if options['bounded'] and rows and columns:
        slope = tan(options['contact_angle'] * pi / 180)
        if columns_first:
            convert_rows = Reduce_Scan_Lace(convert_rows, slope, step + 1)
        else:
            convert_cols = Reduce_Scan_Lace(convert_cols, slope, step + 1)
        if options['bounded'] > 1:
            if columns_first:
                convert_cols = Reduce_Scan_Lace(convert_cols, slope, step + 1)
            else:
                convert_rows = Reduce_Scan_Lace(convert_rows, slope, step + 1)

    units = unitcodes[options['units']]
    convert(nim, units, tool, pixel_size, step, options['safety_height'],
            options['tolerance'], options['feed_rate'], convert_rows,
            convert_cols, columns_first,
            ArcEntryCut(options['plunge_feed_rate'],
                        .125), spindle_speed, options['roughing_offset'],
            options['roughing_depth'], options['feed_rate'])