使用pygame/pyglet从数组重建图像时颜色不正确
我写了一个程序,使用numpy和Image(PIL)库来把一张图片读取成一堆矩阵,然后用pyglet(和opengl)来重建这张图片。
下面是使用pyglet的代码:
import Image
import numpy
import window
import sys
import pyglet
import random
a=numpy.asarray(Image.open(sys.argv[1]))
h,w= a.shape[0],a.shape[1]
s=a[0]
print s.shape
#######################################
def display():
x_a=0;y_a=h
for page in a:
for array in page:
j=array[2]
k=array[1]
l=array[0]
pyglet.gl.glColor3f(l,j,k)
pyglet.gl.glVertex2i(x_a,y_a)
x_a+=1
y_a-=1
x_a=0
######################################33
def on_draw(self):
global w,h
self.clear
pyglet.gl.glClear(pyglet.gl.GL_COLOR_BUFFER_BIT)
pyglet.gl.glBegin(pyglet.gl.GL_POINTS)
display()
pyglet.gl.glEnd()
pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot.png')
window.win.on_draw=on_draw
#######################################
u=window.win(w,h)
pyglet.app.run()
这是修改过的代码,使用pygame库(没有使用opengl)
import pygame
import numpy
import Image
import sys
from pygame import gfxdraw
color=(255,255,255)
a=numpy.asarray(Image.open(sys.argv[1]))
h,w=a.shape[0],a.shape[1]
pygame.init()
screen = pygame.display.set_mode((w,h))
def uu():
y_a=0
for page in a:
x_a=0
for array in page:
co=(array[0],array[1],array[2])
pygame.gfxdraw.pixel(screen,x_a,y_a,co)
x_a+=1
y_a+=1
uu()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
这是pyglet和pygame的结果对比:
所以我想问的是……为什么会有问题?是我用opengl逐个像素绘制图片的方式有问题,还是有其他我现在还不太明白的地方?
1 个回答
1
Pygame.Color
这个函数需要的颜色值是整数,范围在0到255之间,而 pyglet.gl.glColor3f
这个函数需要的颜色值是浮点数,范围在0.0到1.0之间。为了让它们能互相兼容,你可以进行这样的转换来解决你的问题:
j=array[0] / 255.0
k=array[1] / 255.0
l=array[2] / 255.0
pyglet.gl.glColor3f(j,k,l)