2009/02/17

PIL (Python Image Library)による画像分割

For OpenGL texture mapping, only limited size picture can be accepted such as 128x128, and 256x256. I should cut large picture (such as 1500 x 9000) into smaller pieces such as 256 x 256
for OpenGL texture mapping. In Python, I can use PIL to do this. I included PIL sample and OpenGL sample to read the small jpeg files.

OpenGLのテクスチャーは128とか256とか512という2の累乗のサイズの画像しか受け付けません。CubicVRでは普通3000 x 3000ピクセルとかの画像を上下左右前後6枚使います。(私の使う画像は6枚が縦に繋がっています) jpegで保存された大きな画像をPythonで読みだして、複数の256x256の小さな画像に切り分け、またjpegで書き出すプログラムをPIL (Python Image Library)で作ってみました。これで、いくら大きな画像でもPython/OpenGLのCubicVR Viewerに読み込むことができます。ついでにOpenGLに読み込む時のPythonのサンプルもつけます。

#6枚の正方形画像が縦につながった大きな画像をtex_size x tex_sizeの小さな画像に分割して, jpegで保存

def prep_tex (pfname):
global rc, image_x
im=Image.open(pfname)
size=im.size
image_x = size[0]
image_y = size[1]

if image_x*6 == image_y:
print "good y = 6x"
else:
print "error y != 6x"
sys.exit

rc = image_x / tex_size
rc_mod = image_x % tex_size
if rc_mod != 0:
rc = rc + 1

for face in range(6):
for y in range(rc):
for x in range(rc):
x1 = tex_size*x
x2 = x1 + tex_size
y1 = face * image_x + tex_size * y
y2 = y1 + tex_size

box = (x1, y1, x2, y2)
region = im.crop(box)
fname = '%s%d%d%d%s' % (pfname, face, y, x, ".jpg")
region.save(fname)
print (face, y, x, x1, y1, x2, y2, fname)

# 分割されたjpegファイルを読みだして、OpenGLのTextureに変換
tex_num=0
glEnable(GL_TEXTURE_2D)
texture=glGenTextures(rc*rc*6)
for face in range(6):
for y in range(rc):
for x in range(rc):
fname = '%s%d%d%d%s' % ("./pcube/sjtex", face, y, x, ".jpg")
gentex(texture[tex_num], fname)
#print 'reading texture %s %d' % (fname, tex_num)
tex_num = tex_num+1

0 件のコメント: