def visualize(self, resolution=1): rotations = [i.rotation for i in self.keyframes] xPositions = [i.x for i in self.keyframes] yPositions = [i.y for i in self.keyframes] maxRotation = max(rotations) minRotation = min(rotations) maxX = max(xPositions) minX = min(xPositions) maxY = max(yPositions) minY = min(yPositions) lowestPoint = min([minX, minY, minRotation]) highestPoint = max([maxX, maxY, maxRotation]) timeEnd = self.keyframes[-1].time sOut = Surface((timeEnd + 20, highestPoint - lowestPoint + 20)) sOut.fill((255, 255, 255)) point = 0 while point < timeEnd: #print(self.current_position(point)) rot, x, y = self.current_position(point) sOut.set_at((int(point + 10), sOut.get_height() - int(rot - lowestPoint + 10)), (255, 0, 0)) sOut.set_at((int(point + 10), sOut.get_height() - int(x - lowestPoint + 10)), (0, 255, 0)) sOut.set_at((int(point + 10), sOut.get_height() - int(y - lowestPoint + 10)), (0, 0, 255)) point += resolution sOut = transform.smoothscale( sOut, (sOut.get_width() * 4, sOut.get_height() * 4)) image.save(sOut, 'rotationVisual.png')
def gen_test_image(test_name, test_func): """Run the test case and save the resulting test_surf.""" test_surf = create_surface() test_func(test_surf) imgname = 'results/gen_%s.png' % test_name image.save(test_surf, imgname) print('completed %s. Result saved to %s' % (test_name, imgname))
def get_image(): sleep(.1) # Allow camera to calibrate exposure im = cam.get_image() image.save(im, "images/temp_img.jpg") return 'images/temp_img.jpg'
def trasform_image_to_level(json_tiler, img, output): tiler = Tiler() tiler.parse(json_tiler) img = image.load(img) w, h = img.get_size() print w, h, tiler.TileSize nw, nh = w * int(tiler.TileSize), h * int(tiler.TileSize) print nw, nh levelSurface = Surface((int(nw), int(nh))) levelMatrix = [] print "Started loading tiles Image" for i in range(0, len(tiler.Tiles)): tiler.Tiles[i].TileImage = image.load(tiler.Tiles[i].TilePath) print "Done loading tiles Image" print "Building the level" for y in range(0, h): matrixRow = [] for x in range(0, w): c = img.get_at((x, y)) r, g, b = c.r, c.g, c.b tile = tiler.get_tile_from_color([r, g, b]) matrixRow.append(tile.ID) levelSurface.blit(tile.TileImage, (x * tiler.TileSize, y * tiler.TileSize)) levelMatrix.append(matrixRow) print "Done building the level" print "Saving" outJson = open(output + ".json", "w+") outJson.write(dumps(levelMatrix)) outJson.close() image.save(levelSurface, output) print "Done saving"
def scale_image(self): '''scale image''' for filename in os.listdir(self.temp_directory): im = image.load(self._full_filename(filename)) scaled = scale(im, eval(input('please set size (width, heigt)' ' as in example: (1024,720): ').replace(' ',','))) image.save(scaled, self._full_filename(filename))
def main(shtfileName: str) -> None: with open(shtfileName, 'rb') as f: data = f.read() (bits, rle, _mode, _direction, nFrames, _start, _reserved) = unpack(HEADER_FORMAT, data[:HEADER_LENGTH]) nBits = int(bits[0]) isRLE = bool(rle[0]) print( f"{shtfileName}: {nBits}-bit {'RLE' if isRLE else 'Uncompressed'} {nFrames} frames" ) assert nBits in (8, 24) assert not isRLE, "RLE format is not supported, use -n when generating .sht file" startPosition = HEADER_LENGTH + (VGA_PALETTE_SIZE if nBits == 8 else 0) pixelSize = 1 if nBits == 8 else 3 frameSize = WIDTH * HEIGHT * pixelSize assert len(data) == startPosition + frameSize * nFrames fileNamePrefix = shtfileName[:shtfileName.rindex('.')] with TemporaryDirectory(prefix='rtr') as tempDir: fileNameTemplate = join(tempDir, f'{fileNamePrefix}-%08d.png') fileNames: List[str] = [] index = startPosition for nFrame in range(1, nFrames + 1): newIndex = index + frameSize frame = data[index:newIndex] index = newIndex if nBits == 8: frame = bytes(chain.from_iterable(zip(frame, frame, frame))) surface = frombuffer(frame, (WIDTH, HEIGHT), 'RGB') fileName = fileNameTemplate % nFrame save(surface, fileName) fileNames.append(fileName) print(nFrame) apngFileName = f'{fileNamePrefix}.png' print(f"Creating APNG {apngFileName}...") APNG.from_files(fileNames, delay=int(1000.0 / FPS)).save(apngFileName)
def main(): """ use pygame to convert a TTF to BMP """ if len(sys.argv) < 3: print("Usage: {} <TTF-file> <size>".format(sys.argv[0])) exit(1) fname = sys.argv[1] fsize = int(sys.argv[2]) outname = "{}_{}.BMP".format(os.path.splitext(fname)[0], fsize) print("Loading font {} in height {}...".format(fname, fsize)) init() f = Font(fname, fsize) print("Rendering {} characters '{}'".format(len(RENDER_STRING), RENDER_STRING)) width = None for ch in RENDER_CHARS: w, h = f.size(str(ch)) if width is None: width = w if w != width: print("ERROR: Font is not monospaced!") exit(1) surface = f.render(RENDER_STRING, False, (255, 255, 255), (0, 0, 0)) print("Writing rendered characters to '{}'...".format(outname)) image.save(surface, outname)
def test_conformance(test_func, verbose=False): """Run the test case and compare the resulting surface to the existing test case.""" test_name = test_func._filename passed = True for depth in DEPTHS: if depth not in test_func._supported_depths: continue test_surf = create_surface(depth) try: test_func(test_surf) except NotImplementedError: # Don't fail completely on not implemented functions pass except Exception as e: # Fail on other exceptions print('%s at depth %d Failed with exception %s' % (test_name, depth, e)) passed = False continue orig_name = 'results/gen_%d_%s.png' % (depth, test_name) try: orig_surf = image.load(orig_name) except Exception as e: # complain, fail and skip print("Unable to load %s (%s)" % (orig_name, e)) passed = False continue imgname = 'results/test_%d_%s.png' % (depth, test_name) image.save(test_surf, imgname) diffname = 'results/diff_%d_%s.png' % (depth, test_name) # sanity check assert orig_surf.get_size() == test_surf.get_size() differences = False diff_surf = create_surface(depth) # Pixel by pixel comparison. # This is slow, but avoids extra dependancies from pygame.surflock import locked orig_surf = orig_surf.convert(test_surf) with locked(orig_surf._c_surface): with locked(test_surf._c_surface): for x in range(800): for y in range(600): point = (x, y) if orig_surf._get_at(x, y) != test_surf._get_at(x, y): differences = True # Flag as pure white for easier visual inspection diff_surf.set_at(point, (255, 255, 255, 255)) if differences: print("conformance test %s FAILED for depth %d.\n" " Difference saved to %s" % (test_name, depth, diffname)) image.save(diff_surf, diffname) passed = False else: if verbose: print("conformance test %s passed for depth %d" % (test_name, depth)) return passed
def capture(self): # get the image from video & save as ./capimg.jpg surface = self.cam.get_image() if surface is None: print "Could not obtain image from webcam." return print "Saving curent image..." image.save(surface, './mntimg.jpg')
def guardarCaptura(self): if not 'webcam' in listdir('./'): mkdir('webcam') tiempo = strftime("%d %b %Y_%H:%M:%S", gmtime()) imagen = './webcam/' + self.usuario + '_' + tiempo + '.png' save(self.captura, imagen)
def resize_image(self): img = image.load(self.file_path) filename = os.path.splitext(self.file_path)[0] file_ext = os.path.splitext(self.file_path)[1] scaled = scale(img, (640, 480)) image.save(scaled, filename + '-640' + file_ext) print(image)
def capture(): print 'Capturing current image...' surface = cam.get_image() if surface is None: print 'Could not obtain image from webcam.' return print 'Saving current image...' renderText(surface) image.save(surface, '/var/www/webcam.jpg')
def process_files(self): '''Scale each image in the directory to 640x480''' for filename in os.listdir(self.processor.temp_directory): try: im = image.load(self.processor._full_filename(filename)) scaled = scale(im, (640,480)) image.save(scaled, self.processor._full_filename(filename)) except: pass
def trans(file_name): image = load(file_name).convert_alpha() w, h = image.get_size() #print(w,h) #image=chop(image,(0,0,0,h-half_y)) image = smoothscale(image, (maxn_x, maxn_y)) save(image, file_name) return file_name
def process(self, zipprocessor): """Scale each image in the directory to user's size""" for filename in os.listdir(zipprocessor.temp_directory): im = image.load(zipprocessor._full_filename(filename)) users_sizes = input( "Enter the size for image scaling for example - '640 400'" ).split() scaled = scale(im, (int(users_sizes[0]), int(users_sizes[1]))) image.save(scaled, zipprocessor._full_filename(filename))
def main(): parser = argparse.ArgumentParser(description="Time to D-D-D-Duel.") parser.add_argument("saveDir", help="Directory to save photos to.") parser.add_argument("--prefix", default="ygh-photo", help="File prefix for each numbered photo.") parser.add_argument("--psm", type=int, default=6, help="psm argument for tesseract tool.") args = parser.parse_args() prefix = args.prefix save_dir = args.saveDir psm = args.psm if not os.path.exists(save_dir): os.mkdir("./%s" % save_dir) # setup camera try: pc.init() print("Cameras -> ") print(pc.list_cameras()) webcam = pc.Camera(pc.list_cameras()[0]) webcam.start() except Exception as e: print("Error encountered when setting up webcam, check it's not already in use.") print(e) raise SystemExit i = webcam.get_image() pi.save(i, "./photo.png") # let user select when to take each photo, number them consecutively. count = 0 while True: input() img = webcam.get_image() file_path = "%s/%s%d.png" % (save_dir, prefix, count) pi.save(img, file_path) print("---> Processing image %s" % file_path) try: processed_fp = "%s/processed-%s%d.png" % (save_dir, prefix, count) preprocess_image(file_path, processed_fp) # Define config parameters. # '-l eng' for using the English language # '--oem 1' for using LSTM OCR Engine # psm 6 = words as a text line? config = ("-l eng --oem 1 --psm %d" % psm) text = pytesseract.image_to_string( Image.open(file_path), config=config) print("-----text found-------") print(text) print("----------------------") except UnicodeEncodeError: print("[!] had an issue encoding to Unicode.") count += 1 pc.quit()
def main(): screen = pygame.display.set_mode((1024, 768)) pygame.display.init() input_image_name = sys.argv[1] result = scale2x(image.load(input_image_name).convert_alpha()) path, name = p.split(input_image_name) old_name, ext = p.splitext(name) new_name = old_name + "2x" + ext new_path = p.join(path, new_name) image.save(result, new_path)
def snap(cam): #print 'Snap!' #cam.get_image() #cam.get_image() cam.get_image() cam.get_image() img = cam.get_image() file_string = '/var/www/html/toilet.jpeg' pyimg.save(img, file_string)
def resize_height_crop_width(in_path, out_path, resize_height, crop_width, x_offset): image = Image.open(in_path) width, height = image.size ratio = resize_height / height scaled_width = int(width * ratio) image = image.resize((scaled_width, resize_height), Image.ANTIALIAS) image = image.crop((x_offset, 0, x_offset + crop_width, resize_height)) file_root, file_ext = os.path.splitext(in_path) image.save(out_path)
def process_files(self): """ Scale each image in the directory to 640x480 for filename in os.listdir(self.temp_directory) """ for filename in os.listdir(self.temp_directory): im = image.load(self._full_filename(filename)) scaled = scale(im, (700, 500)) image.save(scaled, self._full_filename(filename)) # ScaleZip("img_zip.zip").zip_find_replace()
def shoot(self): if type(self.remaining_shots) == int: idx = self.shots - self.remaining_shots self.remaining_shots = self.remaining_shots - 1 else: idx = self.shots.index(self.remaining_shots[0]) self.remaining_shots.pop(0) # print('taking shot', idx) image_name = os.path.join(self.dir, self.name + str(idx) + ".png") save(self.window, image_name)
def TakeScreenshot(): outputPathTemplate = "Screenshot $index.png" index = 1 outputPath = SubstituteInPath(outputPathTemplate, "index", index) while outputPath.exists(): index += 1 outputPath = SubstituteInPath(outputPathTemplate, "index", index) image.save(GetScreen(), str(outputPath))
def process_files(self): '''Scale each image in the directory to 640x480''' for filename in os.listdir(self.temp_directory): im = image.load(self._full_filename(filename)) scaled = scale( im, eval( input( 'please set size (width, heigt) as in example: (1024,720): ' ).replace(' ', ','))) image.save(scaled, self._full_filename(filename))
def write_screen_image_file(self,filename): """helper method, not directly called in EyeScript scripts in general. Save a screenshot of the display Argument: the filename for the screenshot """ self.drawToBuffer() image = getExperiment().screen.get_framebuffer_as_image() screensDirectory = os.path.dirname(filename) if screensDirectory and not os.path.isdir(screensDirectory): os.makedirs(screensDirectory) image.save(filename)
def gen_test_image(test_func, verbose=False): """Run the test case and save the resulting test_surf.""" test_name = test_func._filename for depth in DEPTHS: if depth not in test_func._supported_depths: continue test_surf = create_surface(depth) test_func(test_surf) imgname = 'results/gen_%d_%s.png' % (depth, test_name) image.save(test_surf, imgname) if verbose: print('completed %s at depth %d. Result saved to %s' % (test_name, depth, imgname))
def take_picture(given_name='test'): camera.init() list_of_cameras = camera.list_cameras() print("Found {} cameras!".format(len(list_of_cameras))) if len(list_of_cameras): my_camera = camera.Camera(list_of_cameras[0]) print("Successfully connected to the camera!") my_camera.start() surface = my_camera.get_image() print(surface) pyimage.save(surface, '{}.bmp'.format(given_name)) my_camera.stop()
def renderHex(name, size = 64, color = Color(128,128,128), smooth = False, fill = False, dashed = False, width = 5): outscribeSize = size*2*math.tan(30*math.pi/180) surf = Surface((int(outscribeSize*2)+width*2,int(outscribeSize*2)+width*2)) surf.fill(Color(0,0,0)) points = [] for deg in range(0,360,60): rad = math.pi/180 * deg points.append((outscribeSize+width+math.cos(rad)*(outscribeSize), outscribeSize+width+math.sin(rad)*(outscribeSize))) if smooth: Draw.aalines(surf, color, True, points) else: Draw.lines(surf, color, True, points) Image.save(surf,name) print ("Hex {} rendered. Inscribed radius: {}".format(name,outscribeSize*math.cos(30*math.pi/180)))
def main(): parser = argparse.ArgumentParser(description='Pack skin textures') parser.add_argument('src') parser.add_argument('dst') parser.add_argument('-u', dest='unpack', const=True, type=bool, default=False, nargs="?") args = parser.parse_args() src_img = image.load(args.src) if args.unpack: dst_img = Surface((10, 50), flags=SRCALPHA) dst_img.blit(src_img, (0, 00), HEAD) dst_img.blit(src_img, (0, 10), STRAIGHT1) dst_img.blit(src_img, (0, 20), STRAIGHT2) dst_img.blit(src_img, (0, 30), TAIL) dst_img.blit(src_img, (0, 40), TURN) else: dst_img = Surface((40, 40), flags=SRCALPHA) single_tile = Surface((10, 10), flags=SRCALPHA) seq = ((HEAD, (0, 0)), (TAIL, (0, 30)), (TURN, (0, 40))) for tile, tile_pos in seq: single_tile.fill((0, 0, 0, 0)) single_tile.blit(src_img, (0, 0), Rect(tile_pos, (10, 10))) for rot, offset in ROT_OFFSET.items(): pos = add_vecs(tile.topleft, offset) dst_img.blit(transform.rotate(single_tile, rot), pos) for tile, tile_pos in ((STRAIGHT1, (0, 10)), (STRAIGHT2, (0, 20))): single_tile.fill((0, 0, 0, 0)) single_tile.blit(src_img, (0, 0), Rect(tile_pos, (10, 10))) dst_img.blit(single_tile, tile) pos = add_vecs(tile.topleft, (0, 10)) dst_img.blit(transform.rotate(single_tile, -90), pos) image.save(dst_img, args.dst)
def process(self, zipprocessor): '''Scale each image in the directory to 640x480''' for folder in zipprocessor.tempfolder: current_folder = folder for file in os.listdir(folder): full_path_file = zipprocessor.path_files_zip(file, current_folder) if full_path_file: try: im = image.load(full_path_file) except Exception as exception: print("File: {}. {}".format(file, exception)) else: im = image.load(full_path_file) scaled = scale(im, (640, 480)) image.save(scaled, full_path_file)
def imagine(fontFile, bold, italic): print fontFile # find a size..... for sqTextSize in goals: f = font.Font(fontFile, sqTextSize / COLS) #f = findGoal(sqTextSize, fontFile) print 'h', f.get_height() #maxHeight = f.size(chars)[1] #maxWidth = 0 #for ch in chars: # maxWidth = max(f.size(ch)[0], maxWidth) #sq = max(maxWidth, maxHeight) info = [] LIST = [alphabet, nums] print LIST for listInd in range(len(LIST)): list = LIST[listInd] x, y = 0, f.get_descent() print y surface = Surface((sqTextSize, sqTextSize)) #draw.line(surface, (255,0,0), (0,0), (sqTextSize, 0)) for ind in range(len(list)): ch = list[ind] s = f.render(ch, 1, (255, 255, 255, 255)) surface.blit(s, (x, y)) info.append((ch, x, y - f.get_descent(), f.size(ch))) x += sqTextSize / COLS if ind % COLS == COLS - 1: y += sqTextSize / COLS x = 0 image.save( surface, fontFileShort + '-bold=' + str(bold) + '-italic=' + str(italic) + '-nro=' + str(listInd) + '-descent=' + str(-f.get_descent()) + '-size=' + str(sqTextSize) + 'x' + str(sqTextSize) + ".bmp")
def save_image(): retangulo = Rect(150, 250, 300, 100) draw.rect(screen, 'gray', retangulo) screen.blit(numeros.render(f"Deseja Salvar", True, BLACK), retangulo) screen.blit(numeros.render(f" Y\\N", True, BLACK), Rect(150, 300, 300, 100)) display.flip() flag = True while flag: for evento in event.get(): if evento.type == py.KEYDOWN: if evento.key == py.K_y: imagem = canvas.image.subsurface(Rect(0, 50, 600, 550)) now = datetime.datetime.now().strftime("%d-%m-%Y %H-%M-%S") image.save(imagem, f"{now}.png") flag = False elif evento.key == py.K_n: flag = False elif evento.type == py.QUIT: flag = False
def test_loadImageTerrain(self): """ If the terrain option is specified as a file containing image-based terrain data, terrain data is loaded from it. """ temp = FilePath(self.mktemp()) temp.makedirs() terrain = temp.child("terrain.png") surface = Surface((2, 1)) surface.set_at((0, 0), (1, 0, 0)) surface.set_at((1, 0), (3, 0, 0)) save(surface, terrain.path) service = gam3plugin.makeService({ "port": 123, "log-directory": None, "terrain": terrain.path}) gam3 = service.getServiceNamed(GAM3_SERVICE_NAME) self.assertEquals( gam3.world.terrain.dict(), {(1, 0, 0): MOUNTAIN, (0, 0, 0): GRASS, (1, 1, 0): MOUNTAIN, (1, 2, 0): GRASS})
def save_display(self, event): if self.is_command(event, "capture-screen"): directory = self.get_configuration().get("screen-captures", "path") try: if not exists(directory): makedirs(directory) name = self.build_name() path = join(directory, name) capture = image.save(self.get_screen(), path) self.print_debug("Saved screen capture to {0}".format(path)) except: self.print_debug("Couldn't save screen capture to {0}, {1}".\ format(directory, exc_info()[1]))
def captureImgAndSend( toAddr ): # capture photos print "capturing photos" pycam.init() cam1 = pycam.Camera(pycam.list_cameras()[0]) cam2 = pycam.Camera(pycam.list_cameras()[1]) cam1.start() #cam1.set_controls(False, False, 100) img1 = cam1.get_image() pyimg.save(img1, "img1.jpg") cam1.stop() cam2.start() img2 = cam2.get_image() pyimg.save(img2, "img2.jpg") cam2.stop() # send to receiver print "sending photos" img1_data = open("img1.jpg", 'rb').read() msg1 = MIMEMultipart() msg1["From"] = EMAIL msg1["To"] = toAddr image1 = MIMEImage(img1_data, name=os.path.basename("img1.jpg")) msg1.attach(image1) img2_data = open("img2.jpg", 'rb').read() msg2 = MIMEMultipart() msg2["From"] = EMAIL msg2["To"] = toAddr image2 = MIMEImage(img2_data, name=os.path.basename("img2.jpg")) msg2.attach(image2) s = smtplib.SMTP_SSL("smtp.gmail.com") s.login(EMAIL, PASSWORD) s.sendmail(EMAIL, [toAddr], msg1.as_string()) s.sendmail(EMAIL, [toAddr], msg2.as_string()) s.quit() # delete the img file os.remove("img1.jpg") os.remove("img2.jpg")
def handle_keys(event, display_surface): global grid_lock global ctrl_down global key_buffer global mouse_mode global drawn_objects if event.key == K_g and event.type == KEYUP: grid_lock = not grid_lock elif event.key == K_LCTRL and event.type == KEYDOWN: ctrl_down = True elif event.key == K_LCTRL and event.type == KEYUP: ctrl_down = False elif event.key == K_z and event.type == KEYDOWN and ctrl_down: if not key_buffer: if len(drawn_objects) is not 0: drawn_objects.pop() key_buffer = True elif event.key == K_z and event.type == KEYUP and ctrl_down: key_buffer = False elif event.key == K_d and event.type == KEYUP: mouse_mode = MouseModes.DOOR elif event.key == K_l and event.type == KEYUP: mouse_mode = MouseModes.STRAIGHT_LINE elif event.key == K_s and event.type == KEYDOWN and ctrl_down: if not key_buffer: cur_time = datetime.now() time_str = "{0}{1}{2}{3}{4}{5}".format(cur_time.year, cur_time.month, cur_time.day, cur_time.hour, cur_time.minute, cur_time.second) if not os.path.exists("screenshots/"): os.makedirs("screenshots/") save(display_surface, "screenshots/screenshot_{}.jpg".format(time_str)) key_buffer = True elif event.key == K_s and event.type == KEYUP and ctrl_down: key_buffer = False
def get_prediction(image): start = time.time() logger.info('About to convert image to bytes') output = io.BytesIO() image.save(output, format='JPEG') output.seek(0) logger.info('About to make sagemaker prediction') response = sm.invoke_endpoint( EndpointName=SAGEMAKER_ENDPOINT, Body=output, ContentType='image/jpeg' ) logger.info('sagemaker took {}'.format(time.time()-start)) result = response['Body'].read() result = json.loads(result) # the result will output the probabilities for all classes # find the class with maximum probability and print the class index logger.info('Probabilities: {}'.format(result)) index = np.argmax(result) return int(index)
def test_conformance(test_name, test_func): """Run the test case and compare the resulting surface to the existing test case.""" test_surf = create_surface() try: test_func(test_surf) except NotImplementedError: # Don't fail completely on not implemented functions pass imgname = 'results/test_%s.png' % test_name image.save(test_surf, imgname) diffname = 'results/diff_%s.png' % test_name orig_name = 'results/gen_%s.png' % test_name orig_surf = image.load(orig_name) # sanity check assert orig_surf.get_size() == test_surf.get_size() differences = False diff_surf = create_surface() # Pixel by pixel comparison. # This is slow, but avoids extra dependancies from pygame.surflock import locked orig_surf = orig_surf.convert(test_surf) with locked(orig_surf._c_surface): with locked(test_surf._c_surface): for x in range(800): for y in range(600): point = (x, y) if orig_surf._get_at(x, y) != test_surf._get_at(x, y): differences = True # Flag as pure white for easier visual inspection diff_surf.set_at(point, (255, 255, 255, 255)) if differences: print("conformance test %s FAILED.\n" " Difference saved to %s" % (test_name, diffname)) image.save(diff_surf, diffname) else: print("conformance test %s passed" % test_name)
def genera_immagini_chunk(self): filename = r"../graphics/results/"+ self.pkl_name.split('/')[-1] if os.path.isfile(filename): print "[WORLD MAKER]: nothing to save..." return z_max = self.maximun dz_height = int((z_max)*(BLOCCOY-2*DY)) height = int(2*DY*(self.dimy-1)+BLOCCOY + dz_height) width = int(BLOCCOX*(self.dimx)) print "[WORLD MAKER]: generation of chunk images\t" background_final = Surface((width, height)) background_final.set_colorkey(TRANSPARENCY) background_final.fill(TRANSPARENCY) #sea_background = Surface((width, height)) #sea_background.set_colorkey(TRANSPARENCY) #sea_background.fill(TRANSPARENCY) for z in range(self.dimz): background = Surface((width, height)) #immagine con i tiles bassi foreground = Surface((width, height)) #immagine con i tiles alti background.fill(TRANSPARENCY) foreground.fill(TRANSPARENCY) background.set_colorkey(TRANSPARENCY) foreground.set_colorkey(TRANSPARENCY) for y in range(self.dimy): for x in range(self.dimx): t_type = self.matrix[z][y][x] tile = self.load_tile(t_type,z,1) tile_up = self.load_tile(t_type,z,0) if tile: xo = width/2 + (x-y-1)*DX yo = (x+y)*DY - z*DZ + dz_height tileRect = tile.get_rect() tileRect.topleft = (int(xo),int(yo)+BLOCCOY/2) background.blit(tile,tileRect) if tile_up: xo = width/2 + (x-y-1)*DX yo = (x+y)*DY - z*DZ + dz_height tileRect = tile_up.get_rect() tileRect.topleft = (int(xo),int(yo)) #if t_type == T_ACQUA: # sea_background.blit(tile_up,tileRect) #else: foreground.blit(tile_up,tileRect) background_final.blit(background,background.get_rect()) background_final.blit(foreground,background.get_rect()) data = Image.tostring(background, "RGBA") surf = Image.fromstring(data, (width, height), 'RGBA', False) Image.save(surf,r"../graphics/results/hill_"+str(z)+"_d.png") data = Image.tostring(foreground, "RGBA") surf = Image.fromstring(data, (width, height), 'RGBA', False) Image.save(surf,r"../graphics/results/hill_"+str(z)+"_u.png") #data = Image.tostring(sea_background, "RGBA") #surf = Image.fromstring(data, (width, height), 'RGBA', False) #Image.save(surf,r"../graphics/results/sea.png") Image.save(background_final,r"../graphics/results/all_hill.png") pickle.dump( self.matrix, open( r"../graphics/results/"+self.pkl_name.split('/')[-1], "wb" ) )
def surf_to_string(surface): image.save(surface, "/tmp/tempimage.png") string = open("/tmp/tempimage.png", "r").read() remove("/tmp/tempimage.png") return string
def export_stack_to_images(self, filename): for num, img in enumerate(self.images_stack): name = filename + str(num) + '.bmp' surface = image.fromstring(img[0], (self.screen.get_width(), self.screen.get_height()), 'RGB') image.save(surface, name)
# Review by MR 26.03.16 # Nice to have such a short script for the beginnging # I would rather go for full words instead of abbreviations for clarity # This is what pylint says: Your code has been rated at -4.00/10 # Could not execute because of missing file. from pygame import image, Rect bg = image.load('bg.xpm') ex = image.load('explo.xpm') bg.blit(ex, Rect((15,15, 0,0)), Rect((0,0,32,32))) image.save(bg, 'merged.png')
def synesthesize(self, image, colors, fontname): """ Purpose: Take an image, replace all the colors with words associated with the colors, saves the image to disk Inputs: Image to be adulterated, colors to be used Outputs: Filename of created image """ textsize = 14 font.init() self.texter = font.SysFont(fontname, textsize) (letWidth, letHeight) = self.texter.size('a') self.iSimp = ImageSimpler() self.preimg = self.iSimp.simplify(image, colors, 25) self.img = self.preimg.resize((self.preimg.size[0], int(self.preimg.size[1] * (letWidth/letHeight)))) pixor = self.img.load() newH = self.img.size[1] * letHeight newW = self.img.size[0] * letWidth self.synpic = Surface((newW, newH)) self.synpic.fill((255,255,255)) #replace pixels with words. One pixel -> one character. Oh hai, linear packing approximation... x = 0 y = 0 def check_fit(space, color): if space <= 25: if self.all_combos[color][space]: word = self.all_combos[color][space].pop() self.all_combos[color][space].appendleft(word) return word else: if space >= 8: return check_fit(floor(space/2), color) + check_fit(ceil(space/2), color) else: return "!" * int(space) else: shift = randint(0,4) return check_fit(floor(space/2) - shift, color) + check_fit(ceil(space/2) + shift, color) def get_space(x,y, color): x1 = x while x < self.img.size[0] and webcolors.rgb_to_name(pixor[x,y]) is color: x += 1 return x - x1 def paint_picture(x, y): while y < self.img.size[1]: pixel = pixor[x,y] color = webcolors.rgb_to_name(pixel) space = get_space(x,y, color) string = check_fit(space, color) drawn = self.texter.render(string, True, pixel) self.synpic.blit(drawn, (x * letWidth, y * letHeight)) x += (len(string)) if x >= self.img.size[0]: y += 1 x = 0 paint_picture(x,y) name = ''.join([choice(string.ascii_letters + string.digits) for n in range(30)]) PyImage.save(self.synpic, 'creations/' + name + '.jpg') return 'creations/' + name + '.jpg'
SIZE = 32 def parse_map(data): return [list(row) for row in data.strip().split('\n')] level = parse_map(""" ####### #.....# #.....# #.*...# #.....# #....x# #######""") def draw_map(data, img, tiles): """Returns an image of a tile-based map""" xs = len(data[0]) * SIZE ys = len(data) * SIZE map_img = Surface((xs, ys)) for y, row in enumerate(data): for x, char in enumerate(row): map_img.blit(img, Rect((x*SIZE, y*SIZE, 0, 0)), tiles[char]) return map_img if __name__ == '__main__': tile_img, tiles = load_tiles() m = draw_map(level, tile_img, tiles) image.save(m, 'map.png')
from pygame import camera from pygame import image camera.init() cam = camera.Camera(camera.list_cameras()[0]) cam.start() img = cam.get_image() image.save(img, "/tmp/photo.bmp") camera.quit()
from load_tiles import load_tiles, get_tile_rect from load_tiles import SIZE from generate_maze import create_maze from util import debug_print def parse_grid(data): """Parses the string representation into a nested list""" return [list(row) for row in data.strip().split("\n")] def draw_grid(data, tile_img, tiles): """Returns an image of a tile-based grid""" debug_print("drawing level", data) xsize = len(data[0]) * SIZE ysize = len(data) * SIZE img = Surface((xsize, ysize)) for y, row in enumerate(data): for x, char in enumerate(row): rect = get_tile_rect(x, y) img.blit(tile_img, rect, tiles[char]) return img if __name__ == '__main__': tile_img, tiles = load_tiles() level = create_maze(12, 7) level = parse_grid(level) maze = draw_grid(level, tile_img, tiles) image.save(maze, 'maze.png')
for x, char in enumerate(row): if char == player_char: return x, y def move(level, direction): """Handles moves on the level""" oldx, oldy = get_player_pos(level) newx, newy = oldx, oldy if direction == 'LEFT': newx = newx - 1 if direction == 'RIGHT': newx = newx + 1 if direction == 'UP': newy = newy - 1 if direction == 'DOWN': newy = newy + 1 if level[newy][newx] == 'x': sys.exit(0) if level[newy][newx] != '#': level[oldy][oldx] = ' ' level[newy][newx] = '*' if __name__ == '__main__': tile_img, tiles = load_tiles() mm = MAP_DATA for direction in ['RIGHT', 'RIGHT', 'UP', 'UP', 'LEFT']: move(mm, direction) img = draw_map(mm, tile_img, tiles) image.save(img, 'moved.png')
clump.blit(i, (x, 0)) x+=i.get_width() if False: # non-working scaling code scale=1 if (NTSC[0]/(1.0*clumpWidth) > NTSC[1]/(1.0*clumpHeight)): scale=NTSC[0]/(1.0*clumpWidth) else: scale=NTSC[1]/(1.0*clumpHeight) if (scale<1): scale=1.0/scale resizedClump=transform.scale(clump, (int(clumpWidth*scale), int(clumpHeight*scale))) mySurf.blit(resizedClump, ((NTSC[0]/2)-(resizedClump.get_height()/2), (NTSC[1]/2)-(resizedClump.get_height()/2))) else: mySurf.blit(clump, ((NTSC[0]/2)-(clump.get_height()/2), (NTSC[1]/2)-(clump.get_height()/2))) image.save(mySurf, r"temp.png") os.system("rm -f temp.txt") f=open("temp.txt", "w") f.write(token) f.close() os.system("text2wave temp.txt -o temp.wav") s=mixer.Sound("temp.wav") seconds=int(s.get_length()+0.5) if(seconds<1): seconds=1 cmd="mencoder -oac copy -ovc lavc -o temp.avi -mf fps=1 "+("mf://temp.png "*seconds) os.system(cmd) os.system("mencoder -oac copy -ovc lavc -audiofile temp.wav -o "+str(counter)+".avi temp.avi") os.system("rm -f temp.{wav,txt,png,avi}") films[token]=str(counter)+".avi" counter+=1 clips.append(films[token])
bwimg = cv.LoadImage(source, 0) img = cv.LoadImage(source) # Create pygame surfaces for bitblitting pygameimg = img.tostring() with_laughingman = image.fromstring(pygameimg, (WIDTH,HEIGHT), "RGB") # Detect faces and bitblit the laughingman faces = cv.HaarDetectObjects(bwimg, hc, cv.CreateMemStorage()) for (fx,fy,fw,fh),n in faces: (x,y,w,h) = (fx-10, fy-10, fw+20, fh+20) laughingman_scaled = scale(laughingman, (w,h)) with_laughingman.blit(laughingman_scaled, (x,y)) # Save the image image.save(with_laughingman, source) tweet = "Total people found in view ("+str(index+1)+"): "+str(len(faces)) print tweet # Check if the room is dark hist = cv.CreateHist([32], cv.CV_HIST_ARRAY, [[0, 255]], 1) cv.CalcHist([bwimg], hist, 0, None) hist_img = cv.CreateImage((32*10,255), 8, 3) (_,max_value,_,_) = cv.GetMinMaxHistValue(hist) (sizex, sizey) = cv.GetSize(bwimg)
def process_files(self): for filename in os.listdir(self.temp_directory): im = image.load(self._full_filename(filename)) scaled = scale(im, (640, 480)) image.save(scaled, self._full_filename(filename))
def process_files(self): for filename in os.listdir(self.processor.temp_directory): img = image.load(self.processor._file_path(filename)) scaled_img = scale(img, (800, 600)) image.save(scaled_img, self.processor._file_path(filename))
def process_files(self): """Scale each image in the directory to 640x480""" for filename in os.listdir(self.temp_directory): im = image.load(self._full_filename(filename)) scaled = scale(im, (640, 480)) image.save(scaled, self._full_filename(filename))
('*', 0, 3), # player ('x', 1, 1), # exit ] SIZE = 32 def get_tile_rect(x, y): """Converts tile indices to a pygame.Rect""" return Rect(x*SIZE, y*SIZE, (x+1)*SIZE, (y+1)*SIZE) def load_tiles(): """Returns a tuple of (image, tile_dict)""" tile_image = image.load('tiles.xpm') tiles = {} for symbol, x, y in TILE_POSITIONS: tiles[symbol] = get_tile_rect(x, y) return tile_image, tiles if __name__ == '__main__': tile_img, tiles = load_tiles() m = Surface((96, 32)) m.blit(tile_img, get_tile_rect(0, 0), tiles['#']) m.blit(tile_img, get_tile_rect(1, 0), tiles[' ']) m.blit(tile_img, get_tile_rect(2, 0), tiles['*']) image.save(m, 'tile_combo.png')
def process(self, zipprocessor): "Scale each image in the directory to 640x480" for filename in os.listdir(zipprocessor.temp_directory): im = image.load(zipprocessor._full_filename(filename)) scaled = scale(im, (640, 480)) image.save(scaled, zipprocessor._full_filename(filename))