gpt4 book ai didi

python - Pygame,从二维 numpy 数组创建灰度

转载 作者:行者123 更新时间:2023-12-01 03:32:19 25 4
gpt4 key购买 nike

Python 3.4,pygame==1.9.2b8

我想绘制灰度框架。现在,下面的代码生成蓝色,但我想在 (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,其中每个元素位于 (0,65535) 期间。所以我想将其转换为灰度。

非常感谢。

最佳答案

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()

关于python - Pygame,从二维 numpy 数组创建灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40755989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com