def write( self ):
        slope       = ( 1.0 * self.height ) / self.width
        pixels      = numpy.zeros( ( self.height, self.width ), dtype=int )

        #
        # Something similar to http://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm
        # but special cased, since I know the lines are mirrored thrice.
        #
        actualY = 0
        for leftX in range( 0, ( self.width / 2 ) + 1 ):
            # Precalculating.  Math!
            frac        = actualY - int( actualY ) 
            topColor    = self.getColor( 1 - frac )
            bottomColor = self.getColor( frac )
            topY        = int( actualY )
            bottomY     = self.height - topY - 1
            rightX      = self.width - leftX - 1

            # Actual Line (top-left)
            pixels[ topY,       leftX ]   = topColor
            pixels[ topY + 1,   leftX ]   = bottomColor

            # Horizontal Flip (top-right)
            pixels[ topY,       rightX ]  = topColor
            pixels[ topY + 1,   rightX ]  = bottomColor

            # Vertical Flip (bottom-left)
            pixels[ bottomY,     leftX ]  = topColor
            pixels[ bottomY - 1, leftX ]  = bottomColor

            # 180-degree Rotation
            pixels[ bottomY,     rightX ] = topColor
            pixels[ bottomY - 1, rightX ] = bottomColor
            
            # Increment `actualY`
            actualY += slope
            
            # Worry about the border (avoids another loop)
            if self.border:
                pixels[ 0,                leftX  ] = Placeholder.BACKGROUND
                pixels[ self.height - 1,  leftX  ] = Placeholder.BACKGROUND
                pixels[ 0,                rightX ] = Placeholder.BACKGROUND
                pixels[ self.height - 1,  rightX ] = Placeholder.BACKGROUND
                if leftX > 1:
                    pixels[ 1,                leftX  ] = Placeholder.FOREGROUND
                    pixels[ self.height - 2,  leftX  ] = Placeholder.FOREGROUND
                    pixels[ 1,                rightX ] = Placeholder.FOREGROUND
                    pixels[ self.height - 2,  rightX ] = Placeholder.FOREGROUND
                if leftX == 1:
                    for y in range( 1, self.height - 1 ):
                        pixels[ y,  leftX  ] = Placeholder.FOREGROUND
                        pixels[ y,  rightX ] = Placeholder.FOREGROUND

        if self.metadata: 
            self.addMetadata( pixels )

        with open( self.out, 'wb' ) as f:
            w = Writer( self.width, self.height, background=self.colors[0], palette=self.colors, bitdepth=8 )
            w.write( f, pixels )
def draw_map(width, height, map, filename, pixel_function):
    """
    Generic function to draw maps with PyPNG
    """
    writer = Writer(width, height)
    pixels = [reduce(lambda x, y: x + y, [pixel_function(elev) for elev in row]) for row in map]
    with open(filename, 'w') as f:
        writer.write(f, pixels)
 def generate_captcha_response(self, request, uri, headers):
     ''' Generate a PNG image and return it as captcha mock
     '''
     f = BytesIO()
     w = Writer(206, 40)
     pngdata = [[random.randint(0,255) for i in range(206*w.planes)] for i in range(40)]
     w.write(f, pngdata)
     headers['Content-Type'] = 'image/png'
     return (200, headers, f.getvalue())
    def _save(self, filename):
        if type(filename) is not str:
            raise ValueError("file name must be a string")

        with open(filename, 'wb') as f:
            rows, cols = len(self.image_data), len(self.image_data[0])
            writer = Writer(cols, rows)

            pixels = _unbox(self.image_data)
            writer.write(f, pixels)

        print(filename, "saved.")
