示例#1
0
def saveImage(data, nodeAllocations, opts):
  global WIDTH
  global HEIGHT
  global PAGESIZE

  # Collapse "step" rows that are completely empty.
  step = 4
  collapser = numpy.zeros(WIDTH*HEIGHT, numpy.uint32)
  for begin, end in ((WIDTH*y, WIDTH*y + WIDTH*step) 
                     for y in xrange(0, HEIGHT, step)):
    if any(data[begin:end]):
      collapser[begin:end] = 1
  data = data.compress(collapser)
  
  # Create the output false colors picture. Rescale the values in the
  # data array so that they are normalised to 245 and convert the array
  # to 8 bit so that it can be easily used with the paletted mode.
  # Notice that we leave the last ten colors (245 - 255) to highlight
  # fragmented memory allocations coming from a unique stacktrace node.
  # Determine the 10 most fragmented allocations coming from the same symbol
  # and highlight the pages they touch.
  # Reshape the array to be bidimensional rather than linear.
  data *= 245
  data /= PAGESIZE
  
  # Calculate an highlight mask to hightlight top MEM_LIVE allocations.
  if topTen[0]:
    highlightNode, highlighNodeName = topTen[4][0]
    for (pos, size) in nodeAllocations[highlightNode]:
      paintAllocation(data, pos, size, 246)
  
  WIDTH = int(sqrt(len(data)))
  data = numpy.reshape(data, (len(data)/WIDTH, WIDTH))
  HEIGHT, WIDTH = data.shape
  
  pilImage = fromarray(numpy.array(data, dtype=numpy.uint8), 'P')
  lut = [0,0,0]
  for x in (int(i / 245. * 255.) for i in range(245)):
    lut.extend([x*0.8, x*0.8 , x*0.8])
  # Extra colors are all purple.
  for x in range(10):
    lut.extend([186., 7., 17.])
  
  pilImage.putpalette(lut)
  
  d = ImageDraw(pilImage)
  for c in xrange(256):
    w, h = WIDTH*0.8 / 256, HEIGHT*0.01
    x, y = c * w+WIDTH*0.1, HEIGHT*0.9 - h
    d.rectangle((x, y, x+w, y+h), fill=c)
  pilImage = pilImage.resize((WIDTH*2, HEIGHT*2))
  pilImage.save(opts.output)
示例#2
0
def saveImage(data, nodeAllocations, opts):
    global WIDTH
    global HEIGHT
    global PAGESIZE

    # Collapse "step" rows that are completely empty.
    step = 4
    collapser = numpy.zeros(WIDTH * HEIGHT, numpy.uint32)
    for begin, end in ((WIDTH * y, WIDTH * y + WIDTH * step)
                       for y in xrange(0, HEIGHT, step)):
        if any(data[begin:end]):
            collapser[begin:end] = 1
    data = data.compress(collapser)

    # Create the output false colors picture. Rescale the values in the
    # data array so that they are normalised to 245 and convert the array
    # to 8 bit so that it can be easily used with the paletted mode.
    # Notice that we leave the last ten colors (245 - 255) to highlight
    # fragmented memory allocations coming from a unique stacktrace node.
    # Determine the 10 most fragmented allocations coming from the same symbol
    # and highlight the pages they touch.
    # Reshape the array to be bidimensional rather than linear.
    data *= 245
    data /= PAGESIZE

    # Calculate an highlight mask to hightlight top MEM_LIVE allocations.
    if topTen[0]:
        highlightNode, highlighNodeName = topTen[4][0]
        for (pos, size) in nodeAllocations[highlightNode]:
            paintAllocation(data, pos, size, 246)

    WIDTH = int(sqrt(len(data)))
    data = numpy.reshape(data, (len(data) / WIDTH, WIDTH))
    HEIGHT, WIDTH = data.shape

    pilImage = fromarray(numpy.array(data, dtype=numpy.uint8), 'P')
    lut = [0, 0, 0]
    for x in (int(i / 245. * 255.) for i in range(245)):
        lut.extend([x * 0.8, x * 0.8, x * 0.8])
    # Extra colors are all purple.
    for x in range(10):
        lut.extend([186., 7., 17.])

    pilImage.putpalette(lut)

    d = ImageDraw(pilImage)
    for c in xrange(256):
        w, h = WIDTH * 0.8 / 256, HEIGHT * 0.01
        x, y = c * w + WIDTH * 0.1, HEIGHT * 0.9 - h
        d.rectangle((x, y, x + w, y + h), fill=c)
    pilImage = pilImage.resize((WIDTH * 2, HEIGHT * 2))
    pilImage.save(opts.output)
