-
Notifications
You must be signed in to change notification settings - Fork 0
/
pygpu_test.py
122 lines (93 loc) · 2.75 KB
/
pygpu_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import sys
try:
import numpy
except:
print """Unable to import numpy.
You need to install numpy (numpy.sf.net) in order to use PyGPU!"""
sys.exit(1)
try:
import pygame
from pygame.locals import *
except:
print """Unable to import pygame.
You need to install pygame (www.pygame.org) in order to use PyGPU!"""
sys.exit(1)
try:
from pyglew import *
except:
print """Unable to import pyglew.
You need to install PyGLEW (www.cs.lth.se/~calle/pygpu/) in order to use PyGPU!"""
sys.exit(1)
try:
import Cg
except:
print """Unable to import pycg.
You need to install PyCG (www.cs.lth.se/~calle/pygpu/) in order to use PyGPU!"""
sys.exit(1)
try:
import PIL.Image
except:
print """Unable to import PIL.
You need to install Python Imaging Library (http://www.pythonware.com/products/pil/)!"""
sys.exit(1)
pygame.display.init()
surface = pygame.display.set_mode((512,512), OPENGL|DOUBLEBUF)
glewInit()
try:
from pygpu import *
from pygpu.functions import float2
from pygpu.types import *
except:
print """Unable to import pygpu.
You need to install PyGPU (www.cs.lth.se/~calle/pygpu/)!"""
sys.exit(1)
initPyGPU()
@gpu(size = lambda *args: (512,512))
def square(p=Position):
x,y = p
if (128.0 < x and x < 384.0) and\
(128.0 < y and y < 384.0):
res = float3(1,1,1)
else:
res = float3(0,0,0)
return res
def offsets(kernel):
n,m = numpy.shape(kernel)
assert (n%2) == 1
assert (m%2) == 1
cx,cy = int(numpy.floor(n/2)),int(numpy.floor(m/2))
yStart,yEnd = cy-m+1,m-cy
xStart,xEnd = cx-n+1,n-cx
return [numpy.array([i,j])
for j in reversed(range(yStart, yEnd))
for i in range(xStart, xEnd)]
@gpu
def convolve(im=RGBImage, p=Position):
kernel = numpy.array([[-1,-2,-1],
[0,0,0],
[1,2,1]])
return sum([w*im(p+o) for w,o in zip(numpy.ravel(kernel),
offsets(kernel))])**2
@gpu
def smooth(im=RGBImage, p=Position):
kernel = numpy.array([[1,1,1],
[1,1,1],
[1,1,1]])
return (1.0/9.0)*sum([w*im(p+o) for w,o in zip(numpy.ravel(kernel),
offsets(kernel))])
glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, 512, 0, 512, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
image = square()
while True:
#check for quit'n events
event = pygame.event.poll()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
break
glClear(GL_COLOR_BUFFER_BIT)
image = smooth(image)
image.show()
pygame.display.flip()