def draw_color_map_with_shadow(width, height, map, filename):

    ELEV_MIN = -1.0
    ELEV_MOUNTAIN = 1.0

    SHADOW_RADIUS = 4

    COAST_COLOR = (203, 237, 128)
    HILL_COLOR = (65, 69, 28)
    MOUNTAIN_COLOR = (226, 227, 218)
    SHALLOW_SEA_COLOR = (128, 237, 235)
    DEEP_SEA_COLOR = (2, 69, 92)

    def shadow_color(color, x, y):
        alt = map[y][x]
        delta = 0
        for dist in range(SHADOW_RADIUS):
            # To avoid picking unexisting cells
            if x > dist and y > dist:
                other = map[y-1-dist][x-1-dist]
                diff = other-alt
                if other > ELEV_SEA and other>alt:
                    delta += diff/(1.0+dist)
        delta = min(0.2, delta)
        return gradient(delta, 0, 0.2, color, (0, 0, 0))


    def elev_to_pixel(elev):
        if elev > ELEV_HILL:
            return gradient(elev, ELEV_HILL, ELEV_MOUNTAIN, HILL_COLOR, MOUNTAIN_COLOR)
        elif elev > ELEV_SEA:
            return gradient(elev, ELEV_SEA, ELEV_HILL, COAST_COLOR, HILL_COLOR)
        else:
            return gradient(elev, ELEV_MIN, ELEV_SEA, DEEP_SEA_COLOR, SHALLOW_SEA_COLOR)

    writer = Writer(width, height)

    colors = [[elev_to_pixel(elev) for elev in row] for row in map]
    for y in range(height):
        for x in range(width):
            colors[y][x] = shadow_color(colors[y][x], x, y)
    pixels = [reduce(lambda x, y: x+y, row) for row in colors]
    with open(filename, 'w') as f:
        writer.write(f, pixels)
示例#6
0
def getSrcFileName(idx):
	return ('%s %04d%s' % (SOURCE_NAME, idx, '.png'))

if __name__ == '__main__':
	print("\nPNGMerger by seCOnDatkE 2014.")
	print("This script is initially written for MarKsCube Prototype.")
	print("Any problem and suggestion goes to [email protected].")
	print('')

	print("\tReading %s..." % getSrcFileName(1)),
	imageMeta = Reader(getSrcFileName(1)).read()
	print('ok'); print ("\tGetting file size..."),
	size = (imageMeta[0], imageMeta[1])
	print('ok, %s: width %d, height %d.' % (getSrcFileName(1), size[0], size[1])); print('\tCreating png writer...'),
	destWriter = Writer(size[0] * DEST_ROWS, size[1] * DEST_COLS, alpha='RGBA', bitdepth=8)
	print('ok, width %d, height %d.' % (size[0] * DEST_ROWS, size[1] * DEST_COLS))

	src_images = []
	print("\n\t\tReading empty image data..."),
	src_images.append([data for data in Reader(EMPTY_FILE).asDirect()[2]])
	print('ok')
	for num in range(1, IMAGE_NUM+1):
		print('\t\tReading image data "%s"...' % getSrcFileName(num)),
		src_images.append([data for data in Reader(getSrcFileName(num)).asDirect()[2]])
		print('ok')

	ret_image = []
	getImage = (lambda x : src_images[(lambda : 0 if x > IMAGE_NUM else x)()])
	print('')
	for row in range(1, DEST_COLS * DEST_ROWS, DEST_ROWS):
示例#7
0
文件: crt-mt.py 项目: svofski/CRT
      p = 1.0
    return int(p * 255)

def clamp_scale3(p):
    return [clamp_scale(x) for x in p]

inputfile = 'testcard.png'

outputfile_coded = (lambda x: x[0] + '-encoded.' + x[1])(inputfile.split('.', 1))
outputfile_decoded = (lambda x: x[0] + '-decoded.' + x[1])(inputfile.split('.', 1))

width, height, pixels, meta = Reader(inputfile).asRGB8()

coded = open(outputfile_coded, 'wb')
decodedf = open(outputfile_decoded, 'wb')
coded_writer = Writer(width, height, greyscale=True)
decoded_writer = Writer(width, height)


# how many counts of Fsc
width_ratio = width / (Fsc / Fline) # ~ 2.69
delta_wt = math.pi / width_ratio