示例#3
0
def save_to_image(filename, img):
    """
    Save to ".jpg", the image
    """
    # Append ".jpg" to filename if not present
    filename = append_type(filename, '.jpg')

    # If img is numpy array, convert it to PIL image
    if isinstance(img, ndarray):
        img = fromarray(uint8(img))
    # Convert the image as necessary
    if not img.mode == 'L':
        img = img.convert('L')
    img.save(filename, 'jpeg')
示例#4
0
def make(**kw):
    step, noise, decay = [float(kw[k]) for k in ['--step','--noise','--decay']]
    X, Y = [int(kw[k]) for k in ['--width', '--height']]
    H = X/2

    gray = ones((Y,X),dtype=float)
    for x in range(H):
        dI = step * exp(-decay*float(H-x))
        gray[:,0+x+0] += dI
        gray[:,X-x-1] -= dI

    scatter = ((random.random((Y,X))*2)-1) * noise
    image = (gray+scatter)*127

    saved = fromarray(image)
    name = 'egray/egray.s.%f.n.%f.d.%f.gif' % (step, noise, decay)
    saved.save(name)
    toimage(saved)
示例#5
0
def make(**kw):
    step  = kw.get( 'step', 3e-2)
    scale = kw.get('scale', 3e-1)
    shape = (Y, X) = [kw.get(edge, 512) for edge in ['Y', 'X']]
    X0, X1, X2, X3 = 0, X/2-1, X/2, X-1

    gray = ones(shape, dtype=float)
    gray[:,X0:X1] -= step
    gray[:,X2:X3] += step

    noise = ((random.random((Y,X))*2)-1) * scale

    image = (gray+noise)*127
    print gray.max(), noise.max(), image.max()
    print gray.min(), noise.min(), image.min()

    saved = fromarray(image)
    name = 'gray/gray.step.%f.scale.%f.gif' % (step, scale)
    print name
    saved.save(name)
示例#6
0
文件: Diffract.py 项目: jlettvin/RPN
 def save(self, kernel, R, dx=0, dy=0, **kw):
     rescaled = (255.0 * kernel).astype('uint8')
     name = "kernels/Airy/kernel.Airy.R%d.dx%1.2f.dy%1.2f" % (R, dx, dy)
     image = fromarray(rescaled)
     image.save(name+".png")
     scipy.save(name+".npy", kernel)
示例#7
0
    pos3 = line.rfind(' ')
    pos4 = line.find(')')
    extent.append(float(line[4:pos1]))
    extent.append(float(line[pos1+1:pos2]))
    extent.append(float(line[pos2+1:pos3]))
    extent.append(float(line[pos3+1:pos4]))
