def get_antiround(self, radius, background): w, h = self.c.get_size() surface = self.s.copy().convert_alpha() newsurf = pygame.Surface((w, h), pygame.SRCALPHA, depth=self.c.get_bitsize()).convert_alpha() newsurf.fill((0, 0, 0, 0)) outer = self.c.get_rect().inflate((-2 * radius, -2 * radius)) n_a = surfarray.pixels_alpha(newsurf) n_rgb = surfarray.pixels3d(newsurf) b_b_c_rgb = surfarray.pixels3d(self.c) rngs = [(0, 0, 0, 2 * radius, 0, 2 * radius), (w, 0, w - 2 * radius, w, 0, 2 * radius), (0, h, 0, 2 * radius, h - 2 * radius, h), (w, h, w - 2 * radius, w, h - 2 * radius, h)] for i, ranges in enumerate(rngs): x0, y0, xi, xf, yi, yf = ranges for x in range(xi, xf): for y in range(yi, yf): d = math.hypot(x - x0, y - y0) n_a[x][y] = get_y(d, 0, 2 * radius) n_rgb[x][y] = b_b_c_rgb[x][y] #grass del n_a del n_rgb surface.unlock() newsurf.unlock() surface.blit(newsurf, (0, 0)) return surface
def _appliquerTransformationGlobale(self, nomTransformation, **p): """Applique la transformation globale <nomTransformation> avec le dico de paramètres <p>.""" if nomTransformation == "Rouge": pixels = surfarray.pixels3d(self._fenetre)[:FENETRE["longueurFenetre"], :FENETRE["largeurFenetre"]] #On exclut la zone de pensée pixels[:,:,1:] = 0 elif nomTransformation == "Noir": pixels = surfarray.pixels3d(self._fenetre)[:FENETRE["longueurFenetre"],:FENETRE["largeurFenetre"]] pixels /= p["coef"] if p["coef"] >= 12: pixels[:] = (0,0,0) elif nomTransformation == "NoirTotal": pixels = surfarray.pixels3d(self._fenetre)[:FENETRE["longueurFenetre"],:FENETRE["largeurFenetre"]] pixels[:] = (0,0,0) elif nomTransformation == "RemplirNoir": self._fenetre.fill((0,0,0)) elif "SplashText" in nomTransformation: if "couleurFond" in p.keys(): couleurFond=p["couleurFond"] else: couleurFond=None surfaceTexte = self._jeu.zonePensee.polices["splashText"].render(p["texte"], p["antialias"], p["couleurTexte"], couleurFond) self._fenetre.blit(surfaceTexte, p["position"]) elif nomTransformation == "Nuit": self._fenetre.fill((0,0,0)) c = 0 while c < self._nombreCouches: for nomPnj in self._pnj[c]: self._afficherBlocPnj(c, nomPnj) c += 1
def get_cliff_round(c, s, cliff, r_int, r_ext): #version for color background w,h = c.get_size() surface = s.copy() inner = c.get_rect().inflate((-4*r_int, -4*r_int)) outer = c.get_rect().inflate((-4*r_ext, -4*r_ext)) arrayrgb = surfarray.pixels3d(surface) c_arrayrgb = surfarray.pixels3d(c) cliff_arrayrgb = surfarray.pixels3d(cliff) ## rngs = [(inner.x,inner.y,0,inner.x,0,inner.y), ## (inner.right,inner.y,inner.right,w,0,inner.y), ## (inner.x,inner.bottom,inner.x-r_int,inner.x,inner.bottom,h), ## (inner.right,inner.bottom,inner.right,w-r_int+1,inner.bottom,h)] rngs = [(outer.x,outer.y,0,outer.x,0,outer.y), (outer.right,outer.y,outer.right,w,0,outer.y), (outer.x,outer.bottom,0,outer.x,outer.bottom,h), (outer.right,outer.bottom,outer.right,w-r_int+1,outer.bottom,h)] ## rngs = [(r_ext,r_ext,0,r_ext,0,r_ext), ## (w-r_ext,r_ext,w-r_ext,w,0,r_ext), ## (r_ext,h-r_ext,0,r_ext,h-r_ext,h), ## (w-r_ext,h-r_ext,w-r_ext,w,h-r_ext,h)] print(c.get_size(), s.get_size(), cliff.get_size(),rngs) for i, ranges in enumerate(rngs): x0,y0,xi,xf,yi,yf = ranges for x in range(xi,xf): for y in range(yi,yf): d = math.sqrt((x-x0)**2 + (y-y0)**2) ## if i < 2: ## if d > r_int+1: ## continue if r_ext >= d >= r_int: arrayrgb[x][y] = cliff_arrayrgb[x][y] elif d < r_int: arrayrgb[x][y] = c_arrayrgb[x][y] return surface
def get_round(self, radius, background): w, h = self.c.get_size() surface = self.s.copy().convert_alpha() newsurf = pygame.Surface((w, h), pygame.SRCALPHA, depth=self.c.get_bitsize()).convert_alpha() newsurf.fill((0, 0, 0, 0)) inner = self.c.get_rect().inflate((-4 * radius, -4 * radius)) n_a = surfarray.pixels_alpha(newsurf) n_rgb = surfarray.pixels3d(newsurf) b_b_c_rgb = surfarray.pixels3d(self.c) rngs = [(inner.x, inner.y, 0, inner.x, 0, inner.y), (inner.right, inner.y, inner.right, w, 0, inner.y), (inner.x, inner.bottom, 0, inner.x, inner.bottom, h), (inner.right, inner.bottom, inner.right, w, inner.bottom, h)] for i, ranges in enumerate(rngs): x0, y0, xi, xf, yi, yf = ranges for x in range(xi, xf): for y in range(yi, yf): d = math.hypot(x - x0, y - y0) n_a[x][y] = 255 - get_y(d, 0, 2 * radius) n_rgb[x][y] = b_b_c_rgb[x][y] del n_a del n_rgb surface.unlock() newsurf.unlock() surface.blit(newsurf, (0, 0)) return surface
def get_antiround(self, radius, background): w, h = self.c.get_size() surface = self.c.copy() b_c_rgb = surfarray.pixels3d(surface) s_rgb = surfarray.pixels3d(self.s) rngs = [(0, 0, 0, radius, 0, radius), (w, 0, w - radius, w, 0, radius), (0, h, 0, radius, h - radius, h), (w, h, w - radius, w, h - radius, h)] for x0, y0, xi, xf, yi, yf in rngs: for x in range(xi, xf): for y in range(yi, yf): if math.sqrt((x - x0)**2 + (y - y0)**2) < radius: b_c_rgb[x][y] = s_rgb[x][y] return surface
def pgBlitColumn(self,surface,pos): # Copy the column to a numpy array self.buffer[pos:pos+1] = np.copy(surfarray.pixels3d(surface).flatten()) # Is there isn't already a burst task in the queue, create a write_column task if not self.transmitter.burstInQueue.isSet(): self._send_noRcv([const.WRITE_COLUMN|const.DATA, pos, self.buffer[pos:pos+1]])
def draw_rectangle(width, height, colour, position, window): rectangle = Surface((width, height)) pixels = surfarray.pixels3d(rectangle) pixels[:][:] = colour del pixels rectangle.unlock() window.blit(rectangle, position)
def from_function_alpha(surface): if not HAS_NUMPY: raise Exception("Could not use surfarray module from PyGame.\ NumPy is probably missing.") size = surface.size newsurf = pygame.Surface(size, SRCALPHA, depth=surface.get_bitsize()).convert_alpha() newsurf.blit(surface, (0, 0)) if subrect: rect = subrect arrayrgb = surfarray.pixels3d(newsurf) arraya = surfarray.pixels_alpha(newsurf) points = [] max_d = hypot(rect.w, rect.h) for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): if tuple(arrayrgb[x][y]) != color_except: points.append((x, y)) if points: for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): if not (x, y) in points: d = 1. - illuminate_dist(points, rect, x, y) / max_d d = 255 * factor * d**fadout arraya[x][y] = d arrayrgb[x][y] = color_target else: if color_bulk: arrayrgb[x][y] = color_bulk if bulk_alpha: arraya[x][y] = bulk_alpha
def NumPy2Ipl(surf): """Converts a pygame surface to an openCV cvArray. Parameters: pygame.Surface surf - pygame Surface """ py_image = surfarray.pixels3d(surf) cv_image = adaptors.NumPy2Ipl(py_image.transpose(1, 0, 2)) return cv_image
def recolor(image, mode): if mode is None: return red = mode.red yellow = mode.yellow green = mode.green red, yellow, green = (np.asarray(c,np.uint8) for c in (red, yellow, green)) # We need to make a copy in this specific format image = image.convert_alpha(pygame.Surface((1,1), pygame.SRCALPHA, 32)) # We can't make a new image from an array, so we're going to # jigger this one in place. a = surfarray.pixels3d(image) yellow_red = (a[...,0] > a[...,1]) & (a[...,2]<=a[...,1]) yr = a[yellow_red,:] c1 = yr[:,2] c2 = yr[:,1]-yr[:,2] c3 = yr[:,0]-yr[:,1] a[yellow_red,:3] = np.minimum(c1[:,None] + (c2[:,None]/255.)*yellow[None,:] + (c3[:,None]/255.)*red[None,:], 255).astype(np.uint8) green_yellow = (a[...,0] <= a[...,1]) & (a[...,2]<=a[...,0]) gy = a[green_yellow,:] c1 = gy[:,2] c2 = gy[:,0]-gy[:,2] c3 = gy[:,1]-gy[:,0] a[green_yellow,:3] = np.minimum(c1[:,None] + (c2[:,None]/255.)*yellow[None,:] + (c3[:,None]/255.)*green[None,:], 255).astype(np.uint8) return image
def compileSVASheet(sheet, color): color = tuple([255-c for c in color]) width = sheet.get_width() height = sheet.get_height() / 3 colorSurf = Surface((width, height)) colorSurf.fill(color) colorSurf.blit(sheet, (0, 0), None, BLEND_MULT) # Now create a white surface so we can invert the Saturation map result = Surface((width, height), SRCALPHA) result.fill((255, 255, 255)) result.blit(colorSurf, (0, 0), None, BLEND_RGB_SUB) # Multiply this with the Value Map result.blit(sheet, (0, -height), None, BLEND_MULT) # copy the alpha mask from the spritesheet alpha = Surface((width, height)) alpha.blit(sheet, (0, -2 * height)) #convert the (nearly done) Surface to per pixel alpha result.convert_alpha() # Use Numpy here numWhite = surfarray.pixels_alpha( result ) numAlpha = surfarray.pixels3d( alpha ) numWhite[ :, : ] = numAlpha[ :, :, 0 ] return result.copy()
def set_alpha_from_intensity(surface, alpha_factor, decay_mode, color): if not HAS_PIL: raise Exception("PIL was not found on this machine.") if not HAS_NUMPY: raise Exception("NumPy was not found on this machine.") rect = surface.get_rect() newsurf = Surface(rect.size, SRCALPHA, depth=surface.get_bitsize()) newsurf = newsurf.convert_alpha() newsurf.blit(surface, (0, 0)) arrayrgb = surfarray.pixels3d(newsurf) arraya = surfarray.pixels_alpha(newsurf) bulk_color = tuple(color) for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): color = tuple(arrayrgb[x][y]) light = square_color_norm(color) alpha = float(light)/MAX_NORM * 255 arrayrgb[x][y][0] = bulk_color[0] arrayrgb[x][y][1] = bulk_color[1] arrayrgb[x][y][2] = bulk_color[2] if decay_mode == "linear": actual_alpha = int(255 - alpha) elif decay_mode == "exponential": tuning_factor = 1.03 actual_alpha = int(255*tuning_factor**-alpha) ## elif decay_mode == "quadratic": ## pass else: raise Exception("decay_mode not recognized: " + decay_mode) actual_alpha *= alpha_factor arraya[x][y] = actual_alpha return newsurf
def illuminate_color_except(surface, color_except, color_target, color_bulk=None, subrect=None, factor=1., fadout=2): """ mode : "except" means all the pixels that are not color_source. "exact" means all the pixels that are exacly color_source. """ if not HAS_NUMPY: raise Exception("Could not use surfarray module from PyGame.\ NumPy is probably missing.") rect = surface.get_rect() newsurf = pygame.Surface(rect.size, depth=surface.get_bitsize()).convert() newsurf.blit(surface, (0, 0)) if subrect: rect = subrect arrayrgb = surfarray.pixels3d(newsurf) points = [] max_d = hypot(rect.w, rect.h) for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): if tuple(arrayrgb[x][y]) != color_except: points.append((x, y)) for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): if not (x, y) in points: d = 1. - illuminate_dist(points, rect, x, y) / max_d d = d**fadout color = grow_color(factor * d, color_target) color = normalize_color(color) arrayrgb[x][y] = color elif color_bulk: arrayrgb[x][y] = color_bulk return newsurf
def surf2CV(surf): """ Given a Pygame surface, convert to an OpenCv cvArray format. Either Ipl image or cvMat. """ numpyImage = surfarray.pixels3d(surf)#.copy() # Is this required to be a copy? cvImage = adaptors.NumPy2Ipl(numpyImage.transpose(1,0,2)) '''arr = surfarray.pixels3d(surf) w = int(surf.get_width()) h = int(surf.get_height()) print str(w) + " " + str(h) cvImage = cv.CreateImage((w,h), 8, 3) #cvSet(cvImage, (0,0,0)) #print arr[0][0][0] for x in range(200): for y in range(200): cv.Set2D(cvImage, y, x, (int(arr[y][x][0]), int(arr[y][x][1]), int(arr[y][x][2])))''' return cvImage
def palettify_bogus(infile, outfile): surface = pygame.image.load(infile).convert(24) a = surfarray.pixels3d(surface) realgreens = (a[...,0]==0) & (a[...,2]==0) realreds = (a[...,1]==0) & (a[...,2]==0) realyellows = (a[...,0]==a[...,1]) & (a[...,2]==0) realblues = (a[...,0]==0) & (a[...,1]==0) & (a[...,2]==255) blues = (a[...,2]>127) greens = (a[...,0]<a[...,1]//2) reds = (a[...,1]<a[...,0]//2) yellows = ~greens & ~reds print infile, np.sum(realgreens & ~greens), np.sum(realreds & ~reds), np.sum(realyellows & ~yellows & ~reds & ~greens), np.sum(realblues & ~blues), np.sum(~realreds & ~realgreens & ~realyellows & ~realblues) a[greens,0] = 0 a[greens,2] = 0 a[yellows,0] = a[yellows,0] + (a[yellows,1]-a[yellows,0])//2 a[yellows,1] = a[yellows,0] a[yellows,2] = 0 a[reds,1] = 0 a[reds,2] = 0 a[blues,0] = 0 a[blues,1] = 0 a[blues,2] = 255 del a pygame.image.save(surface, outfile)
def runTest(self) -> None: width, height = 800, 600 screen = pygame.display.set_mode((width * 2, height)) pygame.display.set_caption("bright pass filter (bpf24_inplace)") checker = pygame.image.load( '../Assets/background_checker.png').convert() checker = pygame.transform.smoothscale(checker, (1600, 600)) background = pygame.image.load('../Assets/I1.png').convert_alpha() background = pygame.transform.smoothscale(background, (800, 600)) background_cp = background.copy() # array3d # test_bpf24_inplace(array3d(background), 40) # pixel3d test_bpf24_inplace(pixels3d(background), 45) # test argument threshold self.assertRaises(OverflowError, test_bpf24_inplace, array3d(background), -40) self.assertRaises(OverflowError, test_bpf24_inplace, array3d(background), 440) display(screen, checker, background_cp, background)
def take_damage(self, damage: int): self._data.health = self._data.health - damage arr = surfarray.pixels3d(self.image) arr[:, :, 0] = 255 arr[:, :, 1] = 0 arr[:, :, 2] = 0 time.sleep(.020)
def set_alpha_from_intensity(surface, alpha_factor, decay_mode, color): if not HAS_PIL: raise Exception("PIL was not found on this machine.") if not HAS_NUMPY: raise Exception("NumPy was not found on this machine.") rect = surface.get_rect() newsurf = Surface(rect.size, SRCALPHA, depth=surface.get_bitsize()) newsurf = newsurf.convert_alpha() newsurf.blit(surface, (0, 0)) arrayrgb = surfarray.pixels3d(newsurf) arraya = surfarray.pixels_alpha(newsurf) bulk_color = tuple(color) for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): color = tuple(arrayrgb[x][y]) light = square_color_norm(color) alpha = float(light) / MAX_NORM * 255 arrayrgb[x][y][0] = bulk_color[0] arrayrgb[x][y][1] = bulk_color[1] arrayrgb[x][y][2] = bulk_color[2] if decay_mode == "linear": actual_alpha = int(255 - alpha) elif decay_mode == "exponential": tuning_factor = 1.03 actual_alpha = int(255 * tuning_factor**-alpha) ## elif decay_mode == "quadratic": ## pass else: raise Exception("decay_mode not recognized: " + decay_mode) actual_alpha *= alpha_factor arraya[x][y] = actual_alpha return newsurf
def pgBlit(self,surface): # Copy the matrix as a numpy array self.buffer = np.copy(surfarray.pixels3d(surface).flatten()) # Is there isn't already a burst task in the queue, create one if not self.transmitter.burstInQueue.isSet(): self.transmitter.burstInQueue.set() self._send_noRcv([const.BURST|const.DATA, self.buffer])
def get_antiround(self, radius, background): w, h = self.c.get_size() surface = self.c.copy() b_c_rgb = surfarray.pixels3d(surface) s_rgb = surfarray.pixels3d(self.s) rngs = [(0, 0, 0, radius, 0, radius), (w, 0, w - radius, w, 0, radius), (0, h, 0, radius, h - radius, h), (w, h, w - radius, w, h - radius, h)] radiusSqr = radius**2 for x0, y0, xi, xf, yi, yf in rngs: for x in range(xi, xf): dxSqr = (x - x0)**2 if dxSqr < radiusSqr: for y in range(yi, yf): if dxSqr + (y - y0)**2 < radiusSqr: b_c_rgb[x][y] = s_rgb[x][y] return surface
def get_round(self, radius, background): #version for color background w, h = self.c.get_size() surface = self.c.copy() inner = self.c.get_rect().inflate((-4 * radius, -4 * radius)) b_c_rgb = surfarray.pixels3d(surface) s_rgb = surfarray.pixels3d(self.s) rngs = [(inner.x, inner.y, 0, inner.x, 0, inner.y), (inner.right, inner.y, inner.right, w, 0, inner.y), (inner.x, inner.bottom, 0, inner.x, inner.bottom, h), (inner.right, inner.bottom, inner.right, w, inner.bottom, h)] for x0, y0, xi, xf, yi, yf in rngs: for x in range(xi, xf): for y in range(yi, yf): if math.sqrt((x - x0)**2 + (y - y0)**2) > radius: b_c_rgb[x][y] = s_rgb[x][y] return surface
def surf2CV(surf): """ Given a Pygame surface, convert to an OpenCv cvArray format. Either Ipl image or cvMat. """ numpyImage = surfarray.pixels3d(surf) # .copy() # Is this required to be a copy? cvImage = adaptors.NumPy2Ipl(numpyImage.transpose(1, 0, 2)) return cvImage
def get_round_river(radius_divider, corner, front): if corner is None: return front w, h = front.get_size() background = pygame.Surface((w, h)) surface = front.copy().convert_alpha() newsurf = pygame.Surface((w, h), pygame.SRCALPHA, depth=background.get_bitsize()).convert_alpha() newsurf.fill((0, 0, 0, 0)) radius = w // radius_divider inner = background.get_rect().inflate((-2 * radius, -2 * radius)) n_a = surfarray.pixels_alpha(newsurf) n_rgb = surfarray.pixels3d(newsurf) b_b_c_rgb = surfarray.pixels3d(background) #Define ranges. topleft = (inner.left, inner.top, 0, inner.left, 0, inner.top) topright = (inner.right, inner.top, inner.right, h, 0, inner.top) bottomleft = (inner.left, inner.bottom, 0, inner.left, inner.bottom, h) bottomright = (inner.right - 1, inner.bottom - 1, inner.right, h, inner.bottom, h) ranges = { "topleft": topleft, "topright": topright, "bottomleft": bottomleft, "bottomright": bottomright } r2 = radius**2 centerx, centery, xi, xf, yi, yf = ranges[corner] for x in range(xi, xf): rx2 = (x - centerx)**2 for y in range(yi, yf): if rx2 + (y - centery)**2 > r2: n_a[x][y] = 255 #alpha background = 255 n_rgb[x][y] = b_b_c_rgb[x][y] ## else: ## n_rgb[x][y] = (b_b_c_rgb[x][y]+n_rgb[x][y])//2 del n_a del n_rgb surface.unlock() newsurf.unlock() surface.blit(newsurf, (0, 0)) surface = surface.convert() surface.set_colorkey((0, 0, 0)) return surface
def pgBlitSection(self,surface,pos,lenght): # Copy the section to a numpy array self.buffer[pos:pos+lenght] = np.copy(surfarray.pixels3d(surface).flatten()) # Is there isn't already a burst task in the queue, create a write_section task if not self.transmitter.burstInQueue.isSet(): self._send_noRcv([const.WRITE_SECTION|const.DATA, pos, lenght, self.buffer[pos:pos+lenght]]) self.setTotalWidth(res[0])
def surf2CV(surf): """ Given a Pygame surface, convert to an OpenCv cvArray format. Either Ipl image or cvMat. """ numpyImage = surfarray.pixels3d( surf) #.copy() # Is this required to be a copy? cvImage = adaptors.NumPy2Ipl(numpyImage.transpose(1, 0, 2)) return cvImage
def genLands(r, landCols, seaColRange, lands=10, sizeParam=1., colChangeRate=0.02): """Generates a planet with seas and islands.""" DIRS = ((0, -1), (-1, 0), (0, 1), (1, 0)) MAXTRIES = 10 # number of times to try to find a land seed PROBA, PROBB = 0.49, 1.1 # generation parameters if len(seaColRange) == 2: sf = planetSolid(r, *seaColRange) else: sf = planetSolid(r, seaColRange, seaColRange) randAngle = random() * 2 * math.pi sf = rotateCircle(sf, randAngle) sizeProb = (PROBA / sizeParam) * (1 - (1 / PROBB**r)) landArray = circleMask(r).clip(0, 1) sfArray = sfa.pixels3d(sf) d = r * 2 landCols = [HtoR(*col) for col in landCols] def joinLands(y, x, landArray, sfArray, col): if y < 0 or y > d or x < 0 or x > d or landArray[y][x] != 1: return landArray[y][x] = 2 if random() < colChangeRate: sfArray[y][x] = choice(landCols) else: sfArray[y][x] = col for dy, dx in DIRS: if random() < sizeProb: joinLands(y + dy, x + dx, landArray, sfArray, col) for i in range(lands): for j in range(MAXTRIES): # find a land seed y, x = randint(0, d), randint(0, d) if landArray[y][x] == 1: break else: continue # recursively generate land starting from the seed callWithLargeStack(joinLands, x, y, landArray, sfArray, choice(landCols)) # get rid of 1x1 seas h, w = landArray.shape for y in range(h): for x in range(w): if (landArray[y][x] == 1 and (x == 0 or landArray[y][x - 1] == 2) and (y == 0 or landArray[y - 1][x] == 2) and (x == w - 1 or landArray[y][x + 1] == 2) and (y == h - 1 or landArray[y + 1][x] == 2)): landArray[y][x] = 2 dy, dx = choice(DIRS) if 0 < y < h - 1 and 0 < x < w - 1: sfArray[y][x] = sfArray[y + dy][x + dx] del sfArray return sf
def _smooth(surface): w,h = surface.get_size() arrayrgb = surfarray.pixels3d(surface) sum_array = numpy.zeros(arrayrgb.shape) for d in mapgen.MOORE: sum_array += numpy.roll( numpy.roll(arrayrgb[:,:], d[0], axis=0), d[1], axis=1 ) sum_array /= len(mapgen.MOORE) s = surfarray.make_surface(sum_array) return s
def blit_tinted(surface, image, pos, tint, src_rect=None): from Numeric import array, add, minimum from pygame.surfarray import array3d, pixels3d if src_rect: image = image.subsurface(src_rect) buf = Surface(image.get_size(), SRCALPHA, 32) buf.blit(image, (0, 0)) src_rgb = array3d(image) buf_rgb = pixels3d(buf) buf_rgb[...] = minimum(255, add(tint, src_rgb)).astype('b') buf_rgb = None surface.blit(buf, pos)
def blit_tinted(surface, image, pos, tint, src_rect=None): from Numeric import add, minimum from pygame.surfarray import array3d, pixels3d if src_rect: image = image.subsurface(src_rect) buf = Surface(image.get_size(), SRCALPHA, 32) buf.blit(image, (0, 0)) src_rgb = array3d(image) buf_rgb = pixels3d(buf) buf_rgb[...] = minimum(255, add(tint, src_rgb)).astype('b') surface.blit(buf, pos)
def cut_side(self, side, radius, background): w, h = self.c.get_size() b_c_surf = self.c.copy().convert_alpha() #beach newsurf = pygame.Surface((w, h), pygame.SRCALPHA, depth=self.c.get_bitsize()).convert_alpha() newsurf.fill((0, 0, 0, 0)) n_a = surfarray.pixels_alpha(newsurf) n_rgb = surfarray.pixels3d(newsurf) s_rgb = surfarray.pixels3d(self.s) b_c_rgb = surfarray.pixels3d(b_c_surf) if "top" in side: for x in range(w): for y in range(0, 2 * radius): n_a[x][y] = 255 - get_y(y, 0, 2 * radius) n_rgb[x][y] = s_rgb[x][y] if "bottom" in side: for x in range(w): for y in range(h - 2 * radius, h): n_a[x][y] = get_y(y, h - 2 * radius, h) n_rgb[x][y] = s_rgb[x][y] if "left" in side: for y in range(h): for x in range(0, 2 * radius): n_a[x][y] = 255 - get_y(x, 0, 2 * radius) n_rgb[x][y] = s_rgb[x][y] if "right" in side: for y in range(h): for x in range(w - 2 * radius, w): n_a[x][y] = get_y(x, w - 2 * radius, w) n_rgb[x][y] = s_rgb[x][y] del n_a del n_rgb del b_c_rgb b_c_surf.unlock() newsurf.unlock() b_c_surf.blit(newsurf, (0, 0)) return b_c_surf
def draw_spectrum(self, f, x): draw_area = Surface((1, len(f)), depth=24) d = surfarray.pixels3d(draw_area) self.peak = np.maximum(np.amax(f, axis=0), self.peak) a = (255 * f / self.peak[np.newaxis, :]).astype(np.uint8) d[0, :, 1:] = a[::-1] d[0, :, 0] = a[::-1, 1] / 2 + a[::-1, 0] / 2 for m in self.markers: im = int((2 * m / self.sample_rate) * len(f)) d[0, -im, 0] = 255 del d it = int((2 * self.top_freq / self.sample_rate) * len(f)) self.surface.blit(smoothscale(draw_area.subsurface((0, len(f) - it - 1, 1, it)), (1, self.size[1])), (x, 0)) self.peak *= 2.0 ** (-1.0 / 100)
def recolor_crosshair(self, entity): """ Changes the color of the entity crosshair to that of the hive :param entity: :return: void """ new_crosshair = entity.crosshair.image.copy() arr = surfarray.pixels3d(new_crosshair) color = team_color_dict[self.team] arr[:, :, 0] = color[0] arr[:, :, 1] = color[1] arr[:, :, 2] = color[2] entity.crosshair.image = new_crosshair entity.highlighted = self.highlighted
def draw_spectrum(self, f, x): draw_area = Surface((1, len(f)), depth=24) d = surfarray.pixels3d(draw_area) self.peak = np.maximum(np.amax(f, axis=0), self.peak) a = (255 * f / self.peak[np.newaxis, :]).astype(np.uint8) d[0, :, 1:] = a[::-1] d[0, :, 0] = (a[::-1, 1] / 2 + a[::-1, 0] / 2) for m in self.markers: im = int((2 * m / self.sample_rate) * len(f)) d[0, -im, 0] = 255 del d it = int((2 * self.top_freq / self.sample_rate) * len(f)) self.surface.blit( smoothscale(draw_area.subsurface((0, len(f) - it - 1, 1, it)), (1, self.size[1])), (x, 0)) self.peak *= 2.**(-1. / 100)
def illuminate_alphacolor_except(surface, color_except, color_target, color_bulk=None, subrect=None, factor=1., fadout=2, bulk_alpha=255): """ mode : "except" means all the pixels that are not color_source. "exact" means all the pixels that are exacly color_source. Set fadout to 0 and bulk_alpha to 255 if you do not want alpha fade out. """ if not HAS_NUMPY: raise Exception("Could not use surfarray module from PyGame.\ NumPy is probably missing.") rect = surface.get_rect() newsurf = pygame.Surface(rect.size, SRCALPHA, depth=surface.get_bitsize()).convert_alpha() newsurf.blit(surface, (0, 0)) if subrect: rect = subrect arrayrgb = surfarray.pixels3d(newsurf) arraya = surfarray.pixels_alpha(newsurf) points = [] max_d = hypot(rect.w, rect.h) for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): if tuple(arrayrgb[x][y]) != color_except: points.append((x, y)) if points: for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): if not (x, y) in points: d = 1. - illuminate_dist(points, rect, x, y) / max_d d = 255 * factor * d**fadout arraya[x][y] = d arrayrgb[x][y] = color_target else: if color_bulk: arrayrgb[x][y] = color_bulk if bulk_alpha: arraya[x][y] = bulk_alpha else: functions.debug_msg("No points for illuminate alpha except") return newsurf
def _transformerPartie(self, surface, nomPnj, positionVisible, positionCarte, **p): """Applique une transformation individuellement à chaque <surface> (mobile) lors de sa pose.""" for nomTransformation in self._transformationsParties: p = self._parametresTransformations[nomTransformation] if nomTransformation == "AlphaFixe": """pixels = surfarray.pixels_alpha(surface) positionsNulles = numpy.where(pixels == 0) pixels[:,:] = p["alpha"] pixels[positionsNulles] = 0""" surface.set_alpha(None) surface.set_alpha(p["alpha"]) elif nomTransformation == "Action Joueur" and nomPnj == "Joueur": centre = positionCarte.move(-self._scrollingX, -self._scrollingY).center pygame.draw.circle(self._fenetre, (255,255,255), centre, p["rayon"], 1) elif "Rouge" in nomTransformation and nomPnj == p["nom"]: pixels = surfarray.pixels3d(surface) #On exclut la zone de pensée pixels[:,:,1:] = 0
def CreateShadow(self): if self._shadows: return self._shadows = [InterpolateToScale(surface, 1.025) for surface in self._surfaces] for shadow in self._shadows: # Make the shadow black. pixels = surfarray.pixels3d(shadow) pixels[:] = 0 # Make the shadow semi-transparent. alpha = surfarray.pixels_alpha(shadow) alpha[alpha > 0] = 150
def get_step(self): if p_name == "Darwin": next_state = pixels3d(self.screen) else: next_state = array3d(setup.SCREEN) reward = 0 score = self.state.get_score() position_x = self.state.last_x_position if position_x > self.max_posision_x: reward += (position_x - self.max_posision_x) * 2 self.max_posision_x = position_x else: reward = 0 reward = reward + score # time penalty #reward -= 0.1 #if self.keys[275] == 1: # reward += 1 ''' if self.keys[276] == 1: reward -= 1 elif self.keys[275] == 1: reward += 1 ''' if self.keys[275] == 1: reward += 1 else: reward -= 5 ''' if self.before_x < position_x: reward += position_x - self.before_x self.before_x = position_x ''' #if position_x < 70 and position_x != 0: # self.ml_done = True return (next_state, reward, self.ml_done, self.state.clear, self.max_posision_x, self.state.timeout, position_x)
def process_image(file): """Функция обрабатывает изображение и преобразует его в массив. :param file: файл-изображение. :return: сериализованный массив.""" # Получаем данные о пикселях изображения img = image.load(file) rgb = surfarray.pixels3d(img) # Ширина и высот исходного изображения WIDTH = img.get_width() HEIGHT = img.get_height() # Отношение исходных размеров к новым kx = WIDTH / SIZE ky = HEIGHT / SIZE # Вычисляем массив для изображения array = [] for x in range(SIZE): # Пиксели по горизонтали из старого изображения, которые нужно учесть # в пикселе нового изображения xs = get_pix_pos(x * kx, kx) for y in range(SIZE): r = g = b = 0 # RGB цвета в пикселе нового изображения # Пиксели по вертикали из старого изображения, которые нужно учесть # в пикселе нового изображения ys = get_pix_pos(y * ky, ky) n = 0 for x_old in xs: if x_old >= WIDTH: break for y_old in ys: if y_old >= HEIGHT: break r += rgb[x_old][y_old][0] g += rgb[x_old][y_old][1] b += rgb[x_old][y_old][2] n += 1 r = round(r / n) / NORM g = round(g / n) / NORM b = round(b / n) / NORM array.append([r, g, b]) # Сериализуем массив return pickle.dumps(array)
def runTest(self) -> None: width, height = 800, 600 screen = pygame.display.set_mode((width * 2, height)) pygame.display.set_caption("Blur5x5Array24Inplace") checker = pygame.image.load( '../Assets/background_checker.png').convert() checker = pygame.transform.smoothscale(checker, (1600, 600)) background = pygame.image.load('../Assets/I1.png').convert() background = pygame.transform.smoothscale(background, (800, 600)) background_cp = background.copy() blur5x5_array24_inplace(pixels3d(background)) # Testing wrong datatype rgba_array = numpy.zeros((800, 600, 4), numpy.float32) self.assertRaises(ValueError, blur5x5_array32, rgba_array) # Testing wrong size (depth = 4) rgba_array = numpy.zeros((800, 600, 4), numpy.int8) self.assertRaises(ValueError, blur5x5_array32, rgba_array) display(screen, checker, background_cp, background)
def runTest(self) -> None: width, height = 800, 600 screen = pygame.display.set_mode((width * 2, height)) pygame.display.set_caption("bright pass filter (bpf24)") checker = pygame.image.load( '../Assets/background_checker.png').convert() checker = pygame.transform.smoothscale(checker, (1600, 600)) background = pygame.image.load('../Assets/I1.png').convert_alpha() background = pygame.transform.smoothscale(background, (800, 600)) # array3d bpf_surface = test_bpf24_c(array3d(background), 40) self.assertRaises(OverflowError, test_bpf24_c, array3d(background), -40) self.assertRaises(OverflowError, test_bpf24_c, array3d(background), 440) # pixel3d bpf_surface = test_bpf24_c(pixels3d(background), 40) # Test a single pixel bpf_array = array3d(bpf_surface) bck_array = array3d(background) r = bck_array[100, 100, 0] g = bck_array[100, 100, 1] b = bck_array[100, 100, 2] lum = r * 0.299 + g * 0.587 + b * 0.114 # no div by zero lum must be strictly > 0 if lum > 40: c = (lum - 40) / lum self.assertEqual(bpf_array[100, 100, 0], int(r * c)) self.assertEqual(bpf_array[100, 100, 1], int(g * c)) self.assertEqual(bpf_array[100, 100, 2], int(b * c)) display(screen, checker, background, bpf_surface)
def reddened(chromograph): """ obtain a reddened version of a chromograph """ redder = chromograph.copy() arr = surfarray.pixels3d(redder) arr[:,:,0] = 255 return redder
return socket.inet_ntoa(ioctl( s.fileno(), 0x8915, pack('256s', ifname[:15]) )[20:24]) except IOError : print ("Can't find interface") def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3)) def color_surface(surface, (red, green, blue)): surface.convert_alpha() arr = surfarray.pixels3d(surface) arr[:,:,0] = red arr[:,:,1] = green arr[:,:,2] = blue def _linux_set_time(time_tuple): import ctypes import ctypes.util # /usr/include/linux/time.h: # # define CLOCK_REALTIME 0 CLOCK_REALTIME = 0 # /usr/include/time.h #
def _appliquerTransformationGlobale(self, nomTransformation, **p): """Applique la transformation globale <nomTransformation> avec le dico de paramètres <p>.""" if nomTransformation == "Alpha": surface = self._fenetre.copy() self._fenetre.fill((0,0,0)) surface.set_alpha(None) surface.set_alpha(0) surface.set_alpha(p["alpha"]) self._fenetre.blit(surface, (0,0)) if nomTransformation == "Rouge": pixels = surfarray.pixels3d(self._fenetre)[:FENETRE["longueurFenetre"], :FENETRE["largeurFenetre"]] #On exclut la zone de pensée pixels[:,:,1:] = 0 elif nomTransformation == "Noir" or nomTransformation == "NoirTransition": pixels = surfarray.pixels3d(self._fenetre)[:FENETRE["longueurFenetre"],:FENETRE["largeurFenetre"]] pixels /= p["coef"] if p["coef"] >= 12: pixels[:] = (0,0,0) elif nomTransformation == "NoirTotal": pixels = surfarray.pixels3d(self._fenetre)[:FENETRE["longueurFenetre"],:FENETRE["largeurFenetre"]] pixels[:] = (0,0,0) elif nomTransformation == "Glow": nomPNJ, c = p["nomPNJ"], p["couche"] if nomPNJ in self._pnj[c].keys(): x, y = self._pnj[c][nomPNJ].positionCarte.left - self._scrollingX, self._pnj[c][nomPNJ].positionCarte.top - self._scrollingY x1, y1, x2, y2 = x-32 if x-32 >= 0 else 0, y-32 if y-32 >= 0 else 0, x+64 if x+64 <= FENETRE["longueurFenetre"] else FENETRE["longueurFenetre"], y+64 if y+64 <= FENETRE["largeurFenetre"] else FENETRE["largeurFenetre"] #On limite les coordonnées du carré autour du cercle aux limites de la fenêtre cerclePossible = False if x1 < x2 and y1 < y2: #On évite les problèmes quand le cercle est en dehors de l'écran à l'arrière... xCentre, yCentre, (xPixels, yPixels), pixels, cerclePossible = x+16, y+16, numpy.mgrid[x1:x2, y1:y2], surfarray.pixels3d(self._fenetre)[x1:x2,y1:y2], True if cerclePossible and 0 not in pixels.shape: #...comme à l'avant distancesCarrees = (xPixels - xCentre) ** 2 + (yPixels - yCentre) ** 2 pixels[distancesCarrees <= 32 ** 2] *= 5 elif nomTransformation == "Fog": idParam = id(self._parametresTransformations[nomTransformation]) fogAlpha = p.get("alpha", 150) if self._idParametres.get(nomTransformation, False) == idParam or (self._idParametres.get(nomTransformation, False) != idParam and p.get("minorChange", False) is True): fog, tempsPrecedent = self._donneesParametres[nomTransformation]["fog"], self._donneesParametres[nomTransformation]["tempsPrecedent"] fogScrollX = self._donneesParametres[nomTransformation]["fogScrollX"] else: fog = pygame.image.load(os.path.join(DOSSIER_RESSOURCES, "fog.png")) surfarray.pixels_alpha(fog)[:] = fogAlpha self._donneesParametres[nomTransformation] = {"fog":fog, "tempsPrecedent":pygame.time.get_ticks(), "fogScrollX":0} self._idParametres[nomTransformation], tempsPrecedent = idParam, self._donneesParametres[nomTransformation]["tempsPrecedent"] fogScrollX = self._donneesParametres[nomTransformation]["fogScrollX"] if p.get("minorChange", False) is True: surfarray.pixels_alpha(fog)[:] = fogAlpha tempsActuel = pygame.time.get_ticks() avancee = ((tempsActuel - tempsPrecedent) / 1000) * VITESSE_DEFILEMENT_FOG if avancee >= 1.0: self._donneesParametres[nomTransformation]["tempsPrecedent"] = tempsActuel fogScrollX += avancee self._donneesParametres[nomTransformation]["fogScrollX"] = fogScrollX #We calculate where the junction between two scroll images will be on screen xScrollRelatif = (((self._scrollingX+fogScrollX) / FENETRE["longueurFenetre"]) - int((self._scrollingX+fogScrollX) / FENETRE["longueurFenetre"])) * FENETRE["longueurFenetre"] yScrollRelatif = ((self._scrollingY / FENETRE["largeurFenetre"]) - int(self._scrollingY / FENETRE["largeurFenetre"])) * FENETRE["largeurFenetre"] fogPositions = dict() #Four images on screen if xScrollRelatif > 0 and yScrollRelatif > 0: fogPositions[0] = Rect(xScrollRelatif, yScrollRelatif, FENETRE["longueurFenetre"]-xScrollRelatif, FENETRE["largeurFenetre"]-yScrollRelatif) fogPositions[1] = Rect(0, yScrollRelatif, xScrollRelatif, FENETRE["largeurFenetre"]-yScrollRelatif) fogPositions[2] = Rect(xScrollRelatif, 0, FENETRE["longueurFenetre"]-xScrollRelatif, yScrollRelatif) fogPositions[3] = Rect(0, 0, xScrollRelatif, yScrollRelatif) elif xScrollRelatif > 0: fogPositions[0] = Rect(xScrollRelatif, 0, FENETRE["longueurFenetre"]-xScrollRelatif, FENETRE["largeurFenetre"]) fogPositions[1] = Rect(0, 0, xScrollRelatif, FENETRE["largeurFenetre"]) elif yScrollRelatif > 0: fogPositions[0] = Rect(0, yScrollRelatif, FENETRE["longueurFenetre"], FENETRE["largeurFenetre"]-yScrollRelatif) fogPositions[2] = Rect(0, 0, FENETRE["longueurFenetre"], yScrollRelatif) else: fogPositions[0] = Rect(0,0, FENETRE["longueurFenetre"], FENETRE["largeurFenetre"]) i = 0 while i < 4: coord = (0,0) if i == 0 else (FENETRE["longueurFenetre"]-xScrollRelatif,0) if i == 1 else (0, FENETRE["largeurFenetre"]-yScrollRelatif) if i == 2 else (FENETRE["longueurFenetre"]-xScrollRelatif, FENETRE["largeurFenetre"]-yScrollRelatif) self._fenetre.blit(fog.subsurface(fogPositions[i]), coord) i += 1 while i not in fogPositions.keys() and i < 4: i += 1 elif nomTransformation == "RemplirNoir": self._fenetre.fill((0,0,0), rect=(0,0,FENETRE["longueurFenetre"],FENETRE["largeurFenetre"])) elif "SplashText" in nomTransformation: idParam = id(p) if self._idParametres.get(nomTransformation, False) == idParam: surfaceTexte = self._donneesParametres[nomTransformation] else: self._idParametres[nomTransformation] = id(p) couleurFond, police, taille = p.get("couleurFond", None), p.get("police", NOM_FICHIER_POLICE_PAR_DEFAUT), p.get("taille", TAILLE_POLICE_SPLASH_SCREEN) self._ajouterPolice(police, taille) surfaceTexte = self._polices[police][taille].render(p["texte"], p["antialias"], p["couleurTexte"], couleurFond) self._donneesParametres[nomTransformation] = surfaceTexte if p.get("position", False) is not False: position = p["position"] self._fenetre.blit(surfaceTexte, position) elif self._ecranVisible.colliderect(self._pnj[p["couche"]][p["nomPNJ"]].positionCarte) or self._jeu.carteActuelle._ecranVisible.contains(self._pnj[p["couche"]][p["nomPNJ"]].positionCarte): position = self._pnj[p["couche"]][p["nomPNJ"]].positionCarte.move(-16, -surfaceTexte.get_height()) position.move_ip(-self._scrollingX, -self._scrollingY) self._fenetre.blit(surfaceTexte, position) elif nomTransformation == "Nuit": self._fenetre.fill((0,0,0), rect=(0,0,FENETRE["longueurFenetre"],FENETRE["largeurFenetre"])) c = 0 while c < self._nombreCouches: for nomPnj in self._pnj[c]: self._afficherBlocPnj(c, nomPnj) c += 1
from pygame import surfarray, image, display import pygame pygame.init() image = image.load('img.png') resolution = (image.get_width(), image.get_height()) screen = display.set_mode(resolution) screen.blit(image,(0,0)) surfarray.use_arraytype("numpy") screenpix = surfarray.pixels3d(image) data = [] data_str = '' for y in range(resolution[1]): for x in range(resolution[0]): red = screenpix[x][y][0] green = screenpix[x][y][1] blue = screenpix[x][y][2] data.append([red / 255.0 , green / 255.0 ,blue / 255.0]) data_str += str([red / 255.0 , green / 255.0 ,blue / 255.0]) + ',' + '\n' with open('rgb.js', 'w') as f: f.write('var labels = [' + data_str + '];') #[[1,1,1],[0,0,0],...]
size = (CellSize*nSites,CellSize*nSites) # Set initial configuration state = Initialize(nSites) pygame.init() UpColor = 255, 0, 0 # red DownColor = 0, 0, 255 # blue # Get display surface screen = pygame.display.set_mode(size) pygame.display.set_caption('2D Ising Model Simulator') # Clear display screen.fill(UpColor) pygame.display.flip() # Create RGB array whose elements refer to screen pixels sptmdiag = surfarray.pixels3d(screen) # display initial dipole configuration for i in range(nSites): for j in range(nSites): if state[i][j] < 0: screen.fill(DownColor,[i*CellSize,j*CellSize,CellSize,CellSize]) t = 0 t0 = time.clock() # total execution time t_total = time.clock() # Main loop flag = 1 while flag > 0:
camera.start() for i in range(100): if camera.query_image(): # ready to take an image? break snapshot = camera.get_image() camera.stop() display.blit(snapshot,(0,0,)) pygame.display.flip() pygame.display.flip() print("Captured an image") raw_input("Press Enter to convert into opencv format") npy = surfarray.pixels3d(snapshot) ipl = adaptors.NumPy2Ipl(npy) print("Captured an image") raw_input("Press Enter to pass to cvEyeTrack to add a cross") green = opencv.CV_RGB(0,255,0) Draw_Cross(ipl,200,200,50,100,green) print("Added a cross") raw_input("Press Enter to pass to back from opencv to pygame") npy2 = adaptors.Ipl2NumPy(ipl) npy2.transpose(1,0,2) """
count = 0 break Z.append(new) count+=1 if not count: color[2] = space[count] return color pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption("Fractals") screen.fill(white) pygame.display.flip() sarr = surfarray.pixels3d(screen) Yc = 0 Xc = 0 space = N.linspace(-2, 2, size[0]-1) for Y in space: Yc+=1 for X in space: C = complex(X, Y) print Yc, ",",Xc, ": ",C color = check_mad(C, precis) print "Color: ",color sarr[Yc,Xc] = color #The surface array is odd. sarr[0] is the first coulum. Xc+=1 Xc = 0
def surf2CV(surf): """Given a surface, convert to an opencv format (cvMat) """ numpyImage = surfarray.pixels3d(surf) cvImage = adaptors.NumPy2Ipl(numpyImage.transpose(1,0,2)) return cvImage
def __init__(self, image=None): if isinstance(image, Surface): image = Image.fromarray(surfarray.pixels3d(transform.flip(transform.rotate(image, 90), False, True)), mode="RGB") self.image = image.convert(mode="RGBA") if image else None
if camera.query_image(): # ready to take an image? break snapshot = camera.get_image() camera.stop() display.blit(snapshot, ( 0, 0, )) pygame.display.flip() pygame.display.flip() print("Captured an image") raw_input("Press Enter to convert into opencv format") npy = surfarray.pixels3d(snapshot) ipl = adaptors.NumPy2Ipl(npy) print("Captured an image") raw_input("Press Enter to pass to cvEyeTrack to add a cross") green = opencv.CV_RGB(0, 255, 0) Draw_Cross(ipl, 200, 200, 50, 100, green) print("Added a cross") raw_input("Press Enter to pass to back from opencv to pygame") npy2 = adaptors.Ipl2NumPy(ipl) npy2.transpose(1, 0, 2) """ In [2]: type(npy2)