Esempio n. 1
0
 def main(self):
     """
     Run and time the main loop.
     """
     logging.info("Starting main video capture loop now, press 'q' to quit")
     key = hg.cvWaitKey(1)
     
     num_frames = 0
     start_time = time.time()
     
     while(key is not "q" and key != '\x1b'):
         num_frames +=1
         self.process()
         key = hg.cvWaitKey(5)
         
     total_time = float(time.time()) - float(start_time)
     
     hg.cvDestroyWindow(self.title)
     cv.cvReleaseCapture(self.camera)
     
     logging.debug("Main loop complete")
     logging.debug("Total time took %e" % total_time)
     
     logging.info("Average time per frame: %e" % (total_time/num_frames) )
     logging.info("Average frames per second: %f" % (num_frames/total_time) )
def main():
  # Initialization
  highgui.cvNamedWindow("Guardian", 1)

  signal.signal(signal.SIGINT, handler)
  # Stage
  #robot = playerc.playerc_client(None, "localhost", 6665)
  # Corobot
  robot = playerc.playerc_client(None, "corobot-w.wifi.wpi.edu", 6665)

  robot.connect()

  p2dproxy = playerc.playerc_position2d(robot, 0)
  p2dproxy.subscribe(playerc.PLAYERC_OPEN_MODE)
  p2dproxy.get_geom()

  robot.read()

  while True:
    image = highgui.cvQueryFrame(camera)
    detectObject(image)

    p2dproxy.set_cmd_vel(speed[0], 0, speed[1], 0)

    draw_gui(image)
    highgui.cvShowImage("Guardian", image)

    if highgui.cvWaitKey(20) != -1:
      break

  highgui.cvDestroyWindow("Guardian")
  p2dproxy.set_cmd_vel(0, 0, 0, 0)
    def main(self):
        """
        Run and time the main loop.
        """
        logging.info("Starting main video capture loop now, press 'q' to quit")
        key = hg.cvWaitKey(1)

        num_frames = 0
        start_time = time.time()

        while (key is not "q" and key != '\x1b'):
            num_frames += 1
            self.process()
            key = hg.cvWaitKey(5)

        total_time = float(time.time()) - float(start_time)

        hg.cvDestroyWindow(self.title)
        cv.cvReleaseCapture(self.camera)

        logging.debug("Main loop complete")
        logging.debug("Total time took %e" % total_time)

        logging.info("Average time per frame: %e" % (total_time / num_frames))
        logging.info("Average frames per second: %f" %
                     (num_frames / total_time))
def main():
    # Initialization
    highgui.cvNamedWindow("Guardian", 1)

    signal.signal(signal.SIGINT, handler)
    # Stage
    #robot = playerc.playerc_client(None, "localhost", 6665)
    # Corobot
    robot = playerc.playerc_client(None, "corobot-w.wifi.wpi.edu", 6665)

    robot.connect()

    p2dproxy = playerc.playerc_position2d(robot, 0)
    p2dproxy.subscribe(playerc.PLAYERC_OPEN_MODE)
    p2dproxy.get_geom()

    robot.read()

    while True:
        image = highgui.cvQueryFrame(camera)
        detectObject(image)

        p2dproxy.set_cmd_vel(speed[0], 0, speed[1], 0)

        draw_gui(image)
        highgui.cvShowImage("Guardian", image)

        if highgui.cvWaitKey(20) != -1:
            break

    highgui.cvDestroyWindow("Guardian")
    p2dproxy.set_cmd_vel(0, 0, 0, 0)
Esempio n. 5
0
    def __init__(self,
                 processFunction=None,
                 title="Video Capture Player",
                 show=True,
                 **argd):
        self.__dict__.update(**argd)
        super(VideoCapturePlayer, self).__init__(**argd)
        t_begin = time.time()
        self.processFunction = processFunction
        self.title = title
        self.show = show

        if self.show is True:
            self.display = hg.cvNamedWindow(self.title)

        try:
            self.camera = hg.cvCreateCameraCapture(0)
        except:
            print("Couldn't open camera device, is it connected?")
            hg.cvDestroyWindow(title)
            raise SystemExit

        # Take a frame to get props and use in testing
        self.snapshot = cv.cvCloneMat(hg.cvQueryFrame(self.camera))
        # check that we got an image, otherwise try again.
        for i in xrange(100):
            if self.snapshot is not None: break
            self.snapshot = hg.cvQueryFrame(self.camera)