# we only get 312 lines
height_ratio = height / 312.0

print 'Files:\n  input picture: %s (%dx%d)\n  encoded picture: %s\n  decoded picture: %s' %\
   (inputfile, width, height, outputfile_coded, outputfile_decoded)
print 'Modem parameters:\n  Fsc=%10.4fHz\n  Line frequency=%5fHz\n  Width to Fsc ratio=%3.3f' % (Fsc, Fline, width_ratio)

def main():

    comm = MPI.COMM_WORLD
    id= comm.Get_rank()
    wsize= comm.Get_size()    
    tstart = MPI.Wtime()
    fsky = open("skymap.png","r")
    reader = Reader(fsky)
    skypixelwidth, skypixelheight, skypixels, metadata=reader.read_flat()
    pixelwidth = int(argv[1])
    pixelheight = int(argv[2])
    tskymapstart = MPI.Wtime()
    telepixels = np.zeros((pixelwidth*pixelheight*3),dtype=np.uint8)
    colorpixels = np.zeros((pixelwidth*pixelheight),dtype=np.uint8)
    skystartall = np.zeros((pixelwidth*pixelheight),dtype=np.uint32)
    telestartall = np.zeros((pixelwidth*pixelheight),dtype=np.uint32)
    colorall = np.zeros((pixelwidth*pixelheight),dtype=np.uint8)
    totnstepsall=np.zeros((wsize),dtype=np.uint32)
    tskymapend = MPI.Wtime()
    tskymap = tskymapend-tskymapstart

    tmin = 1.e6
    tpercparmin=1.e6
    hinit=1.e-1
    #h=1.e-4
    Router = 1000.
    Rplane = 700.
    Rs = 2.
    every = 1
    deltalamb = 1.e-1
    imagewidth = 50;
    imageheight = 50;
    tiny = 1.e-30
    epsilon=1.e-8
    eccentricity = 0.2
    Rfac = 1.+1.e-10
    heps = 1.e-14
    semilatusr = 10.0  

    
    tstartpp=MPI.Wtime() #percent parallelized
    numperprocess = pixelheight*pixelwidth/wsize
    skystart=np.zeros((numperprocess),dtype=np.int32)
    telestart=np.zeros((numperprocess),dtype=np.int32)
    color = np.zeros((numperprocess),dtype=np.int8)
    totnsteps=np.zeros((numperprocess),dtype=np.int32)
    trk4all=np.zeros((numperprocess),dtype=np.float)
    ttelestop = MPI.Wtime()
    ttele = ttelestop-tstartpp
    trk4=float("inf")
    for index in range(numperprocess):
        ypix = int((id*numperprocess+index)/pixelwidth)
        xpix = (id*numperprocess+index)%pixelwidth
        tstartrk4=MPI.Wtime()
        totnsteps[index],skystart[index],telestart[index],color[index]=integrateNullGeodesic(xpix, ypix, pixelheight,pixelwidth, skypixelheight,skypixelwidth,imagewidth,imageheight,Rs,Router,Rplane,eccentricity, semilatusr, epsilon, tiny, hinit,Rfac,heps)
        tendrk4=MPI.Wtime()
        trk4=min(trk4,(tendrk4-tstartrk4)/float(totnsteps[index]))
    totnstepsmax=max(totnsteps)
    tstoppp = MPI.Wtime()
    tpercpar=tstoppp-tstartpp

    comm.Barrier()
    if id==0:
        totnstepsmaxall=0
    else:
        totnstepsmaxall=None
    comm.Barrier()

    totnstepsmaxall=comm.reduce(totnstepsmax,op=MPI.MAX,root=0)
    tskymapall = comm.reduce(tskymap, op=MPI.MAX, root=0)
    tteleall = comm.reduce(ttele,op=MPI.MAX,root=0)
    comm.Gatherv(skystart,skystartall,root=0)
    comm.Gatherv(telestart, telestartall, root=0)
    comm.Gatherv(color,colorall, root=0)
    trk4min=comm.reduce(trk4,op=MPI.MIN,root=0)
    comm.Barrier()
    tend = MPI.Wtime()
    tall = tend-tstart
    if id==0:
        tindexstart = MPI.Wtime()
        for index in range(pixelheight*pixelwidth):

            if(colorall[index]==1):
                telepixels[telestartall[index]:telestartall[index]+3]=skypixels[skystartall[index]:skystartall[index]+3]
            else:
                telepixels[telestartall[index]]=255 #leave other two indices zero,red
        tindexend = MPI.Wtime()
        tindex = tindexend-tindexstart
    if id==0:
        twritestart = MPI.Wtime()
        ftele = open('teleview_{pw}_{ph}_{ws}.png'.format(pw=pixelwidth,ph=pixelheight,ws=wsize), "w")
        telewrite=Writer(width=pixelwidth,height=pixelheight,greyscale=False,alpha=False)
        telewrite.write_array(ftele,telepixels)
        ftele.close()
        twriteend=MPI.Wtime()
        twrite = twriteend-twritestart
    fsky.close()
    comm.Barrier()
    tmax = comm.reduce(tall,MPI.MAX,root=0)
    tpercparmin = comm.reduce(tpercpar/tall,op=MPI.MIN,root=0)
    comm.Barrier()
    if (id==0):