f2.close()
"""
if cellsize == "":
    w = extent[2] - extent[0]
    h = extent[1] - extent[3]
    image_w = 600
    image_h = h * image_w / w
    cellsize = max(w / image_w, h / image_h)
    std_x = std(x)
    std_y = std(y)
    Q_x = quantile(x)
    Q_y = quantile(y)
    IQR_x = Q_x[2] - Q_x[0]
    IQR_y = Q_y[2] - Q_y[0]
    h_x = 0.9 * min(std_x, IQR_x / 1.34) * pow(n, -0.2)
    h_y = 0.9 * min(std_y, IQR_y / 1.34) * pow(n, -0.2)
    bandwidth = max(h_x, h_y) * 2
else:
    cellsize = float(cellsize)
    bandwidth = float(bandwidth)

itv_pts_ids = range(n)
arr, rows, cols, gmin, gmax = call_kde(n, x, y, itv_pts_ids, extent, bandwidth, cellsize, kernel, gradient, opaque)
fromarray(arr).save("test1.png")
def shaded_relief(in_file, raster_band, color_file, out_file_name,
    azimuth=315, angle_altitude=45):
    '''
    The main function. Reads the input image block by block to improve the performance, and calculates the shaded relief image
    '''

    if exists(in_file) is False:
            raise Exception('[Errno 2] No such file or directory: \'' + in_file + '\'')    
    
    dataset = gdal.Open(in_file, GA_ReadOnly )
    if dataset == None:
        raise Exception("Unable to read the data file")
    
    band = dataset.GetRasterBand(raster_band)

    block_sizes = band.GetBlockSize()
    x_block_size = block_sizes[0]
    y_block_size = block_sizes[1]

    #If the block y size is 1, as in a GeoTIFF image, the gradient can't be calculated, 
    #so more than one block is used. In this case, using8 lines gives a similar 
    #result as taking the whole array.
    if y_block_size < 8:
        y_block_size = 8

    xsize = band.XSize
    ysize = band.YSize

    max_value = band.GetMaximum()
    min_value = band.GetMinimum()

    #Reading the color table
    color_table = readColorTable(color_file)
    #Adding an extra value to avoid problems with the last & first entry
    if sorted(color_table.keys())[0] > min_value:
        color_table[min_value - 1] = color_table[sorted(color_table.keys())[0]]

    if sorted(color_table.keys())[-1] < max_value:
        color_table[max_value + 1] = color_table[sorted(color_table.keys())[-1]]
    #Preparing the color table
    classification_values = color_table.keys()
    classification_values.sort()

    max_value = band.GetMaximum()
    min_value = band.GetMinimum()

    if max_value == None or min_value == None:
        stats = band.GetStatistics(0, 1)
        max_value = stats[1]
        min_value = stats[0]

    out_array = zeros((3, ysize, xsize), 'uint8')

    #The iteration over the blocks starts here
    for i in range(0, ysize, y_block_size):
        if i + y_block_size < ysize:
            rows = y_block_size
        else:
            rows = ysize - i
        
        for j in range(0, xsize, x_block_size):
            if j + x_block_size < xsize:
                cols = x_block_size
            else:
                cols = xsize - j

            dem_array = band.ReadAsArray(j, i, cols, rows)
            
            hs_array = hillshade(dem_array, azimuth, 
                angle_altitude)

            rgb_array = values2rgba(dem_array, color_table, 
                classification_values, max_value, min_value)

            hsv_array = rgb_to_hsv(rgb_array[:, :, 0], 
                rgb_array[:, :, 1], rgb_array[:, :, 2]) 

            hsv_adjusted = asarray( [hsv_array[0], 
                hsv_array[1], hs_array] )          

            shaded_array = hsv_to_rgb( hsv_adjusted )
            
            out_array[:,i:i+rows,j:j+cols] = shaded_array
    
    #Saving the image using the PIL library
    im = fromarray(transpose(out_array, (1,2,0)), mode='RGB')
    im.save(out_file_name)
示例#9
0
文件: test_kde.py 项目: lixun910/CAST
    pos4 = line.find(')')
    extent.append(float(line[4:pos1]))
    extent.append(float(line[pos1+1:pos2]))
    extent.append(float(line[pos2+1:pos3]))
    extent.append(float(line[pos3+1:pos4]))
f2.close()
"""
if cellsize == "":
    w = extent[2] - extent[0]
    h = extent[1] - extent[3]
    image_w = 600
    image_h = h * image_w / w
    cellsize = max(w / image_w, h / image_h)
    std_x = std(x)
    std_y = std(y)
    Q_x = quantile(x)
    Q_y = quantile(y)
    IQR_x = Q_x[2] - Q_x[0]
    IQR_y = Q_y[2] - Q_y[0]
    h_x = 0.9 * min(std_x, IQR_x / 1.34) * pow(n, -0.2)
    h_y = 0.9 * min(std_y, IQR_y / 1.34) * pow(n, -0.2)
    bandwidth = max(h_x, h_y) * 2
