def update(self, player): if self.highlight_progress > 0 and self.highlighting: self.red_color += self.red_speed self.red_color = min(255.0, self.red_color) self.green_color += self.green_speed self.green_color = min(255.0, self.green_color) self.blue_color += self.blue_speed self.blue_color = min(255.0, self.blue_color) text_surface = self.font.render(self.text, True, (self.red_color, self.green_color, self.blue_color, 255), (210, 224, 224, 0)) self.text_data = image.tostring(text_surface, "RGBA", True) self.highlight_progress -= 1 elif self.highlight_progress > 0 and not self.highlighting: self.red_color -= self.red_speed self.red_color = max(0.0, self.red_color) self.green_color -= self.green_speed self.green_color = max(0.0, self.green_color) self.blue_color -= self.blue_speed self.blue_color = max(0.0, self.blue_color) text_surface = self.font.render(self.text, True, (self.red_color, self.green_color, self.blue_color, 255), (210, 224, 224, 0)) self.text_data = image.tostring(text_surface, "RGBA", True) self.highlight_progress -= 1 player_coords = player.get_grid_coordinates() tile_coord = self.get_grid_coordinates() target = [tile_coord[0], tile_coord[1], tile_coord[2] + 1] if target != player_coords and self.highlighting: self.dehighlight()
def __init__(self, filename, format, flipped=True): # print "loading texture: %s" % filename texture_img = image.load(filename) if format == GL_ALPHA: # write as RGBA, then take character index 3 (A) from every quartet pixels = image.tostring(texture_img, 'RGBA', flipped)[3::4] elif format == GL_RGB: pixels = image.tostring(texture_img, 'RGB', flipped) elif format == GL_RGBA: pixels = image.tostring(texture_img, 'RGBA', flipped) elif format == GL_LUMINANCE: # write as RGB, then take character index 1 (G) from every triplet pixels = image.tostring(texture_img, 'RGB', flipped)[1::3] elif format == GL_LUMINANCE_ALPHA: # write as RGBA, then take every second character (G and A) pixels = image.tostring(texture_img, 'RGBA', flipped)[1::2] self.texture_id = glGenTextures(1) # print "texture ID: %s" % self.texture_id glBindTexture(GL_TEXTURE_2D, self.texture_id) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D( GL_TEXTURE_2D, 0, format, texture_img.get_width(), texture_img.get_height(), 0, format, GL_UNSIGNED_BYTE, pixels ) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
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 gl_draw_all(self, root, offset): if not self.visible: return from OpenGL import GL, GLU rect = self.rect.move(offset) if self.is_gl_container: self.gl_draw_self(root, offset) suboffset = rect.topleft for subwidget in self.subwidgets: subwidget.gl_draw_all(root, suboffset) else: try: surface = Surface(self.size, SRCALPHA) except Exception, e: #size error? return self.draw_all(surface) data = image.tostring(surface, 'RGBA', 1) w, h = root.size GL.glViewport(0, 0, w, h) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GLU.gluOrtho2D(0, w, 0, h) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glRasterPos2i(max(rect.left, 0), max(h - rect.bottom, 0)) GL.glPushAttrib(GL.GL_COLOR_BUFFER_BIT) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDrawPixels(self.width, self.height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, fromstring(data, dtype='uint8')) GL.glPopAttrib() GL.glFlush()
def gl_draw_all(self, root, offset): from OpenGL import GL, GLU rect = self.rect.move(offset) if self.is_gl_container: self.gl_draw_self(root, offset) suboffset = rect.topleft for subwidget in self.subwidgets: subwidget.gl_draw_all(root, suboffset) else: surface = Surface(self.size, SRCALPHA) self.draw_all(surface) data = image.tostring(surface, 'RGBA', 1) w, h = root.size GL.glViewport(0, 0, w, h) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GLU.gluOrtho2D(0, w, 0, h) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glRasterPos2i(rect.left, h - rect.bottom) GL.glPushAttrib(GL.GL_COLOR_BUFFER_BIT) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDrawPixels(self.width, self.height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, data) GL.glPopAttrib()
def check_images(i1, i2): i1 = im.tostring(i1, "RGB") i1 = Image.frombytes("RGB", (600, 480), i1) i2 = im.tostring(i2, "RGB") i2 = Image.frombytes("RGB", (600, 480), i2) pairs = izip(i1.getdata(), i2.getdata()) if len(i1.getbands()) == 1: dif = sum(abs(p1 - p2) for p1, p2 in pairs) else: dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2)) ncomponents = i1.size[0] * i1.size[1] * 3 return (dif / 255.0 * 100) / ncomponents
def __init__(self, row, column, level, side_length, text, action, parameter): self.side_length = side_length self.tile = Particle(row * side_length, column * side_length, level * side_length) self.tile.add_property("GLLIST", create_cube()) self.tile.add_property("SIZE", [side_length / 2, side_length / 2, side_length / 2]) self.tile.add_property("MATERIAL", material_active_finish_tile) with open("config.json") as json_config: config = json.load(json_config) font_location = config["settings"]["font"] self.highlight_frames = config["constants"]["move_frames"] self.highlight_progress = 0 self.highlighting = None self.red_speed = 42.0 / self.highlight_frames self.green_speed = 200.0 / self.highlight_frames self.blue_speed = 229.0 / self.highlight_frames self.text = text self.action = action self.param = parameter self.font = fonts.Font(font_location, 40) self.red_color = 0.0 self.green_color = 0.0 self.blue_color = 0.0 text_surface = self.font.render(self.text, True, (self.red_color, self.green_color, self.blue_color, 255), (210, 224, 224, 0)) self.text_width = text_surface.get_width() self.text_height = text_surface.get_height() self.text_data = image.tostring(text_surface, "RGBA", True) self.position = (row * side_length - self.text_width, column * side_length - self.text_height, level * side_length + 500)
def __surface_to_string__( self, surface ): ''' Converti une Surface pygame en String @param surface: surface pygame @type surface: pygame.Surface ''' return pymage.tostring( surface, 'RGB' )
def gl_draw_all(self, root, offset): if not self.visible: return from OpenGL import GL, GLU rect = self.rect.move(offset) if self.is_gl_container: self.gl_draw_self(root, offset) suboffset = rect.topleft for subwidget in self.subwidgets: subwidget.gl_draw_all(root, suboffset) else: try: surface = Surface(self.size, SRCALPHA) except Exception: #size error? return self.draw_all(surface) data = image.tostring(surface, 'RGBA', 1) w, h = root.size GL.glViewport(0, 0, w, h) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GLU.gluOrtho2D(0, w, 0, h) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glRasterPos2i(max(rect.left, 0), max(h - rect.bottom, 0)) GL.glPushAttrib(GL.GL_COLOR_BUFFER_BIT) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDrawPixels(self.width, self.height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, fromstring(data, dtype='uint8')) GL.glPopAttrib() GL.glFlush()
def __init__(self, text='iOS android osx windows chrome', font_name=None, max_words=150, prefer_horizontal=0.8, color='pop', custom_colors=[], background_color='', stopwords=[], tilde=True, man_count=False, sp_char=False, debug=False): self.debug = debug self.text = text self.font_path = get_font(font_name) self.max_words = max_words self.prefer_horizontal = prefer_horizontal self.color = color self.custom_colors = custom_colors self.sf = Surface((CANVAS_WIDTH, CANVAS_HEIGHT), SRCALPHA, 32) if background_color == 'white': self.sf.fill((255, 255, 255)) elif background_color == 'black': self.sf.fill((0, 0, 0)) self.stopwords = STOPWORDS.union(set(stopwords)) if tilde: self.tilde = '~' else: self.tilde = '' if sp_char: self.sp_char = '\S' else: self.sp_char = '\w' self.man_count = man_count self.words = [] self.ratio = 1 self._set_font_size() self._create_image() self.image_string = image.tostring(self.sf, 'RGBA')
def load_from_file(self, tex_name, file_name, has_alpha, flip_vertically, mipmap, wrap, filtering): # type: (str, str, bool, bool, MipMap, Wrap, Filter) -> None data = image.load(file_name) # type: Surface width, height = data.get_size() texture = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, texture) # Set the texture wrapping parameters wrap_value = { Wrap.repeat: GL.GL_REPEAT, Wrap.mirror_repeat: GL.GL_MIRRORED_REPEAT, Wrap.clamp_to_edge: GL.GL_CLAMP_TO_EDGE, Wrap.clamp_to_border: GL.GL_CLAMP_TO_BORDER }.get(wrap, GL.GL_REPEAT) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, wrap_value) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrap_value) # Set the texture magnification filtering filter_value = { Filter.linear: GL.GL_LINEAR, Filter.nearest: GL.GL_NEAREST }.get(filtering, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, filter_value) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, filter_value) if has_alpha: gl_channels = GL.GL_RGBA channels = 'RGBA' data = data.convert_alpha() else: gl_channels = GL.GL_RGB channels = 'RGB' data = image.tostring(data, channels, flip_vertically) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, gl_channels, width, height, 0, gl_channels, GL.GL_UNSIGNED_BYTE, data) # Apply the texture mipmaps if mipmap is not MipMap.none: mipmap_value = { MipMap.nearest_nearest: GL.GL_NEAREST_MIPMAP_NEAREST, MipMap.nearest_linear: GL.GL_NEAREST_MIPMAP_LINEAR, MipMap.linear_nearest: GL.GL_LINEAR_MIPMAP_NEAREST, MipMap.linear_linear: GL.GL_LINEAR_MIPMAP_LINEAR }.get(mipmap, GL.GL_LINEAR_MIPMAP_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, mipmap_value) GL.glGenerateMipmap(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) self._descriptors[tex_name] = TexDescriptor(texture, width, height, flip_vertically, mipmap, wrap, filtering)
def captureBackImage(self, filename): """ Capture an image using the default resolution """ self.cam.start() img_surface = self.cam.get_image() pil_string_image = PyGameImage.tostring(img_surface, "RGBA",False) img = Image.fromstring("RGBA",self.resolution,pil_string_image) img.save(filename) self.cam.stop()
def check_images(i1,i2): i1 = im.tostring(i1,"RGB") i1 = Image.frombytes("RGB",(600,480),i1) i2 = im.tostring(i2,"RGB") i2 = Image.frombytes("RGB",(600,480),i2) pairs = izip(i1.getdata(), i2.getdata()) if len(i1.getbands()) == 1: dif = sum(abs(p1 - p2) for p1,p2 in pairs) else: dif = sum(abs(c1 - c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2)) ncomponents = i1.size[0] * i1.size[1] * 3 return (dif / 255.0 * 100) / ncomponents
def gl_draw(self, root, offset): pages = self.pages if len(pages) > 1: tlcorner = (offset[0] + self.bottomleft[0], offset[1] + self.bottomleft[1]) pageTabContents = [] current_page = self.current_page n = len(pages) b = self.tab_border_width s = self.tab_spacing h = self.tab_height m = self.tab_margin tabWidth = (self.size[0] - (s * n) - (2 * m)) / n width = self.width - 2 * m + s - b x0 = m + tlcorner[0] font = self.tab_font fg = self.tab_fg_color surface = Surface(self.size, SRCALPHA) glEnable(GL_BLEND) for i, page in enumerate(pages): x1 = x0 + tabWidth selected = page is current_page if selected: glColor(1.0, 1.0, 1.0, 0.5) else: glColor(0.5, 0.5, 0.5, 0.5) glRectf(x0, tlcorner[1] - (m + b), x1, tlcorner[1] - (h)) buf = font.render(self.pages[i].tab_title, True, self.fg_color or fg) r = buf.get_rect() offs = ((tabWidth - r.size[0]) / 2) + m + ((s + tabWidth) * i) surface.blit(buf, (offs, m)) x0 = x1 + s data = image.tostring(surface, 'RGBA', 1) rect = self.rect.move(offset) w, h = root.size glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, w, 0, h) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRasterPos2i(rect.left, h - rect.bottom) glPushAttrib(GL_COLOR_BUFFER_BIT) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDrawPixels(self.width, self.height, GL_RGBA, GL_UNSIGNED_BYTE, fromstring(data, dtype='uint8')) glPopAttrib() glFlush() glDisable(GL_BLEND)
def merge_images(current_image: image, second_img_path: str): strFormat = "RGBA" raw_str = image.tostring(current_image, strFormat, False) im1 = Image.frombytes(strFormat, current_image.get_size(), raw_str) print(second_img_path) im2 = Image.open(second_img_path) new_image = Image.alpha_composite(im1, im2) return image.fromstring(new_image.tobytes(), new_image.size, new_image.mode)
def setFile(self, file): """ loads pixel data from file. """ self.file = file surface = image.load("../textures/" + file) self.textureData = image.tostring(surface, "RGBA", 1) self.width, self.height = surface.get_size() del surface
def draw_image(self, image, pos=None, scale=None): """Draws an image on the screen arguments image -- a full path to an image file, or a pygame Surface (if image is neither of these, this function will attempt to treat the image as a PIL Image) keyword arguments pos -- image center position, an (x,y) position tuple or None for a central position (default = None) scale -- scale factor for the image or None for no scaling (default = None) returns Nothing -- loads and draws an image surface on (PyGame) or adds SimpleImageStim to (PsychoPy) the self.screen property """ if pos == None: pos = (self.dispsize[0]/2, self.dispsize[1]/2) # check if image is a path name if type(image) in [str, unicode]: # check if the image file exists if os.path.isfile(image): # load image from file try: img = pygame.image.load(image) except: raise Exception("Error in libscreen.PyGameScreen.draw_image: could not load image file %s" % image) else: raise Exception("Error in libscreen.PyGameScreen.draw_image: path %s is not a file!" % image) # check if image is a PyGame Surface elif type(image) == pygame.Surface: # since image is already a PyGame Surface, we needn't do anything with it img = image # finally, try if the image is supported by PIL else: try: # PIL Image to PyGame Surface img = pygame.image.fromstring(image.tostring(), (image.size[0],image.size[1]), 'RGB', False) except: raise Exception("Error in libscreen.PyGameScreen.draw_image: image format not recognized!") if scale != None: img = pygame.transform.scale(img, (int(img.get_width()*scale), int(img.get_height()*scale))) imgpos = (int(pos[0] - img.get_width()/2), int(pos[1] - img.get_height()/2)) self.screen.blit(img, imgpos)
def __init__(self, filename, do_bind=True): # s = surface s = image.load(filename) self.true_w, self.true_h = s.get_size() self.tostring = image.tostring(s, "RGBA", True) self.resize_for_texture(self.tostring) glEnable(GL_TEXTURE_2D) self.texture = [texture_num.value, 0] texture_num.inc() print self.true_w, self.true_h, self.w, self.h if do_bind: self.bind(self.tostring, self.w, self.h)
def draw_image(self, image, pos=None, scale=None): """Draws an image on the screen arguments image -- a full path to an image file, or a pygame Surface (if image is neither of these, this function will attempt to treat the image as a PIL Image) keyword arguments pos -- image center position, an (x,y) position tuple or None for a central position (default = None) scale -- scale factor for the image or None for no scaling (default = None) returns Nothing -- loads and draws an image surface on (PyGame) or adds SimpleImageStim to (PsychoPy) the self.screen property """ if pos == None: pos = (self.dispsize[0]/2, self.dispsize[1]/2) # check if image is a path name if type(image) == str: # check if the image file exists if os.path.isfile(image): # load image from file try: img = pygame.image.load(image) except: raise Exception("Error in libscreen.PyGameScreen.draw_image: could not load image file %s" % image) else: raise Exception("Error in libscreen.PyGameScreen.draw_image: path %s is not a file!" % image) # check if image is a PyGame Surface elif type(image) == pygame.Surface: # since image is already a PyGame Surface, we needn't do anything with it img = image # finally, try if the image is supported by PIL else: try: # PIL Image to PyGame Surface img = pygame.image.fromstring(image.tostring(), (image.size[0],image.size[1]), 'RGB', False) except: raise Exception("Error in libscreen.PyGameScreen.draw_image: image format not recognized!") if scale != None: img = pygame.transform.scale(img, (int(img.get_width()*scale), int(img.get_height()*scale))) imgpos = (int(pos[0] - img.get_width()/2), int(pos[1] - img.get_height()/2)) self.screen.blit(img, imgpos)
def save_texture(self, name, image_obj): """Add pygame surface to video memory""" self.textures[name] = glGenTextures(1) texture_data = image.tostring(image_obj, "RGBA", 1) glBindTexture(GL_TEXTURE_2D, self.textures[name]) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_obj.get_width(), image_obj.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture_data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) return self.textures[name]
def SetImage(self, sec, color, mask): # Split the seconds up into d/h/m/s timelist = [] timelist.append("%02d" % (sec / 86400)) sec = sec % 86400 timelist.append("%02d" % (sec / 3600)) sec = sec % 3600 timelist.append("%02d" % (sec / 60)) sec = sec % 60 timelist.append("%02d" % sec) # Pop left-hand 0's until just m/s are left, if < 1hr while timelist[0] == "00" and len(timelist) > 2: timelist.pop(0) # Turn that into a single string and render it text = ':'.join(timelist) text = self.font.render(text, 0, color, self.bgcolor) # Make sure our background surface is big enough. Grow it if not img_size = text.get_size() if self.bgsurf is None: self.redraw_background(img_size) else: bgsurf_size = self.bgsurf.get_size() if bgsurf_size[0] < img_size[0] or bgsurf_size[1] < img_size[1]: self.redraw_background(img_size) # Figure out where to blit text to background so it's centerprinted bgsurf_size = self.bgsurf.get_size() justify = (bgsurf_size[0] - img_size[0]) / 2 # Blank our background, blit text self.bgsurf.fill(self.bgcolor) self.bgsurf.blit(text, (justify, 0)) # Create the wx surface and load in the pygame surface's image_string image_string = image.tostring(self.bgsurf, "RGB") surf = wx.EmptyImage(*bgsurf_size) surf.SetData(image_string) surf.SetMaskColour(*self.bgcolor) surf.SetMask(mask) self.bmp = surf.ConvertToBitmap() # Shrink window and shape around image self.SetClientSize((self.bmp.GetWidth(), self.bmp.GetHeight())) self.SetWindowShape() dc = wx.ClientDC(self) dc.DrawBitmap(self.bmp, 0,0, True)
def loadImage(textureSurface): textureData = image.tostring(textureSurface, "RGBA") width = textureSurface.get_width() height = textureSurface.get_height() texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData) return texture, width, height
def apply_texture(self): texture_surface = image.load(self.texture) texture_data = image.tostring(texture_surface, "RGBA", 1) glBindVertexArray(self.VAO) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.tex_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.tex_id) glTexImage2D(GL_TEXTURE_2D, 0, 4, *texture_surface.get_size(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture_data) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glGenerateMipmap(GL_TEXTURE_2D)
def blit(self, src, dst=(0, 0), area=None): if isinstance(dst, Rect): dst = dst.topleft x, y = dst if area is not None: area = area.clip(src.get_rect()) src = src.subsurface(area) x += area.left y += area.top w, h = src.get_size() data = image.tostring(src, 'RGBA', 1) gl = GL gl.glRasterPos2i(x, y + h) gl.glDrawPixels(w, h, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data)
def blit(self, src, dst = (0, 0), area = None, flags = 0): # TODO: flags #print "GLSurface.blit:", src, "at", dst, "area =", area ### if isinstance(dst, Rect): dst = dst.topleft x, y = dst if area is not None: area = area.clip(src.get_rect()) src = src.subsurface(area) x += area.left y += area.top w, h = src.get_size() data = image.tostring(src, 'RGBA', 1) #print "GLSurface: Drawing %sx%s pixels at %s,%s" % (w, h, x, y + h) ### gl = GL gl.glRasterPos2i(x, y + h) gl.glDrawPixels(w, h, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data)
def __init__(self, im=None): # todo clean up, it a mess if isinstance(im, Surface): self.image = im elif isinstance(im, str): for start in builtins: if im.startswith(start + ":"): for file in os.listdir("scene/Media" + "/" + start): if file.startswith(im[len(start) + 1:]): im = "scene/Media/" + start + "/" + file self.image = image.load(im) elif isinstance(im, PIL.Image): self.image = image.fromstring(image.tostring(), image.size, image.mode) self.original = self.image self.filtering_mode = 0 # todo implement and add constants self.size = 0 # todo add geter
def blit(self, src, dst=(0, 0), area=None, flags=0): # TODO: flags #print "GLSurface.blit:", src, "at", dst, "area =", area ### if isinstance(dst, Rect): dst = dst.topleft x, y = dst if area is not None: area = area.clip(src.get_rect()) src = src.subsurface(area) x += area.left y += area.top w, h = src.get_size() data = image.tostring(src, 'RGBA', 1) #print "GLSurface: Drawing %sx%s pixels at %s,%s" % (w, h, x, y + h) ### gl = GL gl.glRasterPos2i(x, y + h) gl.glDrawPixels(w, h, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data)
def loadTexture(filename): ''' Loads an OpenGL texture ''' surface = image.load(filename) texture = image.tostring(surface, 'RGBA', True) w, h = surface.get_rect().size ID = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, ID) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture) return ID
import os, time # os.system('sudo rmmod uvcvideo') # time.sleep(2) # os.system('sudo modprobe uvcvideo nodrop=1') # time.sleep(2) camera.init() cam_list = camera.list_cameras() cam = camera.Camera(cam_list[0], (640, 480)) i = 0 cam.start() while 1: i += 1 time.sleep(1) img = cam.get_image() # cam.stop() # screen = pygame.display.set_mode((640, 480), pygame.RESIZABLE) # screen.blit((0, 0), img) # pygame.display.update() img = image.tostring(img, "RGB", False) img = Image.frombytes("RGB", (640, 480), img) img.save('1.jpg'.format(i)) print(img) code = pyzbar.decode(img) print(i, code)
def get_imgdata_rgba(self): from pygame.image import tostring return tostring(self.img.get_pygame_image(), 'RGBA')
class GLDisplayContext(object): def __init__(self, splash=None): self.reset(splash) @staticmethod def getWindowSize(): w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get()) return max(20, w), max(20, h) @staticmethod def displayMode(): return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF def reset(self, splash=None): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception, e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) wwh = self.getWindowSize() d = display.set_mode(wwh, self.displayMode()) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) if splash: swh = splash.get_size() x, y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh data = image.tostring(splash, 'RGBA', 1) GL.glWindowPos2d(x, y) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) display.flip() display.set_caption('MCEdit ~ ' + release.get_version(), 'MCEdit') if sys.platform == 'win32' and config.settings.setWindowPlacement.get( ): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement( hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement( hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif sys.platform == 'linux2' and mcplatform.hasXlibDisplay: dis = mcplatform.Xlib.display.Display() root = dis.screen().root windowIDs = root.get_full_property( dis.intern_atom('_NET_CLIENT_LIST'), mcplatform.Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = dis.create_resource_object('window', windowID) name = window.get_wm_name() if "MCEdit ~ Unified" in name: win = window win.configure(x=config.settings.windowX.get(), y=config.settings.windowY.get()) self.win = win dis.sync() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e))
def draw_interesting_stuff(image, table, cueballs): """Draw table bounds, found cueballs and other interesting data to image.""" img_pygame = pygame.image.frombuffer(image.tostring(), image.size, image.mode) font = pygame.font.Font(pygame.font.get_default_font(), 12) if table: for pocket in ['tl', 'tr', 'bl', 'br']: # Draw pockets pygame.draw.rect( img_pygame, (0xff, 0xbb, 0x44), pygame.Rect( table[pocket].x-pocket_markers[pocket].x, table[pocket].y-pocket_markers[pocket].y, pocket_templates[pocket].width, pocket_templates[pocket].height ), 1 ) # Draw table bounds pygame.draw.lines( img_pygame, (0xdd, 0xaa, 0x00), True, [ (table['tl'].x, table['tl'].y), (table['tr'].x, table['tr'].y), (table['br'].x, table['br'].y), (table['bl'].x, table['bl'].y), ], 1 ) if cueballs: for cueball in cueballs: pygame.draw.rect( img_pygame, cueball is cueballs[0] and (0xcc, 0x22, 0x00) or (0x88, 0x88, 0x88), pygame.Rect( cueball.x-int(tmpl_ball.width/2)-7, cueball.y-7, tmpl_ball.width+14, tmpl_ball.height * 2 + 16 ), cueball.confirmed and 3 or 1 ) # Display confidence img_pygame.blit( font.render("%.2f" % cueball.confidence, True, (0xff, 0xff, 0xff)), (cueball.x-int(tmpl_ball.width/2)-5, cueball.y-7-font.get_height()) ) # Display if ball is not on table if cueball.flags.get('NOT_ON_TABLE'): img_pygame.blit( font.render("NOT", True, (0xcc, 0x00, 0x00)), (cueball.x-int(tmpl_ball.width/2)-5, cueball.y+tmpl_ball.height*2+10) ) # Display the match number. If the ball is incorrectly identified as not-a-cueball but this # number is 0, then it is the evaluator's fault for dismissing it on other bases. img_pygame.blit( font.render(str(cueball.flags['nth_match']), True, (0xcc, 0xcc, 0xcc)), (cueball.x-int(tmpl_ball.width/2)-18, cueball.y-7) ) return img_pygame
X2 = [] Y2 = [] for i in range(len(X1)-1) : for k in range(X1[i+1]-X1[i]) : X2.append(X1[i]+k) Y2.append(Y1[i]+k*(Y[i+1]-Y[i])/(X[i+1]-X[i])) X2.append(X1[-1]) Y2.append(Y1[-1]) #Recuperation d'images de milieux imgforet = image.load("foret.png") imgmer = image.load("mer.png") xf, yf = imgforet.get_size() xm, ym = imgmer.get_size() foret0 = image.tostring(imgforet, "RGB") mer0 = image.tostring(imgmer, "RGB") xif, yif = randint(0, xf-img_size), randint(0, yf-img_size) xim, yim = randint(0, xm-img_size), randint(0, ym-img_size) foret = b"" for y in range(img_size) : pos = (yif+y)*xf*3+xif*3 foret += foret0[pos : pos+img_size*3] mer = b"" for y in range(img_size) : pos = (yim+y)*xm*3+xim*3 mer += mer0[pos : pos+img_size*3] imgmer = image.fromstring(mer, [img_size]*2, "RGB") image.save(imgmer, "merrendu.png")
def preGamePackage(self, sendFn): sendFn(('dims', self.w, self.h, self.players, len(self))) for p in self: sendFn(('p', p.loc, p.r, pgi.tostring(p.image, 'RGBA'), p.pName))
def convert_frame_to_image(self, frame): return Image.frombytes('RGB', self._temp_surface.get_size(), tostring(self._temp_surface, 'RGB'))
def to_database(self) -> None: bin_data = image.tostring(self.sprite.image, "RGBA") self.sql_image = bin_data rect = self.sprite.image.get_rect() self.sql_width = rect.w self.sql_height = rect.h
def draw_text(self, a_text, position=None): text_data = image.tostring(a_text, "RGBA", True) opengl.gl_raster_position(position.x, position.y, position.z) opengl.gl_draw_pixels(text_data, a_text.get_width(), a_text.get_height())
def to_str(name): img = load(name) img_str = b64encode(compress(tostring(img, "RGBA"))) return img_str.decode()
def getKivyTexture(img): buffer = tostring(img.getPGSurface(),'RGB',True) # buffer = img.toString() imdata = ImageData(img.width, img.height, 'rgb', buffer) tex = Texture.create_from_data(imdata) return tex
cam = Device() # inicia la camara screen.fill(background) word = win32com.client.DispatchEx("Word.Application") # inicia word word.DisplayAlerts = 0 doc = word.Documents.Add() # Crea el doc fuente = pygame.font.Font(None, 40) # -------------- etiquetas ------------------ etiqueta = fuente.render('Capturar[a] Guardar[s] ',1, (0,0,0)) screen.blit(etiqueta, (20, height-55)) run = True while run: even = pygame.event.get() cKey = pygame.key.get_pressed() for e in even: if e.type == pygame.QUIT: run = False if cKey[pygame.K_a]: cam.saveSnapshot('c:\\img.png') # captura imagen newShape = word.ActiveDocument.InlineShapes.AddPicture("c:\\img.png", False, True) # agrega la foto al documento os.remove('c:\\img.png') if cKey[pygame.K_s]: word.Visible = True # muestra el documento image = cam.getImage() # captura la imagen img = pygame.image.fromstring(image.tostring(), image.size, 'RGB') # convierte a surface la PIL image screen.blit(img, (width/2 - 320,0)) pygame.display.flip()
def setActive(self): width = self.window.get_width() height = self.window.get_height() self.background = image.frombuffer(image.tostring(self.window,"RGB"),(width,height),"RGB") self.ttype = randint(1,self.TOTALTYPES) self.active = True
def cvimage_to_pygame( image ): """Convert cvimage into a pygame image""" #image_rgb = cv.CreateMat(image.height, image.width, cv.CV_8UC3) #cv.CvtColor(image, image_rgb, cv.CV_BGR2RGB) return pygame.image.frombuffer( image.tostring(), cv.GetSize( image ), "P" )
def pygame_surf_to_pil_img(surf, color_format="RGBA"): if not HAS_PIL: raise Exception("PIL was not found on this machine.") size = surf.get_size() pil_string_image = tostring(surf, color_format, False) return Image.fromstring(color_format, size, pil_string_image)
class GLDisplayContext(object): def __init__(self, splash=None, caption=("", "")): self.win = None self.reset(splash, caption=caption) @staticmethod def getWindowSize(): w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get()) return max(20, w), max(20, h) @staticmethod def displayMode(): return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF def reset(self, splash=None, caption=("", "")): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception, e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) if DEBUG_WM: print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get() wwh = self.getWindowSize() if DEBUG_WM: print "wwh 1", wwh d = display.set_mode(wwh, self.displayMode()) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) display.set_caption(*caption) if mcplatform.WindowHandler: self.win = mcplatform.WindowHandler(mode=self.displayMode()) # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif self.win: maximized = config.settings.windowMaximized.get() if DEBUG_WM: print "maximized", maximized if maximized: geom = self.win.get_root_rect() in_w, in_h = self.win.get_size() x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2) os.environ['SDL_VIDEO_CENTERED'] = '1' else: os.environ['SDL_VIDEO_CENTERED'] = '0' x, y = config.settings.windowX.get(), config.settings.windowY.get() wwh = self.win.get_size() if DEBUG_WM: print "x", x, "y", y print "wwh 2", wwh if splash: GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glWindowPos2d(0, 0) back = Surface(wwh) back.fill((0, 0, 0)) GL.glDrawPixels(wwh[0], wwh[1], GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(image.tostring(back, 'RGBA'), dtype='uint8')) swh = splash.get_size() _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh data = image.tostring(splash, 'RGBA', 1) GL.glWindowPos2d(_x, _y) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) if splash: display.flip() if self.win: if not maximized: wwh = self.getWindowSize() if DEBUG_WM: print "wwh 3", wwh self.win.set_position((x, y), update=True) if DEBUG_WM: print "* self.win.get_position()", self.win.get_position() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e))
def reset(self, splash=None, caption=("", "")): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception as e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) if DEBUG_WM: print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get() wwh = self.getWindowSize() if DEBUG_WM: print "wwh 1", wwh d = display.set_mode(wwh, self.displayMode()) # Let initialize OpenGL stuff after the splash. GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates # GL.glMatrixMode(GL.GL_TEXTURE) # GL.glScale(1 / 256., 1 / 256., 1 / 256.) display.set_caption(*caption) if mcplatform.WindowHandler: self.win = mcplatform.WindowHandler(mode=self.displayMode()) # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif self.win: maximized = config.settings.windowMaximized.get() if DEBUG_WM: print "maximized", maximized if maximized: geom = self.win.get_root_rect() in_w, in_h = self.win.get_size() x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2) os.environ['SDL_VIDEO_CENTERED'] = '1' else: os.environ['SDL_VIDEO_CENTERED'] = '0' x, y = config.settings.windowX.get(), config.settings.windowY.get() wwh = self.win.get_size() if DEBUG_WM: print "x", x, "y", y print "wwh 2", wwh if splash: # Setup the OGL display GL.glLoadIdentity() GLU.gluOrtho2D(0, wwh[0], 0, wwh[1]) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_ACCUM_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT) swh = splash.get_size() _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh try: data = image.tostring(splash, 'RGBA_PREMULT', 1) except ValueError: data = image.tostring(splash, 'RGBA', 1) except ValueError: data = image.tostring(splash, 'RGB', 1) # Set the raster position GL.glRasterPos(_x, _y) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) if splash: display.flip() if self.win: if not maximized: wwh = self.getWindowSize() if DEBUG_WM: print "wwh 3", wwh self.win.set_position((x, y), update=True) if DEBUG_WM: print "* self.win.get_position()", self.win.get_position() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception as e: logging.warning('Unable to set icon: {0!r}'.format(e)) # Let initialize OpenGL stuff after the splash. # GL.glEnableClientState(GL.GL_VERTEX_ARRAY) # GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) # GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) self.display = d self.loadTextures()
def generer_image(img_size, n_points, precision): p = n_points img_size = int(img_size * 1.5) Points = [[i * img_size / (p - 1), random() * (img_size + 1)] for i in range(p)] X = [] Y = [] #Precision n = precision #Partie compliquee mais qui marche for t in range(n): Droites = [Points] for i in range(p - 1): Temp = [] Ref = Droites[-1] for j in range(len(Ref) - 1): Temp.append([(Ref[j + 1][0] - Ref[j][0]) * t / n + Ref[j][0], (Ref[j + 1][1] - Ref[j][1]) * t / n + Ref[j][1]]) Droites.append(Temp) X.append(Droites[-1][0][0]) Y.append(Droites[-1][0][1]) X1 = list(map(int, X)) Y1 = list(map(int, Y)) #Adaptation de la courbe dans une image for i in range(len(X1) - 1, 0, -1): if X1[i] == X[i - 1]: X1.pop(i) Y1.pop(i) X2 = [] Y2 = [] for i in range(len(X1) - 1): for k in range(X1[i + 1] - X1[i]): X2.append(X1[i] + k) Y2.append(Y1[i] + k * (Y[i + 1] - Y[i]) / (X[i + 1] - X[i])) X2.append(X1[-1]) Y2.append(Y1[-1]) #Recuperation d'images de milieux imgforet = image.load("foret.png") imgmer = image.load("mer.png") xf, yf = imgforet.get_size() xm, ym = imgmer.get_size() foret0 = image.tostring(imgforet, "RGB") mer0 = image.tostring(imgmer, "RGB") xif, yif = randint(0, xf - img_size), randint(0, yf - img_size) xim, yim = randint(0, xm - img_size), randint(0, ym - img_size) foret = b"" for y in range(img_size): pos = (yif + y) * xf * 3 + xif * 3 foret += foret0[pos:pos + img_size * 3] mer = b"" for y in range(img_size): pos = (yim + y) * xm * 3 + xim * 3 mer += mer0[pos:pos + img_size * 3] #Creation de l'image def pxl(x, y, c): return x * 3 + c + (img_size * 3) * y rendu = "" for y in range(img_size): for x in range(img_size): if y < Y2[x]: rendu += mer[3 * img_size * y + 3 * x:3 * img_size * y + 3 * x + 3].decode(encoding='latin1') else: rendu += foret[3 * img_size * y + 3 * x:3 * img_size * y + 3 * x + 3].decode(encoding='latin1') #Application du flou def flou(imgstr, imgsize, bsize, x, y, c): infx = max(0, x - bsize) supx = min(img_size, x + bsize + 1) infy = max(0, y - bsize) supy = min(img_size, y + bsize + 1) s, n = 0, 0 for i in range(infx, supx): for j in range(infy, supy): s += imgstr[pxl(i, j, c)] n += 1 return (int(s / n)) sq_size = 1 blur_size = 1 rendu = rendu.encode(encoding='latin1') rendu2 = list(rendu) for x in range(img_size): inf = int(max(0, Y2[x] - sq_size)) sup = int(min(img_size, Y2[x] + sq_size + 1)) for y in range(inf, sup): rendu2[pxl(x, y, 0)] = flou(rendu, img_size, blur_size, x, y, 0) rendu2[pxl(x, y, 1)] = flou(rendu, img_size, blur_size, x, y, 1) rendu2[pxl(x, y, 2)] = flou(rendu, img_size, blur_size, x, y, 2) #Application d'une rotation aleatoire def rotation(x, y, xcentre, ycentre, theta): z = complex(x - xcentre, y - ycentre) z *= np.exp(theta * 1j) return int(z.real) + xcentre, int(z.imag) + ycentre theta = random() * 2 * np.pi rendu3 = [] for x in range(img_size // 6, 5 * img_size // 6): for y in range(img_size // 6, 5 * img_size // 6): xr, yr = rotation(x, y, img_size // 2, img_size // 2, theta) rendu3.append(rendu2[pxl(xr, yr, 0)]) rendu3.append(rendu2[pxl(xr, yr, 1)]) rendu3.append(rendu2[pxl(xr, yr, 2)]) PtsBezier = [ rotation(x, Y2[x], img_size // 2, img_size // 2, theta) for x in range(img_size) ] return rendu3, PtsBezier
def reset(self, splash=None, caption=("", "")): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception as e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) if DEBUG_WM: print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get() wwh = self.getWindowSize() if DEBUG_WM: print "wwh 1", wwh d = display.set_mode(wwh, self.displayMode()) # Let initialize OpenGL stuff after the splash. GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates # GL.glMatrixMode(GL.GL_TEXTURE) # GL.glScale(1 / 256., 1 / 256., 1 / 256.) display.set_caption(*caption) if mcplatform.WindowHandler: self.win = mcplatform.WindowHandler(mode=self.displayMode()) # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif self.win: maximized = config.settings.windowMaximized.get() if DEBUG_WM: print "maximized", maximized if maximized: geom = self.win.get_root_rect() in_w, in_h = self.win.get_size() x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2) os.environ['SDL_VIDEO_CENTERED'] = '1' else: os.environ['SDL_VIDEO_CENTERED'] = '0' x, y = config.settings.windowX.get(), config.settings.windowY.get() wwh = self.win.get_size() if DEBUG_WM: print "x", x, "y", y print "wwh 2", wwh if splash: # Setup the OGL display GL.glLoadIdentity() GLU.gluOrtho2D(0, wwh[0], 0, wwh[1]) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_ACCUM_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT) swh = splash.get_size() _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh try: data = image.tostring(splash, 'RGBA_PREMULT', 1) except ValueError: data = image.tostring(splash, 'RGBA', 1) except ValueError: data = image.tostring(splash, 'RGB', 1) # Set the raster position GL.glRasterPos(_x, _y) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) if splash: display.flip() if self.win: if not maximized: wwh = self.getWindowSize() if DEBUG_WM: print "wwh 3", wwh self.win.set_position((x, y), update=True) if DEBUG_WM: print "* self.win.get_position()", self.win.get_position() try: #iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconpath = directories.getDataFile('favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception as e: logging.warning('Unable to set icon: {0!r}'.format(e)) # Let initialize OpenGL stuff after the splash. # GL.glEnableClientState(GL.GL_VERTEX_ARRAY) # GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) # GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) self.display = d self.loadTextures()
def loadImageFromFile(path): picSurface = image.load(path) pixel = image.tostring(picSurface, "RGB") #assert isinstance(pixel, str) return picSurface, pixel
client_socket_test.connect(("192.168.43.17", 50607)) print "Your IP address is: ", socket.gethostbyname(socket.gethostname()) # GET WEBCAM DATA BY PYGAME--------------- # Force SDL to write on our drawing area os.putenv('SDL_WINDOWID', str(canvas.get_property('window').get_xid())) # We need to flush the XLib event loop otherwise we can't # access the XWindow which set_mode() requires Gdk.flush() pygame.init() data = client_socket_test.recv(1024000) image = Image.fromstring("RGB", (80, 60), data) image = image.resize((640, 480)) image = pygame.image.frombuffer(image.tostring(), (640, 480), "RGB") print Surface.get_size(image) (WINX, WINY) = Surface.get_size(image) # setting screen according to size pygame.display.set_mode((WINX, WINY), 0, 0) screen = pygame.display.get_surface() #screen.blit(image, (0, 0)) #GLib.idle_add(pygame.display.update) print "yoyo" def updateImg(output): screen.blit(output, (0, 0)) GLib.idle_add(pygame.display.update) print "boom"
print "Your IP address is: ", socket.gethostbyname(socket.gethostname()) # GET WEBCAM DATA BY PYGAME--------------- # Force SDL to write on our drawing area os.putenv('SDL_WINDOWID', str(canvas.get_property('window').get_xid())) # We need to flush the XLib event loop otherwise we can't # access the XWindow which set_mode() requires Gdk.flush() pygame.init() data = client_socket_test.recv(1024000) image = Image.fromstring("RGB", (80, 60), data) image = image.resize((640, 480)) image = pygame.image.frombuffer(image.tostring(), (640, 480), "RGB") print Surface.get_size(image) (WINX, WINY) = Surface.get_size(image) # setting screen according to size pygame.display.set_mode((WINX, WINY), 0, 0) screen = pygame.display.get_surface() #screen.blit(image, (0, 0)) #GLib.idle_add(pygame.display.update) print "yoyo" def updateImg(output): screen.blit(output, (0, 0)) GLib.idle_add(pygame.display.update) print "boom" return True
def getKivyTexture(img): buffer = tostring(img.getPGSurface(), 'RGB', True) # buffer = img.toString() imdata = ImageData(img.width, img.height, 'rgb', buffer) tex = Texture.create_from_data(imdata) return tex
def _push_image_to_stack(self, screen): self.images_stack.append((image.tostring(self.screen, 'RGB'), self.upper_left, self.lower_right))
def __init__(self, s): # s = surface self.w, self.h = s.get_size() # print self.w, self.h self.tostring = image.tostring(s, "RGBA", True)