#        print("Telescope dimensions in M", 2.*imagewidth, 2.*imageheight)
#        print("Telescope resolution", pixelwidth, pixelheight)
#        print("Skymap resolution", skypixelwidth, skypixelheight)
#        print("Schwarzschild radius in M", 2.*Rs)
#        print("Outer radius in M", 2.*Router)
#        print("Telescope radius in M", 2.*Rplane)
#        print("Number of processes = ",wsize)
#        print("Maximum number of integration steps taken is",totnstepsmaxall)
#        print("The time for a single step of the RK4 is",trk4min)
#        print("Total runtime = ",tmax)
#        print("Fraction parallel = ", tpercparmin)
        print pixelwidth,pixelheight,wsize,totnstepsmaxall,trk4min,tmax,tpercparmin, tindex, twrite, tskymapall, tteleall

    MPI.Finalize()
示例#9
0
def draw(name, diagram, column_variables, row_variables):
    rows = list(get_rows(diagram, column_variables, row_variables, transform=int))
    writer = Writer(width=screen_width, height=screen_height, greyscale=isinstance(diagram, Diagram))
    with open("visual/{}.png".format(name), "w") as outfile:
        writer.write(outfile, rows)
示例#10
0
 def __init__(self, *args, **kwargs):
     Writer.__init__(self, *args, **kwargs)
     self.fITS = False
     self.qANT = False
     self.nANS = False