Esempio n. 6
0
def main(argv):
    # Frames per second
    fps = 20
    tux_pos = 5
    tux_pos_min = 0.0
    tux_pos_max = 9.0

    try:
        opts, args = getopt.getopt(argv, "fps", ["framerate=",])
    except getopt.GetoptError:
            sys.exit(2)

    for opt, arg in opts:
            if opt in ("-fps", "--framerate"):
                fps = arg

    camera = highgui.cvCreateCameraCapture(0)

    while True:
        highgui.cvNamedWindow('Camera', 1)
        im = highgui.cvQueryFrame(camera)
        if im is None:
            break
        # mirror
        opencv.cv.cvFlip(im, None, 1)

#        positions = face.detect(im, 'haarcascade_data/haarcascade_profileface.xml')
        positions = face.detect(im, 'haarcascade_data/haarcascade_frontalface_alt2.xml')
#        if not positions:
#            positions = face.detect(im, 'haarcascade_data/haarcascade_frontalface_alt2.xml')

        # display webcam image
        highgui.cvShowImage('Camera', im)

        # Division of the screen to count as "walking" motion to trigger tux
        image_size = opencv.cvGetSize(im)
        motion_block = image_size.width / 9

        if positions:
            mp = None
            for position in positions:
                if not mp or mp['width'] > position['width']:
                    mp = position
            pos = (mp['x'] + (mp['width'] / 2)) / motion_block
            print "tux pos: %f" % tux_pos
            print "pos: %f" % pos

            if pos != tux_pos:
                if tux_pos > pos:
                    move_tux_right(tux_pos - pos)
                elif tux_pos < pos:
                    move_tux_left(pos - tux_pos)
                tux_pos = pos

        if highgui.cvWaitKey(fps) >= 0:
            highgui.cvDestroyWindow('Camera')
            sys.exit(0)
Esempio n. 7
0
File: chroma.py Progetto: bmiro/vpc
def getFilter(frameWidht, frameHeight):    
    cvNamedWindow("Filtred")
    
    cvCreateTrackbar("hmax", "Filtred", getHlsFilter('hmax'), 180, trackBarChangeHmax)
    cvCreateTrackbar("hmin", "Filtred", getHlsFilter('hmin'), 180, trackBarChangeHmin)
    #cvCreateTrackbar("lmax", "Filtred", hlsFilter['lmax'], 255, trackBarChangeLmax)
    #cvCreateTrackbar("lmin", "Filtred", hlsFilter['lmin'], 255, trackBarChangeLmin)
    cvCreateTrackbar("smax", "Filtred", getHlsFilter('smax'), 255, trackBarChangeSmax)
    cvCreateTrackbar("smin", "Filtred", getHlsFilter('smin'), 255, trackBarChangeSmin)

    cvSetMouseCallback("Filtred", mouseClick, None)
    
    frame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)
    hlsFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)
    filtredFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)

    mask = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)

    hFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    lFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    sFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    
    ThHFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    ThLFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    ThSFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    
    key = -1
    while key == -1: 
        if not cvGrabFrame(CAM):
            print "Could not grab a frame"
            exit
        frame = cvQueryFrame(CAM)
        
        cvCvtColor(frame, hlsFrame, CV_BGR2HLS)
    
        cvSplit(hlsFrame, hFrame, lFrame, sFrame, None)
        
        pixelInRange(hFrame, getHlsFilter('hmin'), getHlsFilter('hmax'), 0, 180, ThHFrame) 
        #pixelInRange(lFrame, getHlsFilter('lmin'), getHlsFilter('lmax'), 0, 255, ThLFrame)
        pixelInRange(sFrame, getHlsFilter('smin'), getHlsFilter('smax'), 0, 255, ThSFrame)
        
        cvSetZero(mask)        
        cvAnd(ThHFrame, ThSFrame, mask)
        
        cvSetZero(filtredFrame)
        
        cvCopy(frame, filtredFrame, mask)
        
        cvShowImage("Filtred", filtredFrame)

        key = cvWaitKey(10)
        if key == 'r':
            key = -1
            resetHlsFilter()
            
    cvDestroyWindow("Filtred")    
