2016-11-23 186 views
1

Python 3.4,pygame == 1.9.2b8pygame,创建2d numpy数组的灰度

我想绘制灰度框架。 现在,下面的代码会生成蓝色,但我想在范围(0,255)中制作颜色,其中0 - 黑色。 255白色。 这怎么可能?

import pygame 
import numpy as np 
s = 300 
screen = pygame.display.set_mode((s, s)) 
screenarray = np.zeros((s,s)) 
screenarray.fill(200) 
pygame.surfarray.blit_array(screen, screenarray) 
pygame.display.flip() 
input() 
    实际上
  • 我具有更复杂的screenarray,其中在每个元件11c(0,65535)。所以我想把它转换成灰度。

非常感谢。

+0

pygame使用颜色作为三个数字(红色,绿色,蓝色),所以白色是(0,0,0),黑色是(255,255,255) – furas

回答

1

pygame的使用24位颜色三个字节(R,G,B),所以白是(0,0,0)和黑色(255,255,255)

import pygame 
import numpy as np 

SIZE = 256 

pygame.init() 
screen = pygame.display.set_mode((SIZE, SIZE)) 

screenarray = np.zeros((SIZE, SIZE, 3)) 

for x in range(SIZE): 
    screenarray[x].fill(x) 

pygame.surfarray.blit_array(screen, screenarray) 

pygame.display.flip() 

input() 

pygame.quit() 

enter image description here

0

有pygame可以将整数识别为颜色的两种方式:

  1. RGB的3元素序列,其中每个元素的范围介于0-255之间。
  2. 映射的整数值。

如果您希望能够有一个数组,其中0-255之间的每个整数代表灰度阴影,则可以使用此信息创建自己的灰度数组。您可以通过定义一个类来创建自己的数组。


第一种方法是创建一个numpy数组,每个元素是一个3元素序列。

class GreyArray(object): 

    def __init__(self, size, value=0): 
     self.array = np.zeros((size[0], size[1], 3), dtype=np.uint8) 
     self.array.fill(value) 

    def fill(self, value): 
     if 0 <= value <= 255: 
      self.array.fill(value) 

    def render(self, surface): 
     pygame.surfarray.blit_array(surface, self.array) 

创建基于映射的整数值的类可以是一个有点抽象。我不知道这些值是如何映射的,但通过快速测试,可以很容易地确定每个灰色阴影的分隔值为16843008,从0的黑色开始。

class GreyArray(object): 

    def __init__(self, size, value=0): 
     self.array = np.zeros(size, dtype=np.uint32) 
     self.array.fill(value) 

    def fill(self, value): 
     if 0 <= value <= 255: 
      self.array.fill(value * 16843008) # 16843008 is the step between every shade of gray. 

    def render(self, surface): 
     pygame.surfarray.blit_array(surface, self.array) 

简短的演示。按1-6更改灰色阴影。

import pygame 
import numpy as np 
pygame.init() 

s = 300 
screen = pygame.display.set_mode((s, s)) 

# Put one of the class definitions here! 

screen_array = GreyArray(size=(s, s)) 

while True: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      quit() 
     elif event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_1: 
       screen_array.fill(0) 
      elif event.key == pygame.K_2: 
       screen_array.fill(51) 
      elif event.key == pygame.K_3: 
       screen_array.fill(102) 
      elif event.key == pygame.K_4: 
       screen_array.fill(153) 
      elif event.key == pygame.K_5: 
       screen_array.fill(204) 
      elif event.key == pygame.K_6: 
       screen_array.fill(255) 

    screen_array.render(screen) 
    pygame.display.update()