示例#11
0
文件: ico2png.py 项目: ilg/ico2png.py
def ico2png(data):
	"""Convert the bytestring data of an ICO file to PNG-format data as a bytestring."""
	# try to extract the 6-byte ICO header
	try:
		header = unpack('<3H', data[0:6])
	except:
		raise TypeError # data is not an ICO
	if header[:2] != (0,1):
		raise TypeError # data is not an ICO

	# the number of images in the file is header[2]
	image_count = header[2]

	# collect the icon directories
	directories = []
	for i in xrange(image_count):
		directory = list(unpack('<4B2H2I', data[6 + 16 * i : 6 + 16 * i + 16]))
		for j in xrange(3):
			if not directory[j]:
				directory[j] = 256
		directories.append(directory)

	# select "best" icon (??)
	directory = max(directories, key=(lambda x:x[0:3]))

	# get data of that image
	width = directory[0]
	height = directory[1]
	offset = directory[7]
	result = {
		'width':width,
		'height':height,
		'colors':directory[2],
		'bytes':directory[6],
		'offset':offset,
		}
	if data[offset:offset+16] == "\211PNG\r\n\032\n":
		# looks like a PNG, so return the data from here out.
		return data[offset:]
	else:
		dib_size = unpack('<I', data[offset:offset+4])[0]
		if dib_size != 40:
			raise TypeError # don't know how to handle an ICO where the DIB isn't 40 bytes
		else:
			dib = unpack('<L2l2H2L2l2L', data[offset:offset+dib_size])
			bits_per_pixel = dib[4]
			bmp_data_bytes = dib[6]
			if bmp_data_bytes == 0:
				bmp_data_bytes = width * height * bits_per_pixel / 8
			if bits_per_pixel <= 8:
				# assemble the color palette
				color_count = 2 ** bits_per_pixel
				raw_colors = [
					unpack('BBBB', data[offset + dib_size + 4 * i : offset + dib_size + 4 * i + 4])
					for i in xrange(0,color_count)
					]
				# the RGBQUAD for each palette color is (blue, green, red, reserved)
				palette = [ tuple([color[x] for x in (2, 1, 0)]) for color in raw_colors ]

				# get the XorMap bits
				xor_data_bits = [
					bit
					for byte in data[
						offset + dib_size + color_count * 4
						: offset + dib_size + color_count * 4 + bmp_data_bytes
						]
					for bit in _bitlist(unpack('B',byte)[0])
					]
				# get the AndMap bits
				and_row_size = ((width + 31) >> 5) << 2
				and_data_bits = [
					bit
					for byte in data[
						offset + dib_size + color_count * 4 + bmp_data_bytes
						: offset + dib_size + color_count * 4 + bmp_data_bytes + and_row_size * height
						]
					for bit in _bitlist(unpack('B',byte)[0])
					]

				# assemble the combined image (with transparency)
				def get_pixel(x,y):
					if and_data_bits[(height - y - 1) * and_row_size * 8 + x] == 1:
						# transparent
						return (0,0,0,0)
					else:
						# use the xor value, made solid
						return palette[_bitlistvalue(
							xor_data_bits[
								bits_per_pixel * ((height - y - 1) * width + x)
								: bits_per_pixel * ((height - y - 1) * width + x) + bits_per_pixel
								]
							)] + (255,)
				pixels = [
					[
						c
						for x in xrange(result['width'])
						for c in get_pixel(x,y)
						]
					for y in xrange(result['height'])
					]
			elif bits_per_pixel == 32:
				raw_pixels = [
					[
						unpack('BBBB', data[offset + dib_size + 4 * (y * width + x) : offset + dib_size + 4 * (y * width + x) + 4])
						for x in xrange(width)
						]
					for y in xrange(height-1, -1, -1)
					]
				pixels = [
					[
						c
						for px in row
						for c in (px[2], px[1], px[0], px[3])
						]
					for row in raw_pixels
					]
			elif bits_per_pixel == 24:
				raw_pixels = [
					[
						unpack('BBB', data[offset + dib_size + 3 * (y * width + x) : offset + dib_size + 3 * (y * width + x) + 3])
						for x in xrange(width)
						]
					for y in xrange(height-1, -1, -1)
					]
				pixels = [
					[
						c
						for px in row
						for c in (px[2], px[1], px[0], 255)
						]
					for row in raw_pixels
					]
			else:
				raise TypeError # don't know how to handle the pixel depth value
					
	out = StringIO()
	w = PNGWriter(result['width'],result['height'],alpha=True)
	w.write(out, pixels)
	return out.getvalue()