Esempio n. 8
0
File: chroma.py Progetto: bmiro/vpc
def getBackground(frameWidht, frameHeight):
    cvNamedWindow("Background")
    
    text = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)
    frame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)
    background = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)

    font = cvInitFont(CV_FONT_HERSHEY_COMPLEX, 1.0, 1.0, 0.0, 2)
    pt1 = cvPoint(50, 100)
    pt2 = cvPoint(50, 150)
    center = cvPoint(frameWidth/2, frameHeight/2)
    cvPutText(text, "Press enter, run away and wait", pt1, font, CV_RGB(150, 100, 150))
    cvPutText(text, str(delayS) + " seconds to capture background", pt2, font, CV_RGB(150, 100, 150))
    cvShowImage("Background", text)
        
    key = -1
    while key == -1:
        key = cvWaitKey(10)    
        
    like = False
    while not like:
        for i in range(delayS):
            cvZero(text)
            cvPutText(text, str(delayS-i), center, font, CV_RGB(150, 100, 150))
            cvShowImage("Background", text)
            cvWaitKey(1000)
    
        csut = camStartUpTime
        while (csut): # Stats capturing frames in order to give time to the cam to auto-adjust colors
            if not cvGrabFrame(CAM):
                print "Could not grab a frame"
                exit
            cvWaitKey(10)
            csut -= 1
        frame = cvQueryFrame(CAM)
        cvCopy(frame, background)
        
        cvCopy(frame, text)
        cvPutText(text, "Is correct? [y/n]", center, font, CV_RGB(150, 100, 150))

        cvShowImage("Background", text)
        
        key = -1
        while key != 'n' and key != 'y':
            key = cvWaitKey(10)
            if key == 'y': 
                like = True
                
    return background        
    cvDestroyWindow("Background")
Esempio n. 9
0
def recognize_face():
    try:
        argsnum=len(sys.argv)
        print "args:",argsnum
        #if(argsnum<5):
         #   print "usage:python pyfaces.py imgname dirname numofeigenfaces threshold "
          #  sys.exit(2)                
        #imgname=sys.argv[1]
        #dirname=sys.argv[2]
        #egfaces=int(sys.argv[3])
        #thrshld=float(sys.argv[4])

        capture=hg.cvCreateCameraCapture(0)
        hg.cvNamedWindow("Snapshot")
        i=0
        #time.sleep(1)
        myframe=0
        imgname='sample.png'
        dirname='images'
        egfaces=5
        thrshld=0.3
        #frame=0
        
        while 1:     
            frame=hg.cvQueryFrame(capture)
            #print type(frame)
            hg.cvShowImage("Snapshot",frame)
            key = hg.cvWaitKey(5)
            if key=='c' or key=='C':
                hg.cvDestroyWindow("Snapshot")
                hg.cvSaveImage(imgname,frame)
                global_frame=frame
                break   
                #print frame   

        #sys.exit(0)

        pyf=PyFaces(imgname,dirname,egfaces,thrshld,frame)
        #if pyfaces returns false then save this image into images folder
        hg.cvReleaseCapture(capture) 
        return pyf.getFileName()

    except Exception,detail:
        print detail
        print "usage:python pyfaces.py imgname dirname numofeigenfaces threshold "
Esempio n. 10
0
File: chroma.py Progetto: bmiro/vpc
def startChroma(background, frameWidht, frameHeight):
    #cvNamedWindow("Original")
    cvNamedWindow("Chroma")
    
    hlsFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)
    transparency = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 3)

    mask = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)

    hFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    lFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    sFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    
    ThHFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    ThLFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    ThSFrame = cvCreateImage(cvSize(frameWidth, frameHeight), IPL_DEPTH_8U, 1)
    
    key = -1
    while key == -1:
        if not cvGrabFrame(CAM):
            print "Could not grab a frame"
            exit
        frame = cvQueryFrame(CAM)
        
        cvCvtColor(frame, hlsFrame, CV_BGR2HLS)
    
        cvSplit(hlsFrame, hFrame, lFrame, sFrame, None)

        pixelInRange(hFrame, getHlsFilter('hmin'), getHlsFilter('hmax'), 0, 180, ThHFrame) 
        #pixelInRange(lFrame, getHlsFilter('lmin'), getHlsFilter('lmax'), 0, 255, ThLFrame)
        pixelInRange(sFrame, getHlsFilter('smin'), getHlsFilter('smax'), 0, 255, ThSFrame)

        cvAnd(ThHFrame, ThSFrame, mask)
               
        cvCopy(background, frame, mask)
        
        cvShowImage("Chroma", frame)

        key = cvWaitKey(10)
        
    cvDestroyWindow("Chroma")