else:
    cellsize = float(cellsize)
    bandwidth = float(bandwidth)

itv_pts_ids = range(n)
arr, rows, cols, gmin, gmax = call_kde(n, x, y, itv_pts_ids, extent, bandwidth,
                                       cellsize, kernel, gradient, opaque)
fromarray(arr).save("test1.png")
def RingTracking2D(data, n_centers, threshold = 0.5, draw_dots = False, draw_mean = False, return_dots = False, outfolder = None, static = True):
    # tracks a ring pattern in 2D. Locates particles using the Hough transfrom algorithm (center_find)
    # data is a stack of images to track particles in, stored as xyt hyperstack
    # n_centers is the number of ring patterns to track
    # theshold is the treshold used in center_find
    # draw_dots = True draws a label and a spot on each image from data where each center was found
    # draw_mean = True Uses the mean coordinate from each track as the position of the spot to be drawn
    # return_dots = True, retrun the images with the spots drawn on them
    # outfolder = location to save images with spots/labels
    # static = True uses first location of a particle to link tracks. Use False if the particle is moving
    #
    #
    # returns an array containing the coordinates of the ring centers at each frame
    # Also returns the images with a tracks labeled if return_dots = True

    #find centers
    from holopy.core.process.centerfinder import center_find
    coords = []
    print('finding particles')
    #loop through each frame
    for i in np.arange(0,data.shape[-1]):
        if i%50 == 0:
            print(i)
        coord = center_find(data[:,:,i], centers = n_centers, threshold = threshold)
        if n_centers ==1:
            coord = np.reshape(coord, (1,2))
        
        coords.append(coord)
    coords = np.array(coords)


    #link up particles between frames
    print('linking tracks')

    def get_distance(coords1, coords2):
        return np.sqrt( (coords1[0]-coords2[0])**2 + (coords1[1]-coords2[1])**2  )
        
    tracks = np.empty(coords.shape)

    #loop through each particle
    for particle in np.arange(0,coords.shape[1]):
        #set initial point
        tracks[0,particle,:] = coords[0,particle,:]
        known_coord = tracks[0,particle,:] #location of the particle for comparison
        
        #look in subsequent frames to find the closest particle to known_coord
        for frame in np.arange(1,coords.shape[0]):
            min_distance = 10000
            if not static:
                known_coord = tracks[frame-1,particle,:]
            #compare to all center locations
            for i in np.arange(0,coords.shape[1]):
                distance = get_distance(known_coord, coords[frame,i,:])
                if distance < min_distance:
                    min_distance = distance
                    closest_particle_index = i
            
            #set track coordinate     
            tracks[frame,particle,:] = coords[frame, closest_particle_index, :]

    if not draw_dots:
        return tracks

    #Draw a spot at each point that was found
    else:  
        print('drawing tracks')
        from Image import fromarray
        from ImageDraw import Draw

        #used for scaling images
        im_max = data.max()
        im_min = data.min()
        
        if return_dots:
            spot_images = []
        
        if draw_mean:
            tracksmean = np.mean(tracks,0)
        
        #loop through each frame
        for i in np.arange(0,data.shape[-1]):
            #convert to an RGB image
            spot_image = fromarray( 255*(data[:,:,i]-im_min)/(im_max-im_min) )
            spot_image = spot_image.convert('RGB')
            
            #draw spots and labels
            draw = Draw(spot_image)
            for j in np.arange(0,tracks.shape[1]):
                if draw_mean:
                    spot_coord = [np.round(tracksmean[j,1]), np.round(tracksmean[j,0])]                   
                else:
                    spot_coord = [np.round(tracks[i,j,1]), np.round(tracks[i,j,0])]        
                draw.point( (spot_coord[0],spot_coord[1]), (255,0,0))
                draw.text( (spot_coord[0]-10,spot_coord[1]-10), str(j),(255,0,0))
                       
            if return_dots:
                spot_images.append(spot_image)
            
            if outfolder != None:    
                spot_image.save(outfolder + 'spot_image' + str(i).zfill(5) +'.png')
                
        if return_dots:
            return [tracks, spot_images]
        else:
            return tracks
