2016-11-23 187 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()