def imgarray_from_file(filename, sx, sy): imgsurface = pygame.image.load(filename) xdim, ydim = imgsurface.get_size() imgsurface = pygame.transform.scale(imgsurface, (int(xdim * sx), int(ydim * sy))) array = surfarray.array2d(imgsurface) return array
def old_cell_dict_from_file(filename, sx, sy): try: imgsurface = pygame.image.load(filename) xdim, ydim = imgsurface.get_size() imgsurface = pygame.transform.scale(imgsurface, (int(xdim * sx), int(ydim * sy))) imgarray = surfarray.array2d(imgsurface) cd = build_celldict(imgarray) except pygame.error, e: print "Couldn't load %s" % filename print e sys.exit(2)
def main(): sess = Mnist.train() screen = pygame.display.set_mode((28, 28)) #THIS IS A SURFACE OBJECT draw_on = False last_pos = (0, 0) color = (255, 128, 0) radius = 1 def roundline(srf, color, start, end, radius=1): dx = end[0] - start[0] dy = end[1] - start[1] distance = max(abs(dx), abs(dy)) for i in range(distance): x = int(start[0] + float(i) / distance * dx) y = int(start[1] + float(i) / distance * dy) pygame.draw.circle(srf, color, (x, y), radius) try: while True: e = pygame.event.wait() if e.type == pygame.QUIT: raise StopIteration if e.type == pygame.MOUSEBUTTONDOWN: color = (255, 255, 255) pygame.draw.circle(screen, color, e.pos, radius) draw_on = True if e.type == pygame.MOUSEBUTTONUP: draw_on = False if e.type == pygame.MOUSEMOTION: if draw_on: pygame.draw.circle(screen, color, e.pos, radius) roundline(screen, color, e.pos, last_pos, radius) last_pos = e.pos pygame.display.flip() # pygame.transform.scale(screen,(28,28)) new_array = [] arr2d = surfarray.array2d(screen) for arr in arr2d: for integer in arr: #if(integer == -256): # new_array.append(256) #else: new_array.append(integer) print(Mnist.Mnist(new_array, sess)) except StopIteration: pass pygame.quit()
def init(datapoints, i): global rpanel, myra frames = [] pygame.init() #for dp in datapoints: # f = Frame(dp[1], 0, 0) # print "Image: %dx%d" % (f.xdim, f.ydim) # f.secondary_surface(dp[0]) # f.scale_and_init(gsx, gsx) frame1_file = datapoints[i][1] frame1_orig = datapoints[i][0] frame2_file = datapoints[i + 1][1] frame2_orig = datapoints[i + 1][0] print "Loading images and making calculations" frame1 = Frame(frame1_file, 0, 0) frame2 = Frame(frame2_file, 0, 0) print "Image %d: %dx%d" % (1, frame1.xdim, frame1.ydim) print "Image %d: %dx%d" % (2, frame2.xdim, frame2.ydim) frame1.secondary_surface(frame1_orig) frame2.secondary_surface(frame2_orig) sx, sy = calculate_scaling(frame1.xdim, frame1.ydim, frame2.xdim, frame2.ydim) frame1.scale_and_init(sx, sy) frame2.scale_and_init(sx, sy) frame2.y = frame1.ydim bpx = max(frame1.xdim, frame2.xdim) bpanel = Panel(0, frame1.ydim + frame2.ydim, bpx, frame2.ydim) print "Initialising screen...", window = pygame.display.set_mode((frame1.xdim + psize, frame1.ydim + frame2.ydim + bpanel.ydim)) pygame.display.set_caption(caption_string) screen = pygame.display.get_surface() print "done" frame1.flip_surface() frame2.flip_surface() #frame1.draw(screen) #frame2.draw(screen) rpanel = pygame.Surface([psize, frame1.ydim]) rpanel.set_colorkey((0, 0, 0)) myra = surfarray.array2d(rpanel) return screen, frame1, frame2, bpanel
def show_stuff(self, cid): print "Displaying data for cell %d" % cid cparray = surfarray.array2d(self.limage) ox, oy = get_centroid(self.cd1[cid]) ex, ey = 100, 100 for x in range(-50,50): for y in range(-50, 50): try: self.extra_panel.array[x + ex, y + ey] = cparray[x + ox, y + oy] except IndexError, e: print "IndexError in show_stuff"
def get_current_state(self): ''' if self.snake_x_pos >= self.screen_size or self.snake_y_pos >= self.screen_size or self.snake_x_pos < 0 or self.snake_y_pos < 0: screen_tensor = torch.zeros(20,20) if (self.snake_x_pos,self.snake_y_pos) in self.coordinates_list[:-1]: screen_tensor = torch.zeros(20,20) ''' surface_array = surfarray.array2d(self.screen) screen_data = np.delete( surface_array, [i for i in range(self.screen_size) if i % 10 != 0], 0) screen_data = np.delete( screen_data, [i for i in range(self.screen_size) if i % 10 != 0], 1) screen_data = np.divide(screen_data, 2**24) screen_tensor = torch.tensor(screen_data, dtype=torch.float32) return screen_tensor
def __init__(self, sheet, rect): subsurface = sheet.subsurface(rect) data = surfarray.array2d(subsurface) self.shifts = subsurface.get_shifts() self.elevation = self.isolate_and_divide(data, self.shifts[0]).astype( dtype=np.int64, casting="unsafe", copy=False) self.temperature = self.isolate_and_divide( data, self.shifts[1]).astype(dtype=np.int64, casting="unsafe", copy=False) self.alpha = np.bitwise_and(data, 0xff << self.shifts[3]).astype( dtype=np.uint32, casting="unsafe", copy=False) self.scratch = data.copy() self.altered_temp = self.temperature.astype(dtype=np.int64, casting="unsafe") self.altered_elevation = self.elevation.astype(dtype=np.int64, casting="unsafe")
def __init__(self, master=None, surface=None, **surf_kwargs): self.children = [] if not surface: self._build_surface(**surf_kwargs) else: surf_rect = surface.get_rect() Surface.__init__(surf_rect.size, masks=pygame.mask.from_surface(surface)) array = surfarray.array2d(surface) surfarray.blit_array(self, array) if not master: self.master = pygame.display.get_surface() else: self.master = master Events.__init__(self)
def tryToReadImg(f): try: import Image return asarray(Image.open(f)) except ImportError: try: from pygame.image import load from pygame.surfarray import array3d,array2d if (f[-3:].upper() in ['PPM','PGM']): i = array2d(load(f)) else: i = array3d(load(f)) if (f[-3:].upper() in ['PPM']): return i > (i.max()-i.min()) return i except ImportError: print("Can't proceed: Pil or PyGame not found") exit(2)
def __im_to_numpy_arr__( self, img ): matpygame = surfarray.array2d( self.__cvimage_to_pygame__( img ) ) return numpy.asarray( matpygame )
def main(arraytype=None): """show various surfarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed. """ if arraytype is None: if 'numpy' in surfarray.get_arraytypes(): surfarray.use_arraytype('numpy') elif 'numeric' in surfarray.get_arraytype(): surfarray.use_arraytype('numeric') else: raise ImportError('No array package is installed') else: surfarray.use_arraytype(arraytype) if surfarray.get_arraytype() == 'numpy': import numpy as N from numpy import int32 else: import Numeric as N from Numeric import Int32 as int32 pygame.init() print ('Using %s' % surfarray.get_arraytype().capitalize()) print ('Press the mouse button to advance image.') print ('Press the "s" key to save the current image.') def surfdemo_show(array_img, name): "displays a surface, waits for user to continue" screen = pygame.display.set_mode(array_img.shape[:2], 0, 32) surfarray.blit_array(screen, array_img) pygame.display.flip() pygame.display.set_caption(name) while 1: e = pygame.event.wait() if e.type == MOUSEBUTTONDOWN: break elif e.type == KEYDOWN and e.key == K_s: #pygame.image.save(screen, name+'.bmp') #s = pygame.Surface(screen.get_size(), 0, 32) #s = s.convert_alpha() #s.fill((0,0,0,255)) #s.blit(screen, (0,0)) #s.fill((222,0,0,50), (0,0,40,40)) #pygame.image.save_extended(s, name+'.png') #pygame.image.save(s, name+'.png') #pygame.image.save(screen, name+'_screen.png') #pygame.image.save(s, name+'.tga') pygame.image.save(screen, name+'.png') elif e.type == QUIT: raise SystemExit() #allblack allblack = N.zeros((128, 128), int32) surfdemo_show(allblack, 'allblack') #striped #the element type is required for N.zeros in NumPy else #an array of float is returned. striped = N.zeros((128, 128, 3), int32) striped[:] = (255, 0, 0) striped[:,::3] = (0, 255, 255) surfdemo_show(striped, 'striped') #imgarray imagename = os.path.join(main_dir, 'data', 'arraydemo.bmp') imgsurface = pygame.image.load(imagename) imgarray = surfarray.array2d(imgsurface) surfdemo_show(imgarray, 'imgarray') #flipped flipped = imgarray[:,::-1] surfdemo_show(flipped, 'flipped') #scaledown scaledown = imgarray[::2,::2] surfdemo_show(scaledown, 'scaledown') #scaleup #the element type is required for N.zeros in NumPy else #an #array of floats is returned. size = N.array(imgarray.shape)*2 scaleup = N.zeros(size, int32) scaleup[::2,::2] = imgarray scaleup[1::2,::2] = imgarray scaleup[:,1::2] = scaleup[:,::2] surfdemo_show(scaleup, 'scaleup') #redimg rgbarray = surfarray.array3d(imgsurface) redimg = N.array(rgbarray) redimg[:,:,1:] = 0 surfdemo_show(redimg, 'redimg') #soften soften = N.array(rgbarray)*1 soften[1:,:] += rgbarray[:-1,:]*8 soften[:-1,:] += rgbarray[1:,:]*8 soften[:,1:] += rgbarray[:,:-1]*8 soften[:,:-1] += rgbarray[:,1:]*8 soften /= 33 surfdemo_show(soften, 'soften') #crossfade (50%) src = N.array(rgbarray) dest = N.zeros(rgbarray.shape) dest[:] = 20, 50, 100 diff = (dest - src) * 0.50 if surfarray.get_arraytype() == 'numpy': xfade = src + diff.astype(N.uint) else: xfade = src + diff.astype(N.Int) surfdemo_show(xfade, 'xfade') #alldone pygame.quit()
def __init__(self, sheet, rect): assert rect.width == self.SHEET_SIZE assert rect.height == self.SHEET_SIZE get_rid_of_alpha = ~(0xff << sheet.get_shifts()[3]) self.colors = np.bitwise_and(surfarray.array2d(sheet.subsurface(rect)), get_rid_of_alpha)
def array2d(self): return surfarray.array2d(self)
WHITE = (255, 255, 255) BLACK = (0, 0, 0) EXA_WHITE = 0xFFFFFF EXA_BLACK = 0x000000 MAX_ATTEMPTS = 100 width = 800 height = 600 size = (width, height) center = width // 2 + 1j * (height // 2) screen = pygame.display.set_mode(size) clock = pygame.time.Clock() surface = surfarray.array2d(screen) for a, row in enumerate(surface): for b, item in enumerate(row): attempts = f(a + b * 1j) if attempts > MAX_ATTEMPTS // 2: surface[a][b] = EXA_BLACK else: surface[a][b] = EXA_WHITE pygame.surfarray.blit_array(screen, surface) pygame.display.flip() done = False while not done:
def main(arraytype=None): """show various surfarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed. """ if arraytype is None: if 'numpy' in surfarray.get_arraytypes(): surfarray.use_arraytype('numpy') elif 'numeric' in surfarray.get_arraytype(): surfarray.use_arraytype('numeric') else: raise ImportError('No array package is installed') else: surfarray.use_arraytype(arraytype) if surfarray.get_arraytype() == 'numpy': import numpy as N from numpy import int32, uint8, uint else: import Numeric as N from Numeric import Int32 as int32, UInt8 as uint8, UInt as uint pygame.init() print ('Using %s' % surfarray.get_arraytype().capitalize()) print ('Press the mouse button to advance image.') print ('Press the "s" key to save the current image.') def surfdemo_show(array_img, name): "displays a surface, waits for user to continue" screen = pygame.display.set_mode(array_img.shape[:2], 0, 32) surfarray.blit_array(screen, array_img) pygame.display.flip() pygame.display.set_caption(name) while 1: e = pygame.event.wait() if e.type == MOUSEBUTTONDOWN: break elif e.type == KEYDOWN and e.key == K_s: #pygame.image.save(screen, name+'.bmp') #s = pygame.Surface(screen.get_size(), 0, 32) #s = s.convert_alpha() #s.fill((0,0,0,255)) #s.blit(screen, (0,0)) #s.fill((222,0,0,50), (0,0,40,40)) #pygame.image.save_extended(s, name+'.png') #pygame.image.save(s, name+'.png') #pygame.image.save(screen, name+'_screen.png') #pygame.image.save(s, name+'.tga') pygame.image.save(screen, name+'.png') elif e.type == QUIT: raise SystemExit() #allblack allblack = N.zeros((128, 128), int32) surfdemo_show(allblack, 'allblack') #striped #the element type is required for N.zeros in NumPy else #an array of float is returned. striped = N.zeros((128, 128, 3), int32) striped[:] = (255, 0, 0) striped[:,::3] = (0, 255, 255) surfdemo_show(striped, 'striped') #imgarray imagename = os.path.join(main_dir, 'data', 'arraydemo.bmp') imgsurface = pygame.image.load(imagename) imgarray = surfarray.array2d(imgsurface) surfdemo_show(imgarray, 'imgarray') #flipped flipped = imgarray[:,::-1] surfdemo_show(flipped, 'flipped') #scaledown scaledown = imgarray[::2,::2] surfdemo_show(scaledown, 'scaledown') #scaleup #the element type is required for N.zeros in NumPy else #an #array of floats is returned. size = N.array(imgarray.shape)*2 scaleup = N.zeros(size, int32) scaleup[::2,::2] = imgarray scaleup[1::2,::2] = imgarray scaleup[:,1::2] = scaleup[:,::2] surfdemo_show(scaleup, 'scaleup') #redimg rgbarray = surfarray.array3d(imgsurface) redimg = N.array(rgbarray) redimg[:,:,1:] = 0 surfdemo_show(redimg, 'redimg') #soften #having factor as an array forces integer upgrade during multiplication #of rgbarray, even for numpy. factor = N.array((8,), int32) soften = N.array(rgbarray, int32) soften[1:,:] += rgbarray[:-1,:] * factor soften[:-1,:] += rgbarray[1:,:] * factor soften[:,1:] += rgbarray[:,:-1] * factor soften[:,:-1] += rgbarray[:,1:] * factor soften //= 33 surfdemo_show(soften, 'soften') #crossfade (50%) src = N.array(rgbarray) dest = N.zeros(rgbarray.shape) dest[:] = 20, 50, 100 diff = (dest - src) * 0.50 xfade = src + diff.astype(uint) surfdemo_show(xfade, 'xfade') #alldone pygame.quit()
def draw(): num = surfarray.array2d(screen) print(num.shape)
def cell_dict_from_file(image_file, sx, sy): """Take a numpy array containing values that represent segmentation ID, and return a dictionary keyed by the ID containing a list of points in absolute coordinates which comprise that cell""" try: imgsurface = pygame.image.load(image_file) except pygame.error, e: print "Couldn't load %s" % filename print e sys.exit(2) xdim, ydim = imgsurface.get_size() imgsurface = pygame.transform.scale(imgsurface, (int(xdim * sx), int(ydim * sy))) imgarray = surfarray.array2d(imgsurface) cmap = {} cd = {} for x in range(0, xdim): for y in range(0, ydim): val = imgarray[x, y] if val in cmap: c = cmap[val] else: r, g, b, a = imgsurface.unmap_rgb(val) c = b + 255 * g + 255 * 255 * r cmap[val] = c if c not in cd: cd[c] = [(x, y)]
def __init__(self, xdim, ydim): self.xdim = xdim self.ydim = ydim self.surface = pygame.Surface([xdim, ydim]) self.surface.set_colorkey((0, 0, 0)) self.array = surfarray.array2d(self.surface)
font = pygame.font.SysFont("monospace", 48) equ_label = None ans_label = None while True: for event in pygame.event.get(): if event.type == QUIT: exit() elif event.type == pygame.MOUSEMOTION: end_position = pygame.mouse.get_pos() if pygame.mouse.get_pressed() == left_mouse_button: pygame.draw.line(background, draw_color, start_position, end_position, draw_thickness) start_position = end_position elif event.type == pygame.MOUSEBUTTONUP: pixels = np.asarray(array2d(background)) pixels = np.divide(pixels, 16777215) pixels = pixels.transpose() chars = preprocess.extract_chars(pixels) chars = chars.reshape(chars.shape[0], dataset.IMG_ROWS, dataset.IMG_COLS, 1) pred = network.model.predict_classes(chars, verbose=0) pred_str = str() for p in pred: pred_str += dataset.CLASS_INDEX[p] pred_str = pred_str.replace('star', '*').replace('slash', '/') equ_label = font.render('equ = ' + pred_str, 1, (0, 255, 0)) if (pred_str[-1].isdigit() or pred_str[-1] is ')' ) and pred_str.count('(') is pred_str.count(')'): ans_label = font.render('ans = ' + str(eval(pred_str)), 1, (0, 255, 0))
#!/usr/local/bin/python # coding: utf-8 import pygame,urllib.request,pygame.surfarray as surfarray,io pygame.init() screen = pygame.display.set_mode((800,600)) mario = pygame.image.load('mario.jpg') marioArray = surfarray.array2d(mario) marioPosY = 0 marioDirRight = True loop = True fps = 60 clock = pygame.time.Clock() posA = 0 increasePos = True font1 = pygame.font.SysFont("arial", 16) customFont = pygame.font.Font("/home/pi/Desktop/labdays/pygame/8bitfont.otf", 44) httptext = urllib.request.urlopen("http://192.168.8.63/hello").read() myStr = str(httptext, encoding ='utf-8') def surfdemo_show(array_img, name): screen = pygame.display.set_mode(array_img.shape[:2], 0, 32) surfarray.blit_array(screen, array_img) pygame.display.flip() def LoadImageFromUrl(url):