Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # OpenCV and Blender - Test1 Sept 19, 2010
- # by HartsAntler - bhartsho@yahoo.com
- # License: GNU GPL3
- # Tested with Ubuntu Lucid and Blender2.54
- '''
- Hacking - Ram Drive Workaround:
- mkdir /tmp/ramdrive
- sudo mount -t ramfs /dev/ram10 /tmp/ramdrive/
- sudo chmod 777 /tmp/ramdrive
- Getting Blender Connected:
- 0. sudo apt-get install python-opencv python-pygame python3
- 1. download posix_ipc from http://semanchuk.com/philip/posix_ipc
- 2. cd posix_ipc-0.8.1/
- 3. sudo python setup.py install
- 4. sudo python3 setup.py install
- 5. set the path to blender25 below `PATH2BLENDER`
- (blender will not respect local py3 installations? this step should be optional)
- 6. cp -Rv /usr/local/lib/python3.1/dist-packages/posix_ipc.so /<change me>/blender25/2.53/python/lib/python3.1/site-packages/.
- #6 will fail if your local python is Python 3.1.2 [GCC 4.4.3] and Blender is compiled with Python 3.1.1 [GCC 4.3.3]
- ImportError: /home/brett/pyppet2/blender25/2.53/python/lib/python3.1/site-packages/posix_ipc.so: undefined symbol: PyUnicodeUCS4_FromString
- '''
- PATH2BLENDER = 'blender25/blender'
- Size640x480_RGBA = 1228800
- import os, sys, time
- SHARED_MEMORY = '/mysharedmem' # '/tmp/something' is invlid is tmp sharedmemory has not been created
- SEMAPHORE_NAME = '/mysemaphore'
- PY_MAJOR_VERSION = sys.version_info[0]
- if PY_MAJOR_VERSION > 2: NULL_CHAR = 0
- else: NULL_CHAR = '\0'
- import multiprocessing, ctypes
- from multiprocessing import sharedctypes
- posix_ipc = None
- try: import posix_ipc
- except: print( 'posix_ipc not installed' )
- import mmap
- def shm_write(mapfile, s):
- """Writes the string s to the mapfile"""
- mapfile.seek(0)
- #s += '\0' # I append a trailing NULL in case I'm communicating with a C program.
- if PY_MAJOR_VERSION > 2: s = s.encode()
- mapfile.write(s)
- def shm_read_slowly(mapfile):
- """Reads a string from the mapfile and returns that string"""
- mapfile.seek(0)
- s = [ ]
- c = mapfile.read_byte()
- while c != NULL_CHAR:
- s.append(c)
- c = mapfile.read_byte()
- if PY_MAJOR_VERSION > 2: s = [chr(c) for c in s]
- s = ''.join(s)
- return s
- def shm_read(mapfile):
- """Reads a string from the mapfile and returns that string"""
- mapfile.seek(0)
- return mapfile.read(Size640x480_RGBA)
- '''
- if 0: # ctypes can not load libc
- import ctypes.util
- libc = ctypes.util.find_library('libc')
- print libc
- libc = ctypes.CDLL('/usr/lib/libc.a')
- print libc
- raise
- '''
- class BlenderConnection(object):
- def __init__(self):
- if posix_ipc:
- print( 'trying to open sharedmemory')
- self.shm = memory = posix_ipc.SharedMemory(SHARED_MEMORY)
- # MMap the shared memory
- self.mapfile = mmap.mmap(memory.fd, memory.size, mmap.MAP_PRIVATE) # MAP_PRIVATE=copy-on-write
- #os.close(memory.fd) # also valid
- memory.close_fd()
- print( 'sharedmem', self.mapfile)
- self.semaphore = posix_ipc.Semaphore(SEMAPHORE_NAME)
- self.bimage = im = bpy.data.images.new('_opencv_')
- im.source = 'FILE'
- im.filepath = '/tmp/ramdrive/dump.png'
- tex = bpy.data.textures[0]
- tex.type = 'IMAGE' # invalidates object, get again
- self.btexture = tex = bpy.data.textures[0]
- tex.image = im
- self.bmat = mat = bpy.data.materials[0]
- mat.use_transparency=True
- mat.alpha = .0
- mat.emit = 1.0
- mat.specular_intensity = .0
- ts = mat.texture_slots[0]
- ts.use_map_alpha=True
- scn = bpy.data.scenes[0]
- scn.game_settings.material_mode = 'GLSL'
- self.setup_blender_loop()
- def setup_blender_loop(self): # hacks like this should not have to be pulled anymore!?
- bpy.ops.screen.animation_play('EXEC_DEFAULT')
- for area in bpy.context.window.screen.areas:
- print(area.type)
- if area.type == 'VIEW_3D':
- #print('viewportshade', area.viewport_shade)
- for reg in area.regions:
- print( '\tregion: ', reg.type )
- if reg.type == 'WINDOW':
- print( 'adding callback' )
- reg.callback_add(self.loop, (area,reg), 'POST_PIXEL')
- def loop( self, area, reg ):
- if posix_ipc:
- self.semaphore.acquire()
- data = shm_read( self.mapfile )
- self.semaphore.release()
- print( len(data) )
- if self.bimage.bindcode:
- #self.bimage.gl_free()
- self.bimage.reload()
- if '--blender' in sys.argv:
- import bpy
- bc = BlenderConnection()
- else:
- import pygame
- #import Image, ImageDraw, ImageChops
- import gtk, glib, cairo, pango, gobject
- import opencv as cv
- from opencv import highgui
- cv.cvSetNumThreads(3) # 4 threads might be wasteful
- print( 'opencv threads', cv.cvGetNumThreads() )
- _colorspaces = '''
- CV_BGR2GRAY
- CV_BGR2HLS
- CV_BGR2HSV
- CV_BGR2Lab
- CV_BGR2Luv
- CV_BGR2RGB
- CV_BGR2XYZ
- CV_BGR2YCrCb
- '''
- ColorSpaces = {}
- ColorSpacesByValue = {}
- for name in _colorspaces.splitlines():
- name = name.strip()
- if name:
- value = getattr(cv,name)
- ColorSpacesByValue[ value ] = name
- ColorSpaces[ name ] = value
- BG_RED = 0.98
- BG_GREEN = 0.98
- BG_BLUE = 0.99
- BG_ALPHA = 0.0
- BG_COLOR = (BG_RED,BG_GREEN,BG_BLUE,BG_ALPHA)
- def transparent_window( win, color=BG_COLOR, decorate=False ):
- win.set_decorated( decorate )
- # Tell GTK+ that we want to draw the windows background ourself.
- # If we don't do this then GTK+ will clear the window to the
- # opaque theme default color, which isn't what we want.
- win.set_app_paintable(True)
- make_transparent( win, color )
- def expose_transparent(widget, event):
- cr = widget.window.cairo_create()
- r,g,b,a = widget._trans_color_hack
- cr.set_source_rgba(r, g, b, a) # Transparent
- # Draw the background
- cr.set_operator(cairo.OPERATOR_SOURCE)
- cr.paint()
- return False
- def make_transparent(widget, color=BG_COLOR ):
- widget._trans_color_hack = color
- # The X server sends us an expose event when the window becomes
- # visible on screen. It means we need to draw the contents. On a
- # composited desktop expose is normally only sent when the window
- # is put on the screen. On a non-composited desktop it can be
- # sent whenever the window is uncovered by another.
- #
- # The screen-changed event means the display to which we are
- # drawing changed. GTK+ supports migration of running
- # applications between X servers, which might not support the
- # same features, so we need to check each time.
- widget.connect('expose-event', expose_transparent)
- #win.connect('screen-changed', self.screen_changed)
- # To check if the display supports alpha channels, get the colormap
- screen = widget.get_screen()
- colormap = screen.get_rgba_colormap()
- # Now we have a colormap appropriate for the screen, use it
- widget.set_colormap(colormap)
- return False
- '''
- useful utils:
- cv.Ipl2NumPy
- cv.Ipl2PIL
- cv.NumPy2Ipl
- cv.NumPy2PIL
- cv.PIL2Ipl
- cv.PIL2NumPy
- notes:
- CV_ADAPTIVE_THRESH_GAUSSIAN_C
- CV_ADAPTIVE_THRESH_MEAN_C
- CV_CALIB_CB_ADAPTIVE_THRESH
- CV_THRESH_BINARY
- CV_THRESH_BINARY_INV
- #something else? CV_THRESH_MASK # adaptive only?
- #CV_THRESH_OTSU
- CV_THRESH_TOZERO
- CV_THRESH_TOZERO_INV
- CV_THRESH_TRUNC
- cvAdaptiveThreshold
- cvThreshHist
- cvThreshold
- cvAdaptiveThreshold(*args)
- cvAdaptiveThreshold(CvArr src, CvArr dst, double max_value, int adaptive_method = 0,
- int threshold_type = 0, int block_size = 3,
- double param1 = 5)
- cvThreshold(*args)
- cvThreshold(CvArr src, CvArr dst, double threshold, double max_value,
- int threshold_type) -> double
- '''
- def pygame_to_pil_img(pg_img):
- imgstr = pygame.image.tostring(pg_img, 'RGB')
- return Image.fromstring('RGB', pg_img.get_size(), imgstr)
- def pil_to_pygame_img(pil_img):
- imgstr = pil_img.tostring()
- return pygame.image.fromstring(imgstr, pil_img.size, 'RGB')
- class Trackable(object):
- def __init__(self, haar):
- self.haar = haar
- self._cv_storage = cv.cvCreateMemStorage(0)
- self.score = .0
- self.rects = []
- self.color = None
- self.grayscale = None
- # cv.cvSetImageROI( grayscale, cv.cvRect(fx, fy, fw, fh) )
- # cv.cvClearMemStorage(storage) # this invalidates the f.x, f.* attributes
- def detector( self, grayscale, scale=1 ):
- self.grayscale = grayscale
- storage = self._cv_storage
- cv.cvClearMemStorage(storage)
- # equalize histogram
- cv.cvEqualizeHist(grayscale, grayscale)
- _rects = cv.cvHaarDetectObjects(grayscale, self.haar, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, cv.cvSize(25, 25))
- rects = []
- if _rects:
- for r in _rects:
- rects.append( pygame.rect.Rect(r.x*scale, r.y*scale, r.width*scale, r.height*scale) )
- return rects
- _cfg_ubytes = 'active alpha blur athresh_block_size thresh_min thresh_max'.split()
- _cfg_ubytes += 'sobel_xorder sobel_yorder sobel_aperture'.split()
- _cfg_ubytes += 'split_red split_green split_blue'.split()
- FXtypes = 'FXsplit FXstencil FXblur FXsobel FXathresh FXthresh FXdetect'.split()
- _cfg_ubytes += FXtypes
- class LayerConfig( ctypes.Structure ):
- _fields_ = [ ('colorspace',ctypes.c_int) ]
- for tag in _cfg_ubytes: _fields_.append( (tag, ctypes.c_ubyte) )
- #for tag in _cfg_ints: _fields_.append( (tag, ctypes.c_int) )
- del tag
- class UI(object):
- def __init__(self, active, layers, rawimage):
- self.active = active # shared
- self.layers = layers # shared
- self.rawimage = rawimage
- ## gtk ##
- self.window = win = gtk.Window()
- win.set_size_request( 900, 480 )
- win.set_title( 'Harts OpenCV Blender Demo' )
- win.connect('destroy', lambda w: gtk.main_quit() )
- transparent_window( win, decorate=True )
- root = gtk.HBox(); root.set_border_width( 3 )
- win.add( root )
- #####################################
- eb = gtk.EventBox()
- root.pack_start( eb, expand=False )
- self._drawing_area = da = gtk.DrawingArea()
- da.set_size_request( 640,480 )
- da.connect('realize', self.realize)
- eb.add( da )
- make_transparent(da)
- ##################
- eb = gtk.EventBox()
- root.pack_start( eb, expand=True )
- split = gtk.VBox(); eb.add( split )
- make_transparent(split)
- header = gtk.HBox(); split.pack_start( header, expand=False )
- b = gtk.Button('open blender')
- b.connect('clicked', lambda b: os.system('%s -P %s --blender &'%(PATH2BLENDER, sys.argv[0])) )
- header.pack_start( b, expand=False )
- b = gtk.ToggleButton('[-]'); b.set_active(True)
- b.connect('toggled', lambda b: win.set_decorated( b.get_active() ) )
- header.pack_start( b, expand=False )
- #ex = gtk.Expander( 'settings' ); ex.set_expanded(False)
- #split.pack_start( ex, expand=False )
- #ex = gtk.Expander( 'adjust layers' ); ex.set_expanded(True)
- #split.pack_start( ex, expand=True)
- note = gtk.Notebook()
- note.set_tab_pos( gtk.POS_RIGHT )
- #ex.add( note )
- split.pack_start( note )
- for layer in layers:
- cspace = ColorSpacesByValue[ layer.colorspace ]
- tag = cspace.split('2')[-1]
- page = gtk.HBox()
- h = gtk.HBox()
- b = gtk.CheckButton()
- b.connect('toggled', lambda b,lay: setattr(lay,'active',bool(b.get_active())), layer)
- h.pack_start( b, expand=False )
- h.pack_start( gtk.Label(tag) )
- note.append_page( page, h )
- h.show_all()
- b.set_active( bool(layer.active) )
- col1, col2 = gtk.VBox(), gtk.VBox()
- page.pack_start( col1, expand=False )
- page.pack_start( col2, expand=True )
- fxgroups = {}
- for name in FXtypes:
- bx = gtk.VBox()
- fxgroups[ name.split('FX')[-1] ] = bx
- frame = gtk.Frame(); frame.add( bx )
- val = getattr( layer, name )
- b = gtk.CheckButton( name )
- b.set_active( bool(val) )
- b.connect('toggled', lambda b,lay,nam: setattr(lay,nam,bool(b.get_active())), layer, name)
- frame.set_label_widget( b )
- col2.pack_end( frame )
- for name in dir(layer):
- if not name.startswith('_') and name not in ['colorspace','active']+FXtypes:
- val = getattr( layer, name )
- bx = None
- for fx in fxgroups:
- if name.startswith(fx):
- bx = fxgroups[fx]
- break
- if not bx:
- adjust = gtk.Adjustment(
- value=val,
- lower=0, upper=255,
- step_incr=1 )
- adjust.connect("value_changed", lambda a,lay,nam: setattr(lay,nam,int(a.value)), layer,name)
- scale = gtk.HScale( adjust ); scale.set_value_pos(gtk.POS_RIGHT)
- scale.set_digits(0)
- frame = gtk.Frame( name )
- frame.add( scale )
- col2.pack_start( frame )
- else:
- if fx=='split':
- b = gtk.CheckButton( name )
- b.set_active( bool(getattr(layer,name)) )
- b.connect('toggled', lambda b,lay,nam: setattr(lay,nam,bool(b.get_active())), layer, name)
- bx.pack_start( b )
- else:
- upper = 255
- lower = 0
- step = 1
- if name.startswith('sobel'):
- upper = 31; lower = 1; step=2
- adjust = gtk.Adjustment(
- value=val,
- lower=lower, upper=upper,
- step_incr=step )
- adjust.connect("value_changed", lambda a,lay,nam: setattr(lay,nam,int(a.value)), layer,name)
- scale = gtk.HScale( adjust ); scale.set_value_pos(gtk.POS_RIGHT)
- scale.set_digits(0)
- row = gtk.HBox()
- row.pack_start( gtk.Label( name.split(fx)[-1].replace('_',' ') ), expand=False )
- row.pack_start( scale )
- bx.pack_start( row )
- win.show_all()
- def realize( self, da ):
- wid = da.window.xid
- os.environ['SDL_WINDOWID'] = str(wid) # child fork respects environ
- self.subprocess = p = multiprocessing.Process(target=subprocess, args=(self.active,self.layers,self.rawimage))
- p.start()
- #p.join()
- time.sleep(1)
- print( 'trying to open sharedmemory')
- #self.shm = memory = posix_ipc.SharedMemory(SHARED_MEMORY)
- # MMap the shared memory
- #self.mapfile = mmap.mmap(memory.fd, memory.size, mmap.MAP_PRIVATE)
- #os.close(memory.fd) # also valid
- #memory.close_fd()
- #print( 'sharedmem', self.mapfile)
- #self.semaphore = posix_ipc.Semaphore(SEMAPHORE_NAME)
- #glib.timeout_add( 300, self.check_shm )
- def check_shm( self ):
- self.semaphore.acquire()
- data = shm_read( self.mapfile )
- self.semaphore.release()
- #print len(data)
- #print self.rawimage[0] # ctypes is slightly faster or slower than posix_ipc?
- return True
- class Camera(object):
- try: ## opencv haar detect is multithreaded! ##
- DO_HAAR = True
- FaceCascade = cv.cvLoadHaarClassifierCascade('haarcascades/haarcascade_frontalface_alt.xml', cv.cvSize(1,1))
- EyesCascade = cv.cvLoadHaarClassifierCascade('haarcascades/haarcascade_eye.xml', cv.cvSize(1,1))
- except:
- print( 'download opencv latest source code, and copy the haarcascades folder to here')
- DO_HAAR = False
- def exit(self):
- self.mapfile.close()
- # I could call memory.unlink() here but in order to demonstrate
- # unlinking at the module level I'll do it that way.
- posix_ipc.unlink_shared_memory( SHARED_MEMORY )
- print( 'subprocess clean exit')
- def __init__(self, layers, rawimage):
- self.layers = layers
- self.rawimage = rawimage
- self.shm = memory = posix_ipc.SharedMemory(SHARED_MEMORY, posix_ipc.O_CREAT, size=Size640x480_RGBA)
- self.mapfile = mmap.mmap(memory.fd, memory.size, mmap.ACCESS_WRITE)#, mmap.MAP_PRIVATE)
- memory.close_fd()
- print( 'sharedmemory created', self.mapfile)
- self.semaphore = posix_ipc.Semaphore(SEMAPHORE_NAME, posix_ipc.O_CREAT)
- pygame.display.init()
- SSBACKEND = pygame.transform.get_smoothscale_backend()
- if SSBACKEND == 'GENERIC':
- try: pygame.transform.set_smoothscale_backend( 'SSE' ); SSBACKEND = 'SSE'
- except: print( 'SSE backend not available')
- print( 'smooth scale backend', SSBACKEND)
- self.prevfaces = None
- self.active = True
- self.index = 0
- for arg in sys.argv:
- if arg.startswith('camera='): self.index = int(arg.split('=')[-1]); break
- self.camera_pointer = highgui.cvCreateCameraCapture(self.index) # this is the old swig bindings ubuntu lucid works fine
- # HIGHGUI ERROR: V4L: setting property #16 is not supported
- #highgui.cvSetCaptureProperty( self.camera_pointer, highgui.CV_CAP_PROP_CONVERT_RGB, True )
- ## default color space is BGR - linux ##
- self.resize_capture( 640, 480 )
- self.resize_output( 640, 480 )
- if self.DO_HAAR:
- self.track_face = Trackable( self.FaceCascade )
- def resize_capture( self, x,y ):
- self.cwidth = x
- self.cheight = y
- highgui.cvSetCaptureProperty( self.camera_pointer, highgui.CV_CAP_PROP_FRAME_WIDTH, self.cwidth )
- highgui.cvSetCaptureProperty( self.camera_pointer, highgui.CV_CAP_PROP_FRAME_HEIGHT, self.cheight )
- highgui.cvSetCaptureProperty( self.camera_pointer, highgui.CV_CAP_PROP_FPS, 30 )
- self._rgb8 = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 3)
- self._rgb32 = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_32F, 3)
- self._gray8 = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 1)
- self._gray32 = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_32F, 1)
- self._R = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 1)
- self._G = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 1)
- self._B = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 1)
- self._A = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 1)
- def resize_output( self, x, y ):
- self.owidth = x
- self.oheight = y
- pygame.display.set_mode((x,y), 0, 32 ) # size, flags, depth
- self.screen = pygame.display.get_surface()
- def loop(self):
- self.semaphore.release()
- ## BGR - linux
- _frame = highgui.cvQueryFrame(self.camera_pointer) # grabFrame returns 1?
- if not _frame: print( 'lost connection to webcam?')
- self.screen.fill( (0,0,0,0) )
- surf = self.screen.copy()
- surf.fill( (0,0,255) )
- surf.set_alpha(255)
- stencil = []
- ## pre allocated ##
- _rgb8 = self._rgb8
- _rgb32 = self._rgb32
- _gray8 = self._gray8
- _gray32 = self._gray32
- for layer in self.layers:
- if layer.active:
- a = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 3)
- cv.cvCvtColor(_frame, a, layer.colorspace)
- #print 'colorspaced converted'
- ## FX
- if layer.FXsplit:
- _a = cv.cvCreateImage((self.cwidth,self.cheight), cv.IPL_DEPTH_8U, 4)
- cv.cvCvtColor(a, _a, cv.CV_RGB2RGBA)
- cv.cvSplit( _a, self._R, self._G, self._B, self._A )
- if layer.split_red: a = self._R
- elif layer.split_green: a = self._G
- elif layer.split_blue: a = self._B
- if layer.FXblur: # blur before threshing
- blur = layer.blur
- if blur < 1: blur = 1
- cv.cvSmooth( a, a, cv.CV_BLUR, blur )
- if layer.FXsobel and layer.sobel_aperture % 2 and layer.sobel_aperture < 32:
- if layer.sobel_xorder < layer.sobel_aperture and layer.sobel_yorder < layer.sobel_aperture:
- if a.nChannels == 1:
- cv.cvSobel( a, _gray32, layer.sobel_xorder, layer.sobel_yorder, layer.sobel_aperture ) #xorder, yorder, aperture
- cv.cvConvert( _gray32, a )#; cv.cvCvtColor(_sobel8, _sobel, cv.CV_GRAY2RGB)
- else:
- cv.cvSobel( a, _rgb32, layer.sobel_xorder, layer.sobel_yorder, layer.sobel_aperture ) #xorder, yorder, aperture
- cv.cvConvert( _rgb32, a )#; cv.cvCvtColor(_sobel8, _sobel, cv.CV_GRAY2RGB)
- if layer.FXthresh:
- cv.cvThreshold( a, a, layer.thresh_min, layer.thresh_max, cv.CV_THRESH_BINARY )
- if layer.FXathresh:
- blocksize = layer.athresh_block_size
- if blocksize <= 2: blocksize = 3
- if blocksize % 2 != 1: blocksize += 1
- if a.nChannels == 1:
- cv.cvAdaptiveThreshold(a, a, 255, cv.CV_ADAPTIVE_THRESH_MEAN_C, cv.CV_THRESH_BINARY, blocksize )
- else:
- cv.cvCvtColor(a, _gray8, cv.CV_RGB2GRAY)
- cv.cvAdaptiveThreshold(_gray8, _gray8, 255, cv.CV_ADAPTIVE_THRESH_MEAN_C, cv.CV_THRESH_BINARY, blocksize )
- cv.cvCvtColor(_gray8, a, cv.CV_GRAY2RGB)
- if a.nChannels == 1:
- cv.cvCvtColor(a, _rgb8, cv.CV_GRAY2RGB)
- a = _rgb8
- ## pygame
- b = pygame.image.frombuffer(a.imageData, (self.cwidth,self.cheight), 'RGB')
- b.set_alpha( layer.alpha )
- if layer.FXstencil: stencil.append( b )
- surf.blit(b, (0,0))
- self.screen.lock()
- array = pygame.surfarray.pixels_alpha(self.screen)
- if stencil:
- stencil = pygame.transform.average_surfaces( stencil )
- alpha = pygame.surfarray.pixels3d( stencil )
- array[:] = alpha[:,:,0]
- del alpha
- else: array[:] = 255 # values higher than 256 are additive!
- del array
- self.screen.unlock()
- self.screen.blit( surf, (0,0) )
- #data = pygame.image.tostring(self.screen, 'RGBA')
- pygame.display.flip()
- #self.rawimage.value = data
- #self.semaphore.acquire() # waiting for Blender to update to python 3.1.2 and support directly setting a RGBA buffer
- #shm_write( self.mapfile, data )
- #self.semaphore.release()
- # this is an ugly hack #
- #tmp = pygame.transform.scale( self.screen, (320,240) )
- os.system('mv /tmp/ramdrive/_dump.png /tmp/ramdrive/dump.png') # atomic
- pygame.image.save(self.screen, '/tmp/ramdrive/_dump.png')
- return self.active
- def subprocess( active, layers, rawimage ):
- cam = Camera( layers, rawimage )
- while active.value: cam.loop()
- cam.exit()
- if __name__ == '__main__' and '--blender' not in sys.argv:
- #CV_BGR2HLS
- #CV_BGR2Luv
- #CV_BGR2XYZ
- _default_spaces = [
- (cv.CV_BGR2RGB,),
- (cv.CV_BGR2HSV,),
- (cv.CV_BGR2Lab,),
- (cv.CV_BGR2YCrCb,),
- ]
- active = sharedctypes.Value('i', 1, lock=False)
- rawimage = sharedctypes.Array( ctypes.c_char, Size640x480_RGBA, lock=True )
- layers = sharedctypes.Array( LayerConfig, _default_spaces, lock=True )
- for layer in layers:
- layer.alpha = 32
- layer.thresh_min = 32
- layer.thresh_max = 200
- layer.blur = 2
- layer.athresh_block_size = 3
- layer.sobel_xorder = 1
- layer.sobel_yorder = 1
- layer.sobel_aperture = 5
- layers[0].active = 1
- layers[0].alpha = 128
- gui = UI( active, layers, rawimage )
- gtk.main()
- gui.active.value = 0
- print( 'waiting for child to exit')
- time.sleep(1)
- gui.subprocess.join()
- print( 'main process exit')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement