def load_depth(path): # PyPNG library is used since it allows to save 16-bit PNG r = png.Reader(filename=path) im = np.vstack(map(np.uint16, r.asDirect()[2])).astype(np.float32) # itertools.imap is removed in py3 return im
"0": "-----", ".": ".-.-.-", ",": "--..--", ":": "---...", "?": "..--..", "'": ".----.", "-": "-....-", "/": "-..-.", "@": ".--.-.", "=": "-...-" } inverse_morse_alphabet = dict((v, k) for (k, v) in morse_alphabet.items()) # Read in our png file reader = png.Reader(filename='download.png') w, h, pixels, metadata = reader.read_flat() # Iterate over the image, keeping a counter so we can calculate distance last_white_pixel_pos = 0 current_pos = 0 morse_string = "" for i in pixels: if i == 1: morse_string += chr(current_pos - last_white_pixel_pos) last_white_pixel_pos = current_pos current_pos += 1 # Divide up the morse code and translate each letter
import png import numpy as np reader = png.Reader('C:/png16.png') data = reader.asDirect() width = data[0] height = data[1] pixels = data[2] greyscale = data[3]['greyscale'] alpha = data[3]['alpha'] bitdepth = data[3]['bitdepth'] image = [] i = 0 j = 0 for row in pixels: row = np.asarray(row) if bitdepth == 16: for i in range(0, row.size): if alpha and i % 4 == 3: pass else: row[i] = pow(row[i] / 65535, 0.45) * 255 row = np.asarray(row, dtype='uint8') image.append(row) f = open('C:/Test.png', 'wb') writer = png.Writer(width, height, greyscale=greyscale, alpha=alpha) writer.write(f, image) f.close() # import png
def file2image(path): """ Reads an image into a list of lists of pixel values (tuples with three values). This is a color image. """ (w, h, p, m) = png.Reader(filename=path).asRGBA() # force RGB and alpha return [_flat2boxed(r) for r in p]
def read_screenshot(screenshot_path): reader = png.Reader(filename=screenshot_path) # todo - resize according to tile size w, h, pixels, metadata = reader.read_flat() return (w, h, pixels, metadata)
def testSigOnly(self): """Test file containing just signature bytes.""" r = png.Reader(bytes=pngsuite.basi0g01[:8]) self.assertRaises(png.FormatError, r.asDirect)
def getImageVals(url): r = png.Reader(file=urllib2.urlopen(url)) w, h, pixels, metadata = r.read() pxlist = list(pixels) return pxlist
#python -m pip install pypng import png import math from math_helper import * from setup import * from renderer import * from Frame import * from Camera import * from EnvironmentMap import * print("Starting our ray tracer") r = png.Reader("background.png") temp = r.read() EnvironmentMap.backgroundData = list(temp[2]) EnvironmentMap.backgroundWidth = temp[0] EnvironmentMap.backgroundHeight = temp[1] print(f'The background image has dimensions {str(temp[0])}, {str(temp[1])}') ## Run the ray tracing algorithm run() #Write the buffer out to a file #Open the output file in binary mode f = open('./saved.png', 'wb') #Create a write object w = png.Writer(Frame.width, Frame.height, greyscale=False)
def load_depth(path, mul=1., shift=(-4, -1)): r = png.Reader(filename=path) im = np.vstack(list(map(np.uint16, r.asDirect()[2]))) im = (im * mul).astype(np.float32) im = np.roll(im, shift, (0, 1)) return im
gradient blocks, so instead I recorded the current color and then recorded the next gradient when the color changed. Of course, doing that disallows repeated characters. So "110", "116", etc in the list of ints that I needed to come up with "integrity" were outputting as just "10", "16", etc. When I fell back to skipping 7 pixels to the right at a time, all was fixed. """ import png, time file = "oxygen.png" fh = open(file, "rb") r = png.Reader(fh) w, h, pixel_map, mydict = r.read() ### A list is easier to deal with than a map. pixel_list = list(pixel_map) ### This was my first attempt gradients = [] row = 0 for pixel_row in pixel_list: row +=1 if row != h // 2: continue for i in range( 0, len(pixel_row), 4*7): gradients.append( pixel_row[i] ) word = "".join([ chr(g) for g in gradients ])
def load_png(path, mode, halve_width=False, transparent_physical_index=None, transparent_rgb=None, print_warnings=True, use_fixed_16=False): '''loads PATH, a PNG representing a BBC screen in mode MODE, returning a 2d array of BBC physical colour indexes for the caller to disentangle. TRANSPARENT_PHYSICAL_INDEX, if not None, is the value to produce for transparent pixels. TRANSPARENT_RGB is the opaque RGB value, if any, to treat as transparent. ''' png_result = png.Reader(filename=path).asRGBA() width = png_result[0] height = png_result[1] pixels = [] for row in png_result[2]: pixels.append([]) for x in range(0, len(row), 4): pixels[-1].append((row[x + 0], row[x + 1], row[x + 2], row[x + 3])) if halve_width: good = True for y in range(len(pixels)): row = [] for x in range(0, len(pixels[y]), 4): if pixels[y][x + 0] != pixels[y][x + 1]: print >> sys.stderr, 'pixel at (%d,%d) is different from pixel at (%d,%d)' % ( x + 0, y, x + 1, y) #good=False row.append(pixels[y][x + 0]) pixels[y] = row if not good: raise ValueError('image not suitable for width halving') pidxs = [] for y in range(len(pixels)): pidxs.append([]) for x in range(len(pixels[y])): p = pixels[y][x] if p[3] < 128 or (transparent_rgb is not None and p[0] == transparent_rgb[0] and p[1] == transparent_rgb[1] and p[2] == transparent_rgb[2]): if transparent_physical_index is None: if print_warnings: print >> sys.stderr, 'invalid transparency' pidx = -1 #raise ValueError('invalid transparency') else: pidx = transparent_physical_index elif use_fixed_16: pidx = find_closest_fixed(p) if pidx is None: if print_warnings: print >> sys.stderr, 'failed to match fixed_16 for RGB (%d,%d,%d)' % ( p[0], p[1], p[2]) pidx = 0 else: for i in range(3): if p[i] != 0 and p[i] != 255: p = find_closest_rgb(p) if print_warnings: print >> sys.stderr, 'Non-BBC Micro colour %s at (%d,%d) - using %s' % ( pixels[y][x], x, y, p) break pidx = rgbs.index((p[0], p[1], p[2])) pidxs[-1].append(pidx) for y in range(1, len(pixels)): assert len(pixels[y]) == len(pixels[y - 1]) return pidxs
def from_dir(path, read_images=True): self = Sprite() xml = ET.parse(str(path / "SpriteSheet.xml")) SpriteSheet = xml.getroot() true_max_components = 0 self.max_components = int(SpriteSheet.get("a")) self.num_variations = int(SpriteSheet.get("b")) for Palette in SpriteSheet.findall("./PaletteList/Palette"): if read_images: img = png.Reader(str(path / Palette.get("src"))) img.preamble(True) palette = img.palette(alpha="force") assert len(palette) == 16 self.palettes.append(palette) self.palette_names.append(Palette.get("src").split(".png")[0]) for Raster in SpriteSheet.findall("./RasterList/Raster"): if read_images: img_path = str(path / Raster.get("src")) width, height, raster, info = png.Reader(img_path).read_flat() image = Image() image.width = width image.height = height image.raster = raster image.palette_index = int(Raster.get("palette"), base=16) assert (image.width % 8) == 0, f"{img_path} width is not a multiple of 8" assert (image.height % 8) == 0, f"{img_path} height is not a multiple of 8" self.images.append(image) self.image_names.append(Raster.get("src").split(".png")[0]) for i, Animation in enumerate( SpriteSheet.findall("./AnimationList/Animation")): components = [] for ComponentEl in Animation.findall("Component"): comp = Component() x, y, z = ComponentEl.get("xyz", "0,0,0").split(",") comp.x = int(x) comp.y = int(y) comp.z = int(z) for Command in ComponentEl: comp.commands.append(int(Command.get("val"), base=16)) components.append(comp) self.animation_names.append(Animation.get("name")) self.animations.append(components) if len(components) > true_max_components: true_max_components = len(components) assert self.max_components == true_max_components, f"{true_max_components} component(s) used, but SpriteSheet.a = {self.max_components}" return self
def main(): try: frames_dir = sys.argv[1] output_path = sys.argv[2] json_output_path = sys.argv[3] except: print 'python pngvideo.py <frames> <output.png> <output.json>' sys.exit(1) # Read each frame frames = [] for frame_name in standard_sorted(os.listdir(frames_dir)): if not frame_name.lower().endswith('.png'): continue frame_path = os.path.join(frames_dir, frame_name) frames.append({ 'originalPath': frame_path, 'png': png.Reader(filename=frame_path), }) # Check that we have any frames at all if not frames: print 'No frames found in source directory.' sys.exit(1) # Determine which frame is full frames[0]['isFull'] = True lastFull = frames[0] allrows = [] lastFullPixels = box(lastFull['png'].asRGBA8()[2]) allrows.extend(unbox(lastFullPixels)) for f in frames[1:]: print f['originalPath'] print f['png'].asRGBA8()[2] unboxedpixels = f['png'].asRGBA8()[2] pixels = box(unboxedpixels) isFull = False unchanged = 0 changed = 0 for i in xrange(len(lastFullPixels)): for j in xrange(len(lastFullPixels[i])): a = lastFullPixels[i][j] b = pixels[i][j] if b[3] == 255 or a[3] == 0 or a == b: unchanged += 1 continue changed += 1 print i print j print a print b isFull = True break if isFull: break # Delta encode if not isFull: for i in xrange(len(lastFullPixels)): for j in xrange(len(lastFullPixels[i])): a = lastFullPixels[i][j] b = pixels[i][j] if a == b: pixels[i][j] = (0, 0, 0, 0) else: lastFullPixels = pixels f['isFull'] = isFull allrows.extend(unbox(pixels)) fullpng = png.from_array(allrows, 'RGBA;8') fullpng.save(output_path) json_output = { "width": len(allrows[0]) / 4, "height": len(allrows) / len(frames), "frame": [{ "isFull": f["isFull"], "duration": 1.0, } for f in frames], } with open(json_output_path, 'w') as jo: jo.write(json.dumps(json_output, sort_keys=True, indent=2 ))
def load_png_into_matrix(self): # A simple function that finds the mean def find_mean(value_list): k = 0.0 for i_val in value_list: k += i_val return k / len(value_list) # PNG File has a key map as to the colour, with each pixel assigned a number corresponding to the colour # First need to create a map of these colours and what radar intensity they represent. palette_key_temp = { '(245, 245, 255, 255)': 1, '(180, 180, 255, 255)': 2, '(120, 120, 255, 255)': 3, '(20, 20, 255, 255)': 4, '(0, 216, 195, 255)': 5, '(0, 150, 144, 255)': 6, '(0, 102, 102, 255)': 7, '(255, 255, 0, 255)': 8, '(255, 200, 0, 255)': 9, '(255, 150, 0, 255)': 10, '(255, 100, 0, 255)': 11, '(255, 0, 0, 255)': 12, '(200, 0, 0, 255)': 13, '(120, 0, 0, 255)': 14, '(40, 0, 0, 255)': 15 } # Need to create a map that will correspond the intensity to what ever the PNG index number is palette_key_reversed = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0 } # This map is group together, basically use an average of the whole map to ensure that there are not two # indexes that are unintentionally assigned. Thisi s what i_avg is for i_avg = [] # Open the file with the PNG reader: r = png.Reader(self.radar_path) read = r.read() # Read through the palette key from the PNG - read[3]['palette'] for i in range(0, len(read[3]['palette'])): # Check through the palette key representing the intensity colours for j in palette_key_temp: # If there is a match (ie. the PNG palette key represents an intensity colour if str(read[3]['palette'][i]) == str(j): # Take note of the index in the PNG. # This will be used to ensure all indices are close to each other (in a bunch) remducing and # almost removing the possibility of doubling up on hte PNG indices reoccurring i_avg.append(i) # Find the mean of the indices i_avg = find_mean(i_avg) # Go through the PNG palette again for i in range(0, len(read[3]['palette'])): # Go through the locally defined palette for j in palette_key_temp: # If there is a match between the local palette and the PNG palette if str(read[3]['palette'][i]) == str(j): # Make sure that the PNG and local palette are not duplicates if fabs(i - i_avg) < 16: # Add the key/value combination to be used to decode the PNG palette_key_reversed[palette_key_temp[j]] = i # Flip the palette key around to give the PNG palette to return the intensity value palette_key = dict((v, k) for k, v in palette_key_reversed.iteritems()) # Load the data into a matrix self.matrix_radar_initial_load = np.vstack(read[2]) # Copy the initial matrix into the working matrix self.matrix_radar_working = np.copy(self.matrix_radar_initial_load) # Work through the working matrix, substitute the PNG palette for intensity values for k, v in palette_key.iteritems(): self.matrix_radar_working[self.matrix_radar_working == k] = v # Zero everything else temp_matrix = np.asarray(self.matrix_radar_working) high_values_indices = temp_matrix > 15 # Where values are low low_values_indices = temp_matrix < 0 # Where values are low temp_matrix[high_values_indices] = 0 # All low values set to 0 temp_matrix[low_values_indices] = 0 # All low values set to 0 # Copy matrix into final self.matrix_radar_finished = np.flipud(temp_matrix)
def testTrnsArray(self): """Test that reading a type 2 PNG with tRNS chunk yields each row as an array (using asDirect).""" r = png.Reader(bytes=pngsuite.tbrn2c08) list(r.asDirect()[2])[0].tostring
def main(): hinit = 1.e-1 #h=1.e-4 Router = 1000. Rplane = 700. Rs = 2. pixelwidth = 10 pixelheight = 10 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 fsky = open("skymap.png", "r") reader = png.Reader(fsky) skypixelwidth, skypixelheight, skypixels, metadata = reader.read_flat() 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) comm = MPI.COMM_WORLD id = comm.Get_rank() wsize = comm.Get_size() wtimep = MPI.Wtime() numperprocess = pixelheight * pixelwidth / wsize totnstepsall = np.zeros((wsize), dtype=np.uint32) 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) 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) print(trk4) comm.Barrier() if id == 0: totnstepsmaxall = 0 else: totnstepsmaxall = None comm.Barrier() totnstepsmaxall = comm.reduce(totnstepsmax, 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() if id == 0: 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 ftele = open("teleview.png", "w") telewrite = png.Writer(width=pixelwidth, height=pixelheight, greyscale=False, alpha=False) telewrite.write_array(ftele, telepixels) ftele.close() fsky.close() if id == 0: print("Maximum number of integration steps taken is", totnstepsmaxall) print("The time for a single step of the RK4 is", trk4min) MPI.Finalize()
def testEmpty(self): """Test empty file.""" r = png.Reader(bytes='') self.assertRaises(png.FormatError, r.asDirect)
def png_to_2bpp(filein, **kwargs): """ Convert a png image to planar 2bpp. """ arguments = { 'tile_padding': 0, 'pic_dimensions': False, 'interleave': False, 'norepeat': False, 'tilemap': False, } arguments.update(kwargs) if type(filein) is str: filein = open(filein) assert type(filein) is file width, height, rgba, info = png.Reader(filein).asRGBA8() # png.Reader returns flat pixel data. Nested is easier to work with len_px = len('rgba') image = [] palette = [] for line in rgba: newline = [] for px in xrange(0, len(line), len_px): color = dict(zip('rgba', line[px:px+len_px])) if color not in palette: if len(palette) < 4: palette += [color] else: # TODO Find the nearest match print 'WARNING: %s: Color %s truncated to' % (filein, color), color = sorted(palette, key=lambda x: sum(x.values()))[0] print color newline += [color] image += [newline] assert len(palette) <= 4, '%s: palette should be 4 colors, is really %d (%s)' % (filein, len(palette), palette) # Pad out smaller palettes with greyscale colors greyscale = { 'black': { 'r': 0x00, 'g': 0x00, 'b': 0x00, 'a': 0xff }, 'grey': { 'r': 0x55, 'g': 0x55, 'b': 0x55, 'a': 0xff }, 'gray': { 'r': 0xaa, 'g': 0xaa, 'b': 0xaa, 'a': 0xff }, 'white': { 'r': 0xff, 'g': 0xff, 'b': 0xff, 'a': 0xff }, } preference = 'white', 'black', 'grey', 'gray' for hue in map(greyscale.get, preference): if len(palette) >= 4: break if hue not in palette: palette += [hue] palette.sort(key=lambda x: sum(x.values())) # Game Boy palette order palette.reverse() # Map pixels to quaternary color ids padding = get_image_padding(width, height) width += padding['left'] + padding['right'] height += padding['top'] + padding['bottom'] pad = bytearray([0]) qmap = [] qmap += pad * width * padding['top'] for line in image: qmap += pad * padding['left'] for color in line: qmap += [palette.index(color)] qmap += pad * padding['right'] qmap += pad * width * padding['bottom'] # Graphics are stored in tiles instead of lines tile_width = 8 tile_height = 8 num_columns = max(width, tile_width) / tile_width num_rows = max(height, tile_height) / tile_height image = [] for row in xrange(num_rows): for column in xrange(num_columns): # Split it up into strips to convert to planar data for strip in xrange(min(tile_height, height)): anchor = ( row * num_columns * tile_width * tile_height + column * tile_width + strip * width ) line = qmap[anchor : anchor + tile_width] bottom, top = 0, 0 for bit, quad in enumerate(line): bottom += (quad & 1) << (7 - bit) top += (quad /2 & 1) << (7 - bit) image += [bottom, top] dim = arguments['pic_dimensions'] if dim: if type(dim) in (tuple, list): w, h = dim else: # infer dimensions based on width. w = width / tile_width h = height / tile_height if h % w == 0: h = w tiles = get_tiles(image) pic_length = w * h tile_width = width / 8 trailing = len(tiles) % pic_length new_image = [] for block in xrange(len(tiles) / pic_length): offset = (h * tile_width) * ((block * w) / tile_width) + ((block * w) % tile_width) pic = [] for row in xrange(h): index = offset + (row * tile_width) pic += tiles[index:index + w] new_image += transpose(pic, w) new_image += tiles[len(tiles) - trailing:] image = connect(new_image) # Remove any tile padding used to make the png rectangular. image = image[:len(image) - arguments['tile_padding'] * 0x10] tmap = None if arguments['interleave']: image = deinterleave_tiles(image, num_columns) if arguments['pic_dimensions']: image, tmap = condense_image_to_map(image, w * h) elif arguments['norepeat']: image, tmap = condense_image_to_map(image) if not arguments['tilemap']: tmap = None arguments.update({ 'palette': palette, 'tmap': tmap, }) return image, arguments
def FromPng(png_data): width, height, pixels, meta = png.Reader(bytes=png_data).read_flat() return Bitmap(4 if meta['alpha'] else 3, width, height, pixels, meta)
def main(options): # Only support MODE 9 for now. MODE 13 coming later. if options.mode != 9: print >> sys.stderr, 'FATAL: invalid mode: %d' % options.mode sys.exit(1) pixels_per_byte = 2 pack = arc.pack_4bpp png_result = png.Reader(filename=options.input_path).asRGBA8() width = png_result[0] height = png_result[1] print 'Image width: {0} height: {1}'.format(width, height) palette = get_palette(png_result[2]) print 'Found {0} palette entries.'.format(len(palette)) if len(palette) > 16: print >> sys.stderr, 'FATAL: too many colours: %d' % len(palette) sys.exit(1) # Sort palette by intensity. palette.sort(key=lambda e: e[0] * e[0] + e[1] * e[1] + e[2] * e[2]) if len(palette) < 16: # Prefer entry 0 to be black, if not already. if palette[0] != [0, 0, 0]: palette.insert(0, [0, 0, 0]) # Pad end of palette with white: while len(palette) < 16: palette.append([255, 255, 255]) # Reading the file again seems wrong? png_result = png.Reader(filename=options.input_path).asRGBA8() pixels = to_box_row_palette_indices(png_result[2], palette) pixel_data = [] assert (len(pixels) == height) for row in pixels: assert (len(row) == width) for x in range(0, width, pixels_per_byte): xs = row[x + 0:x + pixels_per_byte] assert len(xs) == pixels_per_byte pixel_data.append(pack(xs)) assert (len(pixel_data) == width * height / pixels_per_byte) save_file(pixel_data, options.output_path) print 'Wrote {0} bytes Arc data.'.format(len(pixel_data)) if options.palette_path is not None: pal_data = [] for p in palette: warned = False for i in range(0, 3): if (p[i] & 0x0f) != 0 and not warned: if options.loud: print 'Warning: lost precision for colour', p warned = True pal_data.append(p[i] & 0xf0) pal_data.append(0) assert (len(pal_data) == 4 * len(palette)) save_file(pal_data, options.palette_path) print 'Wrote {0} bytes palette data.'.format(len(pal_data))
import sys import png # Run `python -m pip install pypng` if not found def is_pow_of_2(n): return (n & (n - 1)) == 0 def fatal(message): print(message) exit(1) if len(sys.argv) != 4: fatal('usage: ' + sys.argv[0] + ' colormap heightmap binfile') # Read colormap r = png.Reader(sys.argv[1]) (cmapWidth, cmapHeight, cmapRows, info) = r.read() if not is_pow_of_2(cmapWidth): fatal(sys.argv[1] + ': width must be a power of two') if not is_pow_of_2(cmapHeight): fatal(sys.argv[1] + ': height must be a power of two') if info['bitdepth'] != 8: fatal(sys.argv[1] + ': bit depth must be 8') # Read heightmap r = png.Reader(sys.argv[2]) (hmapWidth, hmapHeight, hmapRows, info) = r.read() if not is_pow_of_2(hmapWidth): fatal(sys.argv[2] + ': width must be a power of two') if not is_pow_of_2(hmapHeight): fatal(sys.argv[2] + ': height must be a power of two')
def read_png_file(filepath): data = png.Reader(filename=filepath).asRGBA8() width = data[0] height = data[1] rows = list(data[2]) return width, height, rows
def LoadTextures(): global texture texture = glGenTextures(6) ################################################################################ glBindTexture(GL_TEXTURE_2D, texture[0]) reader = png.Reader(filename='dado.png') w, h, pixels, metadata = reader.read_flat() if (metadata['alpha']): modo = GL_RGBA else: modo = GL_RGB glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL_UNSIGNED_BYTE, pixels.tolist()) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) ################################################################################ ################################################################################ glBindTexture(GL_TEXTURE_2D, texture[1]) reader = png.Reader(filename='dado.png') w, h, pixels, metadata = reader.read_flat() if (metadata['alpha']): modo = GL_RGBA else: modo = GL_RGB glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL_UNSIGNED_BYTE, pixels.tolist()) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) ################################################################################ ################################################################################ glBindTexture(GL_TEXTURE_2D, texture[2]) reader = png.Reader(filename='dado.png') w, h, pixels, metadata = reader.read_flat() if (metadata['alpha']): modo = GL_RGBA else: modo = GL_RGB glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL_UNSIGNED_BYTE, pixels.tolist()) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) ################################################################################ ################################################################################ glBindTexture(GL_TEXTURE_2D, texture[3]) reader = png.Reader(filename='dado.png') w, h, pixels, metadata = reader.read_flat() if (metadata['alpha']): modo = GL_RGBA else: modo = GL_RGB glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL_UNSIGNED_BYTE, pixels.tolist()) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) ################################################################################ ################################################################################ glBindTexture(GL_TEXTURE_2D, texture[4]) reader = png.Reader(filename='dado.png') w, h, pixels, metadata = reader.read_flat() if (metadata['alpha']): modo = GL_RGBA else: modo = GL_RGB glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL_UNSIGNED_BYTE, pixels.tolist()) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) ################################################################################ ################################################################################ glBindTexture(GL_TEXTURE_2D, texture[5]) reader = png.Reader(filename='dado.png') w, h, pixels, metadata = reader.read_flat() if (metadata['alpha']): modo = GL_RGBA else: modo = GL_RGB glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL_UNSIGNED_BYTE, pixels.tolist()) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) # glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
def getfingerprint(filepath): r = png.Reader(open(filepath, 'r')) block_matrix = [[0 for x in range(blocks_per_image_side)] for y in range(blocks_per_image_side)] img = r.read() img_x = img[0] img_y = img[1] img_data = img[2] img_info = img[3] # print (img_info) if not img_info['greyscale']: print(filepath, 'is not greyscale') sys.exit() if img_info['planes'] > 1: print(filepath, 'is not flat') sys.exit() if img_info['alpha']: print(filepath, 'has alpha') sys.exit() img_bitdepth = img_info['bitdepth'] #white = 2 ** img_bitdepth - 1 pixels_per_block = img_x / blocks_per_image_side for i in range(0, blocks_per_image_side): for j in range(0, blocks_per_image_side): bx = i * img_x / blocks_per_image_side by = j * img_y / blocks_per_image_side black_blocks = 0 for y in range(by, by + pixels_per_block): row = img_data[y] for x in range(bx, bx + pixels_per_block): if row[x] == 0: black_blocks += 1 if black_blocks / (pixels_per_block * pixels_per_block) > threshold: block_matrix[i][j] = -1 else: block_matrix[i][j] = 0 # print block_matrix fillnum = 1 for b in range(0, blocks_per_image_side): if block_matrix[b][0] is -1: fill(block_matrix, (b, 0), fillnum, -1) fillnum += 1 if block_matrix[blocks_per_image_side - 1][b] is -1: fill(block_matrix, (blocks_per_image_side - 1, b), fillnum, -1) fillnum += 1 if block_matrix[b][blocks_per_image_side - 1] is -1: fill(block_matrix, (b, blocks_per_image_side - 1), fillnum, -1) fillnum += 1 if block_matrix[0][b] is -1: fill(block_matrix, (0, b), fillnum, -1) fillnum += 1 edge = [[0 for x in range(blocks_per_image_side)] for y in range(4)] #clockwise for sides, but always left-to-right or top-to-bottom for b in range(0, blocks_per_image_side): edge[0][b] = block_matrix[b][0] edge[1][b] = block_matrix[blocks_per_image_side - 1][b] edge[2][b] = block_matrix[b][blocks_per_image_side - 1] edge[3][b] = block_matrix[0][b] # print edge fingerprint = '' for a in range(0, 4): for b in range(0, squares_per_side): data = Counter( edge[a][b * blocks_per_square_side:b * blocks_per_square_side + blocks_per_square_side]) if len(data.most_common(1)[0]) is 0 or 2 * data.most_common( 1)[0][1] <= blocks_per_square_side * discard_thresh: print filepath, ': edge on side', a, 'square', b, 'is ambiguous, perhaps increase blocks? Tile will not be included.', edge[ a][b * blocks_per_square_side:b * blocks_per_square_side + blocks_per_square_side] mode = 'X' else: mode = data.most_common(1)[0][0] # print 'edge on side',a,'square',b,'is',mode fingerprint = fingerprint + str(mode) return fingerprint
def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hi:o:f:b:k', [ 'help', 'input-file=', 'output-file=', 'output-format=verilog', 'output-bit-format=444', 'row-col-organization' ]) except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" usage() sys.exit(2) inputfile = None outputfile = None outputformat = "verilog" rcorganization = False rb = 4 gb = 4 bb = 4 for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-i", "--input-file"): inputfile = a elif o in ("-o", "--output-file"): outputfile = a elif o in ("-f", "--output-format"): outputformat = a elif o in ("-b", "--output-bit-format"): if len(a) != 3: usage() sys.exit(2) rb = int(a[0]) gb = int(a[1]) bb = int(a[2]) elif o in ("-k", "--row-col-organization"): rcorganization = True else: assert False, "unhandled option" if inputfile is None or outputfile is None: usage() sys.exit(2) print("Input file: %s" % (inputfile)) print("Output file: %s" % (outputfile)) print("Output format: %s" % (outputformat)) print("Output bit format: R%s, G%s, B%s" % (rb, gb, bb)) print("Keep row/col organization: %s" % rcorganization) r = png.Reader(inputfile) w, h, p, m = r.asRGB() address_bits_w = int.bit_length(w - 1) address_bits_h = int.bit_length(h - 1) if outputformat == "verilog": outputVerilog(p, address_bits_w, address_bits_h, outputfile, rb, gb, bb, w, h, rcorganization) elif outputformat == "quartus": outputQuartus(p, address_bits_w, address_bits_h, outputfile, rb, gb, bb, w, h, rcorganization)
def testPaletteForcealpha(self): """Test forcing alpha channel for palette""" r = png.Reader(bytes=pngsuite.basn3p04) r.preamble() r.palette(alpha='force')
def getImage(url, rowpixel, colpixel): r = png.Reader(file=urllib.request.urlopen(url)) w, h, pixels, metadata = r.read() pxlist = list(pixels) return pxlist[rowpixel][colpixel]
def testInterlacedArray(self): """Test that reading an interlaced PNG yields each row as an array.""" r = png.Reader(bytes=pngsuite.basi0g08) list(r.read()[2])[0].tostring
def PNGtoGcode(self, pos_file_png_exported, pos_file_png_BW, pos_file_gcode): ######## GENERO IMMAGINE IN SCALA DI GRIGI ######## #Scorro l immagine e la faccio diventare una matrice composta da list reader = png.Reader(pos_file_png_exported) #File PNG generato w, h, pixels, metadata = reader.read_flat() matrice = [[255 for i in range(w)] for j in range(h)] #List al posto di un array #Scrivo una nuova immagine in Scala di grigio 8bit #copia pixel per pixel if self.options.grayscale_type == 1: #0.21R + 0.71G + 0.07B for y in range(h): # y varia da 0 a h-1 for x in range(w): # x varia da 0 a w-1 pixel_position = ( x + y * w) * 4 if metadata['alpha'] else (x + y * w) * 3 matrice[y][x] = int(pixels[pixel_position] * 0.21 + pixels[(pixel_position + 1)] * 0.71 + pixels[(pixel_position + 2)] * 0.07) elif self.options.grayscale_type == 2: #(R+G+B)/3 for y in range(h): # y varia da 0 a h-1 for x in range(w): # x varia da 0 a w-1 pixel_position = ( x + y * w) * 4 if metadata['alpha'] else (x + y * w) * 3 matrice[y][x] = int((pixels[pixel_position] + pixels[ (pixel_position + 1)] + pixels[(pixel_position + 2)]) / 3) elif self.options.grayscale_type == 3: #R for y in range(h): # y varia da 0 a h-1 for x in range(w): # x varia da 0 a w-1 pixel_position = ( x + y * w) * 4 if metadata['alpha'] else (x + y * w) * 3 matrice[y][x] = int(pixels[pixel_position]) elif self.options.grayscale_type == 4: #G for y in range(h): # y varia da 0 a h-1 for x in range(w): # x varia da 0 a w-1 pixel_position = ( x + y * w) * 4 if metadata['alpha'] else (x + y * w) * 3 matrice[y][x] = int(pixels[(pixel_position + 1)]) elif self.options.grayscale_type == 5: #B for y in range(h): # y varia da 0 a h-1 for x in range(w): # x varia da 0 a w-1 pixel_position = ( x + y * w) * 4 if metadata['alpha'] else (x + y * w) * 3 matrice[y][x] = int(pixels[(pixel_position + 2)]) elif self.options.grayscale_type == 6: #Max Color for y in range(h): # y varia da 0 a h-1 for x in range(w): # x varia da 0 a w-1 pixel_position = ( x + y * w) * 4 if metadata['alpha'] else (x + y * w) * 3 list_RGB = pixels[pixel_position], pixels[( pixel_position + 1)], pixels[(pixel_position + 2)] matrice[y][x] = int(max(list_RGB)) else: #Min Color for y in range(h): # y varia da 0 a h-1 for x in range(w): # x varia da 0 a w-1 pixel_position = ( x + y * w) * 4 if metadata['alpha'] else (x + y * w) * 3 list_RGB = pixels[pixel_position], pixels[( pixel_position + 1)], pixels[(pixel_position + 2)] matrice[y][x] = int(min(list_RGB)) ####Ora matrice contiene l'immagine in scala di grigi ######## GENERO IMMAGINE IN BIANCO E NERO ######## #Scorro matrice e genero matrice_BN B = 255 N = 0 matrice_BN = [[255 for i in range(w)] for j in range(h)] if self.options.conversion_type == 1: #B/W fixed threshold soglia = self.options.BW_threshold for y in range(h): for x in range(w): if matrice[y][x] >= soglia: matrice_BN[y][x] = B else: matrice_BN[y][x] = N elif self.options.conversion_type == 2: #B/W random threshold from random import randint for y in range(h): for x in range(w): soglia = randint(20, 235) if matrice[y][x] >= soglia: matrice_BN[y][x] = B else: matrice_BN[y][x] = N elif self.options.conversion_type == 3: #Halftone Step1 = [[B, B, B, B, B], [B, B, B, B, B], [B, B, N, B, B], [B, B, B, B, B], [B, B, B, B, B]] Step2 = [[B, B, B, B, B], [B, B, N, B, B], [B, N, N, N, B], [B, B, N, B, B], [B, B, B, B, B]] Step3 = [[B, B, N, B, B], [B, N, N, N, B], [N, N, N, N, N], [B, N, N, N, B], [B, B, N, B, B]] Step4 = [[B, N, N, N, B], [N, N, N, N, N], [N, N, N, N, N], [N, N, N, N, N], [B, N, N, N, B]] for y in range(int(int(h) / 5)): for x in range(int(int(w) / 5)): media = 0 for y2 in range(5): for x2 in range(5): media += matrice[y * 5 + y2][x * 5 + x2] media = media / 25 for y3 in range(5): for x3 in range(5): if media >= 250 and media <= 255: matrice_BN[y * 5 + y3][x * 5 + x3] = B if media >= 190 and media < 250: matrice_BN[y * 5 + y3][x * 5 + x3] = Step1[y3][x3] if media >= 130 and media < 190: matrice_BN[y * 5 + y3][x * 5 + x3] = Step2[y3][x3] if media >= 70 and media < 130: matrice_BN[y * 5 + y3][x * 5 + x3] = Step3[y3][x3] if media >= 10 and media < 70: matrice_BN[y * 5 + y3][x * 5 + x3] = Step4[y3][x3] if media >= 0 and media < 10: matrice_BN[y * 5 + y3][x * 5 + x3] = N elif self.options.conversion_type == 4: #Halftone row Step1r = [B, B, N, B, B] Step2r = [B, N, N, B, B] Step3r = [B, N, N, N, B] Step4r = [N, N, N, N, B] for y in range(h): for x in range(w / 5): media = 0 for x2 in range(5): media += matrice[y][x * 5 + x2] media = media / 5 for x3 in range(5): if media >= 250 and media <= 255: matrice_BN[y][x * 5 + x3] = B if media >= 190 and media < 250: matrice_BN[y][x * 5 + x3] = Step1r[x3] if media >= 130 and media < 190: matrice_BN[y][x * 5 + x3] = Step2r[x3] if media >= 70 and media < 130: matrice_BN[y][x * 5 + x3] = Step3r[x3] if media >= 10 and media < 70: matrice_BN[y][x * 5 + x3] = Step4r[x3] if media >= 0 and media < 10: matrice_BN[y][x * 5 + x3] = N elif self.options.conversion_type == 5: #Halftone column Step1c = [B, B, N, B, B] Step2c = [B, N, N, B, B] Step3c = [B, N, N, N, B] Step4c = [N, N, N, N, B] for y in range(h / 5): for x in range(w): media = 0 for y2 in range(5): media += matrice[y * 5 + y2][x] media = media / 5 for y3 in range(5): if media >= 250 and media <= 255: matrice_BN[y * 5 + y3][x] = B if media >= 190 and media < 250: matrice_BN[y * 5 + y3][x] = Step1c[y3] if media >= 130 and media < 190: matrice_BN[y * 5 + y3][x] = Step2c[y3] if media >= 70 and media < 130: matrice_BN[y * 5 + y3][x] = Step3c[y3] if media >= 10 and media < 70: matrice_BN[y * 5 + y3][x] = Step4c[y3] if media >= 0 and media < 10: matrice_BN[y * 5 + y3][x] = N else: #Grayscale if self.options.grayscale_resolution == 1: matrice_BN = matrice else: for y in range(h): for x in range(w): if matrice[y][x] <= 1: matrice_BN[y][x] = 0 if matrice[y][x] >= 254: matrice_BN[y][x] = 255 if matrice[y][x] > 1 and matrice[y][x] < 254: matrice_BN[y][x] = ( matrice[y][x] // self.options.grayscale_resolution ) * self.options.grayscale_resolution ####Ora matrice_BN contiene l'immagine in Bianco (255) e Nero (0) #### SALVO IMMAGINE IN BIANCO E NERO #### file_img_BN = open(pos_file_png_BW, 'wb') #Creo il file Costruttore_img = png.Writer( w, h, greyscale=True, bitdepth=8) #Impostazione del file immagine Costruttore_img.write(file_img_BN, matrice_BN) #Costruttore del file immagine file_img_BN.close() #Chiudo il file #### GENERO IL FILE GCODE #### if self.options.preview_only == False: #Genero Gcode solo se devo if self.options.flip_y == False: #Inverto asse Y solo se flip_y = False #-> coordinate Cartesiane (False) Coordinate "informatiche" (True) matrice_BN.reverse() Laser_ON = False F_G01 = self.options.speed_ON Scala = self.options.resolution file_gcode = open(pos_file_gcode, 'w') #Creo il file #Configurazioni iniziali standard Gcode file_gcode.write( '; Generated with:\n; "Raster 2 Laser Gcode generator"\n; by 305 Engineering\n;\n;\n;\n' ) #HOMING if self.options.homing == 1: file_gcode.write('G28; home all axes\n') elif self.options.homing == 2: file_gcode.write('$H; home all axes\n') else: pass file_gcode.write('G21; Set units to millimeters\n') file_gcode.write('G90; Use absolute coordinates\n') file_gcode.write('G92; Coordinate Offset\n') #Creazione del Gcode #allargo la matrice per lavorare su tutta l'immagine for y in range(h): matrice_BN[y].append(B) w = w + 1 if self.options.conversion_type != 6: for y in range(h): if y % 2 == 0: for x in range(w): if matrice_BN[y][x] == N: if Laser_ON == False: #file_gcode.write('G00 X' + str(float(x)/Scala) + ' Y' + str(float(y)/Scala) + ' F' + str(F_G00) + '\n') file_gcode.write( 'G00 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + '\n') #tolto il Feed sul G00 file_gcode.write(self.options.laseron + '\n') Laser_ON = True if Laser_ON == True: #DEVO evitare di uscire dalla matrice if x == w - 1: file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False else: if matrice_BN[y][x + 1] != N: file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False else: for x in reversed(range(w)): if matrice_BN[y][x] == N: if Laser_ON == False: #file_gcode.write('G00 X' + str(float(x)/Scala) + ' Y' + str(float(y)/Scala) + ' F' + str(F_G00) + '\n') file_gcode.write( 'G00 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + '\n') #tolto il Feed sul G00 file_gcode.write(self.options.laseron + '\n') Laser_ON = True if Laser_ON == True: #DEVO evitare di uscire dalla matrice if x == 0: file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False else: if matrice_BN[y][x - 1] != N: file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False else: ##SCALA DI GRIGI for y in range(h): if y % 2 == 0: for x in range(w): if matrice_BN[y][x] != B: if Laser_ON == False: file_gcode.write('G00 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + '\n') file_gcode.write(self.options.laseron + ' ' + ' S' + str(255 - matrice_BN[y][x]) + '\n') Laser_ON = True if Laser_ON == True: #DEVO evitare di uscire dalla matrice if x == w - 1: #controllo fine riga file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False else: if matrice_BN[y][x + 1] == B: file_gcode.write( 'G01 X' + str(float(x + 1) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False elif matrice_BN[y][x] != matrice_BN[y][ x + 1]: file_gcode.write( 'G01 X' + str(float(x + 1) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseron + ' ' + ' S' + str(255 - matrice_BN[y][x + 1]) + '\n') else: for x in reversed(range(w)): if matrice_BN[y][x] != B: if Laser_ON == False: file_gcode.write('G00 X' + str(float(x + 1) / Scala) + ' Y' + str(float(y) / Scala) + '\n') file_gcode.write(self.options.laseron + ' ' + ' S' + str(255 - matrice_BN[y][x]) + '\n') Laser_ON = True if Laser_ON == True: #DEVO evitare di uscire dalla matrice if x == 0: #controllo fine riga ritorno file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False else: if matrice_BN[y][x - 1] == B: file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseroff + '\n') Laser_ON = False elif matrice_BN[y][x] != matrice_BN[y][ x - 1]: file_gcode.write( 'G01 X' + str(float(x) / Scala) + ' Y' + str(float(y) / Scala) + ' F' + str(F_G01) + '\n') file_gcode.write( self.options.laseron + ' ' + ' S' + str(255 - matrice_BN[y][x - 1]) + '\n') #Configurazioni finali standard Gcode file_gcode.write('G00 X0 Y0; home\n') #HOMING if self.options.homing == 1: file_gcode.write('G28; home all axes\n') elif self.options.homing == 2: file_gcode.write('$H; home all axes\n') else: pass file_gcode.close() #Chiudo il file
# reads in image, stores it in text files import png import os import shutil try: shutil.rmtree('uncompressed/') except OSError: print('making new folder') os.mkdir('uncompressed/') f = open('control.txt', 'r') imagename = next(f).split()[-1].strip() width, height, image, meta = png.Reader(imagename).asRGBA() print 'with image - ', imagename print 'dimensions - ', width, height redfile = open('uncompressed/red.txt', 'w') greenfile = open('uncompressed/green.txt', 'w') bluefile = open('uncompressed/blue.txt', 'w') colors = (redfile, bluefile, greenfile) for line in image: while line: for color in colors: color.write(str(line.pop(0)) + " ")