PyKinect と Pygame で深度画像を視覚化するために、BitBucket アカウントにスニペットを作成しました。コードは次のとおりです。
import thread
import pygame
from pykinect import nui
DEPTH_WINSIZE = 320,240
screen_lock = thread.allocate()
screen = None
tmp_s = pygame.Surface(DEPTH_WINSIZE, 0, 16)
def depth_frame_ready(frame):
with screen_lock:
frame.image.copy_bits(tmp_s._pixels_address)
arr2d = (pygame.surfarray.pixels2d(tmp_s) >> 7) & 255
pygame.surfarray.blit_array(screen, arr2d)
pygame.display.update()
def main():
"""Initialize and run the game."""
pygame.init()
# Initialize PyGame
global screen
screen = pygame.display.set_mode(DEPTH_WINSIZE, 0, 8)
screen.set_palette(tuple([(i, i, i) for i in range(256)]))
pygame.display.set_caption('PyKinect Depth Map Example')
with nui.Runtime() as kinect:
kinect.depth_frame_ready += depth_frame_ready
kinect.depth_stream.open(nui.ImageStreamType.Depth, 2, nui.ImageResolution.Resolution320x240, nui.ImageType.Depth)
# Main game loop
while True:
event = pygame.event.wait()
if event.type == pygame.QUIT:
break
if __name__ == '__main__':
main()
EDIT : 上記のコードは、深度データを 8 ビット表現に変換する方法を示しています (グレースケール イメージとして簡単に描画できるようにするため)。ただし、実際の深度データを使用する場合は、それらがどのように構造化されているかを知る必要があります。
Microsoft Kinect SDK (PyKinect のベース) を使用すると、1 つの深度ピクセルが 16 ビットで構成されます。重要度の低い 3 つのビットはプレーヤー インデックスを表しますが、最も重要なビットの意味はよくわかりません... しかし、最後の 3 ビットと最初のビットを削除する必要があるとしましょう。たとえば、これは各ピクセルに対して行う必要があることの例です (この質問から取得):
0 1 1 0 0 0 1 0 0 0 1 1 1 0 0 0 - 16 bits number
0 1 1 0 0 0 1 0 0 0 1 1 1 - 13 bits number
1 1 0 0 0 1 0 0 0 1 1 1 - 12 bits number
arr2d
上記の操作 (最後の 3 ビットと最初のビットを削除する) は、配列に対する 2 つのビット単位の操作で実装できます。これは NumPy 配列であるため、次のように進めることができます。
def depth_frame_ready(frame):
frame.image.copy_bits(tmp_s._pixels_address)
arr2d = (pygame.surfarray.pixels2d(tmp_s) >> 3) & 4095
# arr2d[x,y] is the actual depth measured in mm at (x,y)
次に、このデータを表示する必要があるため、おそらく 8 ビット表現が必要になります。それを取得するには:
arr2d >>= 4