Esempio n. 11
0
def opencvSnap(dev,size):
    """
    An example use of the "camera" taking a single picture frame using opencv's cvMat as the return method.
    """
    # First lets take a picture using opencv, and display it using opencv...
    cvWin = hg.cvNamedWindow( "Opencv Rendering and Capture", 0 )

    print("Opening device %s, with video size (%s,%s)" % (dev,size[0],size[1]))
    
    # creates the camera of the specified size and in RGB colorspace
    cam = Camera(dev, size, "RGB")
    a = cam.get_image()
    hg.cvShowImage ('Opencv Rendering and Capture', a)
    
    # close the capture stream to avoid problems later, should see the camera turn off
    hg.cvReleaseCapture(cam.capture)
    del cam
    
    # Wait for any key then clean up
    print("Press any key to continue")
    k = hg.cvWaitKey()
    hg.cvDestroyWindow("Opencv Rendering and Capture")
Esempio n. 12
0
def opencvSnap(dev, size):
    """
    An example use of the "camera" taking a single picture frame using opencv's cvMat as the return method.
    """
    # First lets take a picture using opencv, and display it using opencv...
    cvWin = hg.cvNamedWindow("Opencv Rendering and Capture", 0)

    print("Opening device %s, with video size (%s,%s)" %
          (dev, size[0], size[1]))

    # creates the camera of the specified size and in RGB colorspace
    cam = Camera(dev, size, "RGB")
    a = cam.get_image()
    hg.cvShowImage('Opencv Rendering and Capture', a)

    # close the capture stream to avoid problems later, should see the camera turn off
    hg.cvReleaseCapture(cam.capture)
    del cam

    # Wait for any key then clean up
    print("Press any key to continue")
    k = hg.cvWaitKey()
    hg.cvDestroyWindow("Opencv Rendering and Capture")
Esempio n. 13
0
    def process(self, take_new_image=True):
        """We will take a snapshot, optionally do some arbitrary process (eg in numpy/scipy)
        then display it. If a frame is given use that instead of taking a new image.
        """

        try:
            if take_new_image:
                logging.debug("capturing an image")
                self.snapshot = cv.cvCloneMat(hg.cvQueryFrame(self.camera))

            if self.processFunction is not None:
                logging.debug("Sending image to process function")
                res = self.processFunction(self.snapshot)
                logging.debug("Received result from processing function")
                assert isinstance(res, cv.CvMat), "Not CvMat"
                self.snapshot = res

            if self.show:
                hg.cvShowImage(self.title, self.snapshot)
        except Exception, e:
            # If something goes wrong make sure we close the window
            logging.error("Error in processing image: %s" % e)
            hg.cvDestroyWindow(self.title)
            raise SystemExit
Esempio n. 14
0
    def process(self, take_new_image=True):
        """We will take a snapshot, optionally do some arbitrary process (eg in numpy/scipy)
        then display it. If a frame is given use that instead of taking a new image.
        """
 
        try:
            if take_new_image:
                logging.debug("capturing an image")
                self.snapshot = cv.cvCloneMat( hg.cvQueryFrame( self.camera) )
       
            if self.processFunction is not None:
                logging.debug("Sending image to process function")
                res = self.processFunction(self.snapshot)
                logging.debug("Received result from processing function")
                assert isinstance(res,cv.CvMat), "Not CvMat"
                self.snapshot = res
                       
            if self.show:
                hg.cvShowImage( self.title, self.snapshot )
        except Exception, e:
            # If something goes wrong make sure we close the window
            logging.error("Error in processing image: %s" % e)
            hg.cvDestroyWindow(self.title)
            raise SystemExit