示例#12
0
def ico2png(data):
    """Convert the bytestring data of an ICO file to PNG-format data as a bytestring."""
    # try to extract the 6-byte ICO header
    try:
        header = unpack('<3H', data[0:6])
    except:
        raise TypeError  # data is not an ICO
    if header[:2] != (0, 1):
        raise TypeError  # data is not an ICO

    # the number of images in the file is header[2]
    image_count = header[2]

    # collect the icon directories
    directories = []
    for i in xrange(image_count):
        directory = list(unpack('<4B2H2I', data[6 + 16 * i:6 + 16 * i + 16]))
        for j in xrange(3):
            if not directory[j]:
                directory[j] = 256
        directories.append(directory)

    # select "best" icon (??)
    directory = max(directories, key=(lambda x: x[0:3]))

    # get data of that image
    width = directory[0]
    height = directory[1]
    offset = directory[7]
    result = {
        'width': width,
        'height': height,
        'colors': directory[2],
        'bytes': directory[6],
        'offset': offset,
    }
    if data[offset:offset + 16] == "\211PNG\r\n\032\n":
        # looks like a PNG, so return the data from here out.
        return data[offset:]
    else:
        dib_size = unpack('<I', data[offset:offset + 4])[0]
        if dib_size != 40:
            raise TypeError  # don't know how to handle an ICO where the DIB isn't 40 bytes
        else:
            dib = unpack('<L2l2H2L2l2L', data[offset:offset + dib_size])
            bits_per_pixel = dib[4]
            bmp_data_bytes = dib[6]
            if bmp_data_bytes == 0:
                bmp_data_bytes = width * height * bits_per_pixel / 8
            if bits_per_pixel <= 8:
                # assemble the color palette
                color_count = 2**bits_per_pixel
                raw_colors = [
                    unpack(
                        'BBBB', data[offset + dib_size + 4 * i:offset +
                                     dib_size + 4 * i + 4])
                    for i in xrange(0, color_count)
                ]
                # the RGBQUAD for each palette color is (blue, green, red, reserved)
                palette = [
                    tuple([color[x] for x in (2, 1, 0)])
                    for color in raw_colors
                ]

                # get the XorMap bits
                xor_data_bits = [
                    bit for byte in data[offset + dib_size +
                                         color_count * 4:offset + dib_size +
                                         color_count * 4 + bmp_data_bytes]
                    for bit in _bitlist(unpack('B', byte)[0])
                ]
                # get the AndMap bits
                and_row_size = ((width + 31) >> 5) << 2
                and_data_bits = [
                    bit for byte in data[offset + dib_size + color_count * 4 +
                                         bmp_data_bytes:offset + dib_size +
                                         color_count * 4 + bmp_data_bytes +
                                         and_row_size * height]
                    for bit in _bitlist(unpack('B', byte)[0])
                ]

                # assemble the combined image (with transparency)
                def get_pixel(x, y):
                    if and_data_bits[(height - y - 1) * and_row_size * 8 +
                                     x] == 1:
                        # transparent
                        return (0, 0, 0, 0)
                    else:
                        # use the xor value, made solid
                        return palette[_bitlistvalue(
                            xor_data_bits[bits_per_pixel * (
                                (height - y - 1) * width + x):bits_per_pixel *
                                          ((height - y - 1) * width + x) +
                                          bits_per_pixel])] + (255, )

                pixels = [[
                    c for x in xrange(result['width'])
                    for c in get_pixel(x, y)
                ] for y in xrange(result['height'])]
            elif bits_per_pixel == 32:
                raw_pixels = [[
                    unpack(
                        'BBBB',
                        data[offset + dib_size + 4 * (y * width + x):offset +
                             dib_size + 4 * (y * width + x) + 4])
                    for x in xrange(width)
                ] for y in xrange(height - 1, -1, -1)]
                pixels = [[
                    c for px in row for c in (px[2], px[1], px[0], px[3])
                ] for row in raw_pixels]
            elif bits_per_pixel == 24:
                raw_pixels = [[
                    unpack(
                        'BBB',
                        data[offset + dib_size + 3 * (y * width + x):offset +
                             dib_size + 3 * (y * width + x) + 3])
                    for x in xrange(width)
                ] for y in xrange(height - 1, -1, -1)]
                pixels = [[
                    c for px in row for c in (px[2], px[1], px[0], 255)
                ] for row in raw_pixels]
            else:
                raise TypeError  # don't know how to handle the pixel depth value

    out = StringIO()
    w = PNGWriter(result['width'], result['height'], alpha=True)
    w.write(out, pixels)
    return out.getvalue()