示例#11
0
def frompil(src):
    return pil_to_ipl(fromarray(src))
示例#12
0
def shaded_relief(in_file,
                  raster_band,
                  color_file,
                  out_file_name,
                  azimuth=315,
                  angle_altitude=45):
    '''
    The main function. Reads the input image block by block to improve the performance, and calculates the shaded relief image
    '''

    if exists(in_file) is False:
        raise Exception('[Errno 2] No such file or directory: \'' + in_file +
                        '\'')

    dataset = gdal.Open(in_file, GA_ReadOnly)
    if dataset == None:
        raise Exception("Unable to read the data file")

    band = dataset.GetRasterBand(raster_band)

    block_sizes = band.GetBlockSize()
    x_block_size = block_sizes[0]
    y_block_size = block_sizes[1]

    #If the block y size is 1, as in a GeoTIFF image, the gradient can't be calculated,
    #so more than one block is used. In this case, using8 lines gives a similar
    #result as taking the whole array.
    if y_block_size < 8:
        y_block_size = 8

    xsize = band.XSize
    ysize = band.YSize

    max_value = band.GetMaximum()
    min_value = band.GetMinimum()

    #Reading the color table
    color_table = readColorTable(color_file)
    #Adding an extra value to avoid problems with the last & first entry
    if sorted(color_table.keys())[0] > min_value:
        color_table[min_value - 1] = color_table[sorted(color_table.keys())[0]]

    if sorted(color_table.keys())[-1] < max_value:
        color_table[max_value + 1] = color_table[sorted(
            color_table.keys())[-1]]
    #Preparing the color table
    classification_values = color_table.keys()
    classification_values.sort()

    max_value = band.GetMaximum()
    min_value = band.GetMinimum()

    if max_value == None or min_value == None:
        stats = band.GetStatistics(0, 1)
        max_value = stats[1]
        min_value = stats[0]

    out_array = zeros((3, ysize, xsize), 'uint8')

    #The iteration over the blocks starts here
    for i in range(0, ysize, y_block_size):
        if i + y_block_size < ysize:
            rows = y_block_size
        else:
            rows = ysize - i

        for j in range(0, xsize, x_block_size):
            if j + x_block_size < xsize:
                cols = x_block_size
            else:
                cols = xsize - j

            dem_array = band.ReadAsArray(j, i, cols, rows)

            hs_array = hillshade(dem_array, azimuth, angle_altitude)

            rgb_array = values2rgba(dem_array, color_table,
                                    classification_values, max_value,
                                    min_value)

            hsv_array = rgb_to_hsv(rgb_array[:, :, 0], rgb_array[:, :, 1],
                                   rgb_array[:, :, 2])

            hsv_adjusted = asarray([hsv_array[0], hsv_array[1], hs_array])

            shaded_array = hsv_to_rgb(hsv_adjusted)

            out_array[:, i:i + rows, j:j + cols] = shaded_array

    #Saving the image using the PIL library
    im = fromarray(transpose(out_array, (1, 2, 0)), mode='RGB')
    im.save(out_file_name)