Esempio n. 15
0
    def __init__(self, processFunction = None, title = "Video Capture Player", show=True, **argd):
        self.__dict__.update(**argd)
        super(VideoCapturePlayer, self).__init__(**argd)
        t_begin = time.time()
        self.processFunction = processFunction
        self.title = title
        self.show = show

        if self.show is True:
            self.display = hg.cvNamedWindow(self.title)

        try:
            self.camera = hg.cvCreateCameraCapture(0)
        
            # Take a frame to get props and use in testing
            self.snapshot = cv.cvCloneMat( hg.cvQueryFrame( self.camera ) )
            # check that we got an image, otherwise try again.
            for i in xrange(20):
                if self.snapshot is not None: break
                self.snapshot = hg.cvQueryFrame( self.camera )
        except:
            print("Couldn't open camera device, is it connected?")
            hg.cvDestroyWindow(title)
            raise SystemExit
Esempio n. 16
0
            # we can now display the images
            highgui.cvShowImage('Camera', frame)
            highgui.cvShowImage('Binarisation', frameBin)
            highgui.cvShowImage('1-without background', framewithoutbg)
            highgui.cvShowImage('2-amplifie', framemul)
            highgui.cvShowImage('3-lisser-Smooth', framelisser1)
            highgui.cvShowImage('4-lisser-And', framelisser2)

            # handle events
            if image_par_image == 1:
                k = highgui.cvWaitKey(100000000)

                if k == '\x1b':
                    # user has press the ESC key, so exit
                    highgui.cvDestroyWindow("Camera")
                    highgui.cvDestroyAllWindows()
                    sys.exit(0)
                    break

                if k == 'n':
                    #image par image. util si la var image_par_image=1 ligne 42
                    None

            k = highgui.cvWaitKey(10)
            if k == 'b':
                # recupere l image en appuyant sur b
                frameGrayBg = cv.cvCloneImage(frameGray)

            if k == 's':
                # save configuration
Esempio n. 17
0
    # load image and force it to be grayscale
    image03 = highgui.cvLoadImage(filename, 0)
    if not image03:
        print "Could not load image " + filename
        sys.exit(-1)

    # Create the destination images
    image02 = cv.cvCloneImage(image03)
    image04 = cv.cvCloneImage(image03)

    # Create windows.
    highgui.cvNamedWindow("Source", 1)
    highgui.cvNamedWindow("Result", 1)

    # Show the image.
    highgui.cvShowImage("Source", image03)

    # Create toolbars. HighGUI use.
    highgui.cvCreateTrackbar("Threshold", "Result", slider_pos, 255,
                             process_image)

    process_image(1)

    #Wait for a key stroke; the same function arranges events processing
    print "Press any key to exit"
    highgui.cvWaitKey(0)

    highgui.cvDestroyWindow("Source")
    highgui.cvDestroyWindow("Result")
Esempio n. 18
0
    # load image and force it to be grayscale
    image03 = highgui.cvLoadImage(filename, 0)
    if not image03:
        print "Could not load image " + filename
        sys.exit(-1)

    # Create the destination images
    image02 = cv.cvCloneImage( image03 );
    image04 = cv.cvCloneImage( image03 );

    # Create windows.
    highgui.cvNamedWindow("Source", 1);
    highgui.cvNamedWindow("Result", 1);

    # Show the image.
    highgui.cvShowImage("Source", image03);

    # Create toolbars. HighGUI use.
    highgui.cvCreateTrackbar( "Threshold", "Result", slider_pos, 255, process_image );


    process_image( 1 );

    #Wait for a key stroke; the same function arranges events processing                
    print "Press any key to exit"
    highgui.cvWaitKey(0);

    highgui.cvDestroyWindow("Source");
    highgui.cvDestroyWindow("Result");

Esempio n. 19
0
#! /usr/bin/env python

import sys

# import the necessary things for OpenCV
from opencv import cv
from opencv import highgui

im = highgui.cvLoadImage("molecule.jpg", 1)

highgui.cvNamedWindow( "image", highgui.CV_WINDOW_AUTOSIZE)
highgui.cvShowImage( "image", im )

highgui.cvWaitKey(0)

highgui.cvDestroyWindow( "image" )