Ejemplo n.º 1
0
def TrackFile(anim):
    tracks = cvb.Tracks()
    capture = cv.CreateFileCapture(anim)
    cv.GrabFrame(capture)
    img = cv.RetrieveFrame(capture)
    frame = cv.CreateImage(cv.GetSize(img), img.depth, img.nChannels)
    cnt = 1
    while cv.GrabFrame(capture):
        # Capture Frames
        img = cv.RetrieveFrame(capture)
        cv.ResetImageROI(frame)
        cv.ConvertScale(img, frame, 1, 0)
        cv.Threshold(frame, frame, 100, 200, cv.CV_THRESH_BINARY)
        #rct=cv.Rectangle(0, 25, 383, 287)
        cv.SetImageROI(frame, (0, 25, 383, 287))
        chB = cv.CreateImage(cv.GetSize(frame), 8, 1)
        cv.Split(frame, chB, None, None, None)
        labelImg = cv.CreateImage(cv.GetSize(frame), cvb.IPL_DEPTH_LABEL, 1)

        # Get Blobs and try Update Tracks
        blobs = cvb.Blobs()
        result = cvb.Label(chB, labelImg, blobs)
        cvb.FilterByArea(blobs, 500, 1000)

        # Trys are implemented here just to ensure crashes don't happen when blobs are not present
        try:
            print type(blobs.items()[0][1])
        except:
            pass
        cvb.UpdateTracks(blobs, tracks, 5., 10, 0)
        try:
            print type(blobs.items()[0][1])
        except:
            pass
        try:
            print type(tracks.items()[0][1])
        except:
            pass
        imgOut = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3)
        cv.Zero(imgOut)
        cvb.RenderBlobs(
            labelImg, blobs, frame, imgOut, cvb.CV_BLOB_RENDER_COLOR
            | cvb.CV_BLOB_RENDER_CENTROID | cvb.CV_BLOB_RENDER_BOUNDING_BOX)

        # Save images to see what's blobs are getting out.
        cnt = cnt + 1
        print cnt  #
        cv.SaveImage('blobs' + str(cnt) + '.png', imgOut)

    return tracks, blobs
    def get_image(self):
        """
        Retrieve an image of the correct type from the Kinect, depending on the
        type that was passed to the constructor.

        Since the classes share a OpenNI camera instance, only obtain the image
        at the set update frequency.
        """
        global NI_grabtime
        global NI_camera

        if time.time() > NI_grabtime + self.grab_interval:
            cv.GrabFrame(NI_camera)
            NI_grabtime = time.time()

        if self.img_type == "depth":
            depth = cv.RetrieveFrame(NI_camera, cv.CV_CAP_OPENNI_DEPTH_MAP)
            temp = cv.CreateImage(cv.GetSize(depth), cv.IPL_DEPTH_8U, 1)
            cv.ConvertScale(depth, temp, 0.0625, 0.0)


#            temp = doUsefulConvert8(cv2array(depth))
        elif self.img_type == "rgb":
            temp = cv.RetrieveFrame(NI_camera, cv.CV_CAP_OPENNI_BGR_IMAGE)
        elif self.img_type == "pcl":
            temp = cv.RetrieveFrame(NI_camera,
                                    cv.CV_CAP_OPENNI_POINT_CLOUD_MAP)

        if temp == None:
            raise Exception("Unable to start Kinect, check connection")
        return temp
Ejemplo n.º 3
0
 def run(self):
     global _camera, lock
     while self.running:
         lock.acquire()
         try:
             cv.GrabFrame(cam)
         finally:
             lock.release()
Ejemplo n.º 4
0
 def ar_video_for_ui(self):
     cap = cv.CaptureFromCAM(0)
     if not cap:
         sys.stdout.write("failed CaptureFromCAM")
     while True:
         if not cv.GrabFrame(cap):
             break
         frame = cv.RetrieveFrame(cap)
         sys.stdout.write(frame.tostring())
Ejemplo n.º 5
0
def main():

    tree = utils.open_project(sys.argv)
    if tree == None:
        return

    try:
        os.mkdir(OUTPUT_DIR)
    except OSError:
        pass

    movie = tree.getroot()
    file_path = movie.attrib["path"]
    #fps = float( movie.attrib["fps"] )

    cap = cv.CreateFileCapture(file_path)
    cv.QueryFrame(cap)

    # skip frames in the beginning, if neccessary
    start_frame = int(movie.attrib["start_frame"])
    for i in range(start_frame):
        cv.QueryFrame(cap)

    end_frame = int(movie.attrib["end_frame"])
    every_nth_frame = int((end_frame - start_frame) / 100)
    print "every", every_nth_frame, "frames"
    #print "=", every_nth_frame / fps, "sec"
    frame = start_frame
    counter = 1

    while 1:
        print counter
        img = cv.QueryFrame(cap)
        if not img or frame > end_frame:
            break

        img_small = cv.CreateImage(
            (WIDTH, int(img.height * float(WIDTH) / img.width)),
            cv.IPL_DEPTH_8U, 3)
        cv.Resize(img, img_small, cv.CV_INTER_CUBIC)

        cv.SaveImage(os.path.join(OUTPUT_DIR, "still_%07d.jpg" % (frame)),
                     img_small)

        for i in range(every_nth_frame - 1):
            cv.GrabFrame(cap)

        frame += every_nth_frame
        counter += 1

    #raw_input("- done -")
    return
Ejemplo n.º 6
0
 def dequeue(self):
     # flush
     cv.GrabFrame(self.cam)
     im = cv.RetrieveFrame(self.cam)
     #cv.Flip(im, None, 1)
     img = cv.CreateImage(cv.GetSize(im), 8, 1)
     cv.CvtColor(im, img, cv.CV_BGR2GRAY)
     im = img
     a = np.fromstring(im.tostring(),
             dtype=self.depth2dtype[im.depth],
             count=im.width*im.height*im.nChannels)
     a.shape = (im.height, im.width, im.nChannels)
     return a[:, :, 0]
Ejemplo n.º 7
0
 def run(self):
     global _camera, lock
     while self.running:
         """
         I'm using a lock to use the resource uninterrupted.
         Currently variable, where camera image is saved, can be called in two threads,
         which can make one of them crash.
         Lock is the simplest way of avoiding crashing when using a shared resource
         """
         lock.acquire()
         try:
             cv.GrabFrame(_camera)
             print "Frame grabbed"
         finally:
             lock.release()
Ejemplo n.º 8
0
def camera_capture():

    # /dev/video0
    c = cv.CaptureFromCAM(0)
    #assert type(c) ==  "cv.Capture"

    # or use QueryFrame. It's the same
    cv.GrabFrame(c)
    image = cv.RetrieveFrame(c)
    #image = cv.QueryFrame(c)
    assert image != None

    dst = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_16S, 3)
    #im = cv.CloneImage(image)
    laplace = cv.Laplace(image, dst)
    cv.SaveImage("my-camera.png", dst)

    print cv.GetCaptureProperty(c, cv.CV_CAP_PROP_FRAME_HEIGHT)
def load_video_clip(video_file, start_frame=0, end_frame=None, verbose=False):
    """Loads frames from a video_clip

    Args:
        video_file: path of the video file
        start_frame: first frame to be loaded
        end_frame: last frame to be loaded

    Returns:
        A (#frames)x(height)x(width)x(#channels) NumPy array containing the
        video clip
    """
    if not os.path.exists(video_file):
        raise IOError, 'File "%s" does not exist!' % video_file
    capture = cv.CaptureFromFile(video_file)
    if not end_frame:
        end_frame = int(
            cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT))
    else:
        end_frame = int(
            min(end_frame,
                cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT)))
    width = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH)
    height = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT)
    if verbose:
        print "end_frame: %d" % end_frame
        print "clip has %d frames" % int(
            cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT))
    for _ in range(start_frame):  # frames start with 1 in annotation files
        cv.GrabFrame(capture)
    frames = np.zeros((end_frame - start_frame - 2, height, width),
                      dtype=np.uint8)
    for i in range(end_frame - start_frame -
                   2):  # end_frame = last action frame
        img = cv.QueryFrame(capture)
        if img is None:
            continue
        tmp = cv.CreateImage(cv.GetSize(img), 8, 1)
        cv.CvtColor(img, tmp, cv.CV_BGR2GRAY)
        frames[i, :] = np.asarray(cv.GetMat(tmp))
    return np.array(frames)
Ejemplo n.º 10
0
#!/usr/bin/python
import cv

video = cv.CaptureFromFile(
    "rtsp://admin:@192.168.0.19/user=admin&password=&channel=1&stream=0.sdp?")
cv.NamedWindow("IP Camera", cv.CV_WINDOW_AUTOSIZE)
#contador = 1
while True:
    #  img = cv.QueryFrame(video)
    #  cv.SaveImage("/var/www/html/teste.jpg",img)
    cv.GrabFrame(video)
    frame = cv.RetrieveFrame(video)
    cv.ShowImage("IP Camera", frame)
    cv.WaitKey(150)
#   print contador
#   contador = contador + 1
Ejemplo n.º 11
0
#speed = [1, 1]
#black = 0, 0, 0

#print os.path.isfile('/dev/video0')
#print os.path.exists('/dev/video0')
if os.path.exists('/dev/video0') ==False:
    print "no video0,exit"
    sys.exit(2)

try:
   cam = cv.CreateCameraCapture(0)
   cv.SetCaptureProperty(cam,cv.CV_CAP_PROP_FRAME_WIDTH, 640)
   cv.SetCaptureProperty(cam,cv.CV_CAP_PROP_FRAME_HEIGHT, 480);
except:
   print "system error,exit"
   sys.exit(1)

k=0
t = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
filename = '%s.jpg' %(t)
while 1:
    k += 1
    if k > 8: break
    try:
        cv.GrabFrame(cam)
        img = cv.RetrieveFrame(cam)
        cv.SaveImage(filename, img)
    except:
        pass
    cv.WaitKey(1500)
Ejemplo n.º 12
0
def main():
    cv.NamedWindow('frame', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('frame', 10, 10)
    cv.NamedWindow('edges', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('edges', 600, 10)

    parser = OptionParser()
    parser.add_option('-s',
                      '--seek',
                      action='store',
                      type='int',
                      dest='seek',
                      default=0)
    parser.add_option('-i',
                      '--image',
                      action='store_true',
                      dest='image',
                      default=False)
    parser.add_option('-v',
                      '--verbose',
                      action='store_true',
                      dest='verbose',
                      default=False)
    options, args = parser.parse_args()

    global verbose
    verbose = options.verbose

    if options.image:
        # Use image
        frame = cv.LoadImage(args[0])
        if frame is None:
            print 'Error loading image %s' % args[0]
            return
        find_lines(frame)

        # Pause for key press
        while True:
            k = cv.WaitKey(33)
            if k == ord('q'):
                break
    else:
        if len(args) > 0:
            # Use video
            cam = cv.CaptureFromFile(args[0])
            if cam is None:
                print 'Error opening file'
                return
        else:
            # Use webcam
            cam = cv.CreateCameraCapture(1)
            if cam is None:
                print 'Error opening camera'
                return

        # Seek to initial position by discarding frames
        for i in range(options.seek):
            cv.GrabFrame(cam)

        while True:
            frame = cv.QueryFrame(cam)
            if frame is None:
                print 'End of video'
                break
            find_lines(frame)

            k = cv.WaitKey(10)
            if k == ord('q'):
                break
        cv.ReleaseCapture(cam)
Ejemplo n.º 13
0
    def getCoordinates(self, target="ball", debug=False):
        t = time.time()
        """
        This function will return the best coordinates found by thresholding the received image
        by the chosen threshold.
        """
        """Get the latest frame from the camera"""
        global cam, lock
        lock.acquire()
        try:
            cv.GrabFrame(cam)
            frame = cv.RetrieveFrame(cam)
        finally:
            lock.release()
        """Initialize the coordinates to -1, which means that the object is not found"""
        x = -1
        y = -1
        """Prepair image for thresholding"""
        #cv.Smooth(thresholded_frame, thresholded_frame, cv.CV_GAUSSIAN, 5, 5)
        cv.Smooth(frame, frame, cv.CV_BLUR, 3)
        cv.CvtColor(frame, self.hsv_frame, cv.CV_BGR2HSV)
        """Threshold the image according to the chosen thresholds"""
        if target == "ball":
            cv.InRangeS(self.hsv_frame, self.ball_threshold_low,
                        self.ball_threshold_high, self.thresholded_frame)
        elif target == "blue gate":
            cv.InRangeS(self.hsv_frame, self.blue_gate_threshold_low,
                        self.blue_gate_threshold_high, self.thresholded_frame)
        elif target == "yellow gate":
            cv.InRangeS(self.hsv_frame, self.yellow_gate_threshold_low,
                        self.yellow_gate_threshold_high,
                        self.thresholded_frame)
        elif target == "black":
            cv.InRangeS(self.hsv_frame, self.black_threshold_low,
                        self.black_threshold_high, self.thresholded_frame)
        elif target == "white":
            cv.InRangeS(self.hsv_frame, self.white_threshold_low,
                        self.white_threshold_high, self.thresholded_frame)

        cv.InRangeS(self.hsv_frame, self.green_threshold_low,
                    self.green_threshold_high, self.thresholded_field)
        """Now use some function to find the object"""
        blobs_image = SimpleCV.Image(self.thresholded_frame)
        field_image = SimpleCV.Image(self.thresholded_field)

        blobs = blobs_image.findBlobs(minsize=2)
        if blobs:
            if target == "ball":
                for i in range(len(blobs)):
                    i = len(blobs) - 1 - i
                    pos_x = blobs[i].maxX()
                    pos_y = blobs[i].maxY()
                    on_field = False
                    for py in range(0, pos_y):
                        if field_image.getPixel(pos_x, py) == (255, 255, 255):
                            on_field = True
                            break
                    if on_field:
                        x, y = pos_x, pos_y
                        break
            else:
                x, y = blobs[-1].coordinates()
        """Old, openCV using contours
        contours = cv.FindContours(cv.CloneImage(thresholded_frame), cv.CreateMemStorage(),mode=cv.CV_RETR_EXTERNAL)
        
        if len(contours)!=0:
            #determine the objects moments and check that the area is large  
            #enough to be our object 
            moments = cv.Moments(contours,1) 
            moment10 = cv.GetSpatialMoment(moments, 1, 0)
            moment01 = cv.GetSpatialMoment(moments, 0, 1)
            area = cv.GetCentralMoment(moments, 0, 0) 
            
            #there can be noise in the video so ignore objects with small areas 
            if area > 2: 
                #determine the x and y coordinates of the center of the object 
                #we are tracking by dividing the 1, 0 and 0, 1 moments by the area 
                x = moment10/area
                y = moment01/area"""
        if debug:
            cv.ShowImage("Camera", self.thresholded_frame)
            #thresholded_frame=SimpleCV.Image(thresholded_frame)
            #thresholded_frame.show()
        print time.time() - t

        return x, y
Ejemplo n.º 14
0
 def grab(self):
     return cv.GrabFrame(self.cv_capture)
Ejemplo n.º 15
0
            corner = clusters[0][0]
        else:
            fg = averages[clusters[1][0]]
            bg = averages[clusters[0][0]]
            corner = clusters[1][0]

        if (fg > bg):
            return (corner, "w")
        else:
            return (corner, "b")


#solve_camera(xyz,xy)
print sys.argv[1]
capture = cv.CaptureFromFile(sys.argv[1])
cv.GrabFrame(capture)
img = cv.RetrieveFrame(capture)
img2 = cv.CloneImage(img)
eig_image = cv.CreateMat(img.height, img.width, cv.CV_32FC1)
temp_image = cv.CreateMat(img.height, img.width, cv.CV_32FC1)
img32f = cv.CreateImage((img.width, img.height), cv.IPL_DEPTH_32F, 3)
cv.Convert(img, img32f)
img_gs = cv.CreateImage((img.width, img.height), cv.IPL_DEPTH_32F, 1)
cv.CvtColor(img32f, img_gs, cv.CV_RGB2GRAY)

font = cv.InitFont(cv.CV_FONT_HERSHEY_PLAIN, 1.0, 1.0)


def tand(alpha):
    return tan(alpha * 3.1415926 / 180)
Ejemplo n.º 16
0
 def grab(self):
     """Grab a frame from capture device"""
     return cv.GrabFrame(self.capture)
Ejemplo n.º 17
0
    def getCoordinates(self, target="ball", debug=False):
        """
        This function will return the best coordinates found by thresholding the received image
        by the chosen threshold.
        """
        """Get the latest frame from the camera"""
        global cam, lock
        lock.acquire()
        try:
            cv.GrabFrame(cam)
            frame = cv.RetrieveFrame(cam)
        finally:
            lock.release()
        """Initialize the coordinates to -1, which means that the object is not found"""
        x = -1
        y = -1
        """Prepair image for thresholding"""
        #cv.Smooth(thresholded_frame, thresholded_frame, cv.CV_GAUSSIAN, 5, 5)
        cv.Smooth(frame, frame, cv.CV_BLUR, 3)
        cv.CvtColor(frame, self.hsv_frame, cv.CV_BGR2HSV)
        """Threshold the image according to the chosen thresholds"""
        if target == "ball":
            cv.InRangeS(self.hsv_frame, self.ball_threshold_low,
                        self.ball_threshold_high, self.thresholded_frame)
        elif target == "blue gate":
            cv.InRangeS(self.hsv_frame, self.blue_gate_threshold_low,
                        self.blue_gate_threshold_high, self.thresholded_frame)
        elif target == "yellow gate":
            cv.InRangeS(self.hsv_frame, self.yellow_gate_threshold_low,
                        self.yellow_gate_threshold_high,
                        self.thresholded_frame)
        elif target == "black":
            cv.InRangeS(self.hsv_frame, self.black_threshold_low,
                        self.black_threshold_high, self.thresholded_frame)
        elif target == "white":
            cv.InRangeS(self.hsv_frame, self.white_threshold_low,
                        self.white_threshold_high, self.thresholded_frame)
        else:  #green
            cv.InRangeS(self.hsv_frame, self.green_threshold_low,
                        self.green_threshold_high, self.thresholded_frame)
        """Now use some function to find the object"""
        blobs_image = SimpleCV.Image(self.thresholded_frame)
        blobs = blobs_image.findBlobs()
        if blobs:
            for i in range(len(blobs)):
                line = blobs[i]
                angle = line.angle()
                pos_x, pos_y = line.coordinates()
                if line.maxY() > 100:
                    y = line.maxY()
                    if angle > 0:
                        x = line.maxX()
                    else:
                        x = line.minX()
                    break

        if debug:
            cv.ShowImage("Camera", self.thresholded_frame)
            #thresholded_frame=SimpleCV.Image(thresholded_frame)
            #blobs_image.show()

        return x, y
Ejemplo n.º 18
0
'''capture.py'''
import cv, sys
cap = cv.CaptureFromCAM(0)  # 0 is for /dev/video0
while True:
    if not cv.GrabFrame(cap): break
    frame = cv.RetrieveFrame(cap)
    sys.stdout.write(frame.tostring())
Ejemplo n.º 19
0
		if not img:
			break
<<<<<<< HEAD:02_5_100-stills.py

		img_small = cv.CreateImage((WIDTH, int( img.height * float(WIDTH)/img.width )), cv.IPL_DEPTH_8U, 3)
		cv.Resize(img, img_small, cv.CV_INTER_CUBIC)

		cv.SaveImage(os.path.join(OUTPUT_DIR,"still_%07d.jpg" % (frame)), img_small)

=======
		
		cv.SaveImage(OUTPUT_DIR + "\\still_%07d.jpg" % (frame), img)
		
>>>>>>> parent of 1f8384f... minor changes:stills_100.py
		for i in range(every_nth_frame-1):
			cv.GrabFrame(cap)

		frame += every_nth_frame
<<<<<<< HEAD:02_5_100-stills.py

	#raw_input("- done -")
=======
		counter += 1
	
	raw_input("- done -")
>>>>>>> parent of 1f8384f... minor changes:stills_100.py
	return


# #########################
if __name__ == "__main__":
Ejemplo n.º 20
0
def GetRawDartXY():
    global capture
    global image

    if calibration.debug:
        # the coordinates
        global x_coordinate
        global y_coordinate
        x_coordinate = 0
        y_coordinate = 0

        #use this events wait for mouse click
        global mouse_click_down
        mouse_click_down = Event()

        cv.NamedWindow(window_name, 1)
        cv.SetMouseCallback(window_name, on_mouse)

        while not mouse_click_down.is_set():
            if calibration.from_video:
                cv.GrabFrame(capture)
                image = cv.RetrieveFrame(capture)
            cv.ShowImage(window_name, image)
            cv.WaitKey(1)
        mouse_click_down.clear()

        ##        clone = cv.CloneImage(image)
        ##
        ##        cv.Circle(clone,(x_coordinate,y_coordinate),3,cv.CV_RGB(255, 0, 0),2)
        ##        cv.ShowImage(window_name, clone)

        return (x_coordinate, y_coordinate)

    else:
        motion = 0
        ##        capture = 0
        darts_found = list()
        detected_x = 0
        detected_y = 0
        no_dart_prev = True
        no_dart_prev_prev = True
        ##        draw = False

        ##        parser = OptionParser(usage = "usage: %prog [options]")
        ##        parser.add_option("-c", "--cascade", action="store", dest="cascade", type="str", help="Haar cascade file, default %default", default = "default.xml")
        ##        parser.add_option("-f", "--videofile", action="store", dest="videofile", type="str", help="Video capture file, default is to capture from camera", default = None)
        ##
        ##        (options, args) = parser.parse_args()
        ##
        ##        cascade = cv.Load(options.cascade)
        ##        videofile = options.videofile
        ##
        ##        if videofile == None:
        ##            capture = cv.CreateCameraCapture(0)
        ##        else:
        ##            capture = cv.CaptureFromFile(videofile)

        cascade = cv.Load(calibration.cascadefile)

        ##        cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
        ##        cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT , 480)

        cv.NamedWindow("Motion")
        cv.NamedWindow('Original')

        while True:
            image = cv.QueryFrame(capture)
            ##            cv.GrabFrame(capture)
            ##            image = cv.RetrieveFrame(capture)
            image_clone = cv.CloneImage(image)
            if (image):
                if (not motion):
                    motion = cv.CreateImage((image.width, image.height), 8, 1)
                    cv.Zero(motion)

                update_mhi(image, motion, 30)
                # no darts 2 frames ago
                no_dart_prev_prev = no_dart_prev
                # no darts 1 frame ago
                no_dart_prev = (len(darts_found) == 0)

                # when we transition from having a dart frame to not having a
                # dart frame, then the dart coordinates are stable and we can return
                if (no_dart_prev_prev == False) and (no_dart_prev == True):
                    # we can return here
                    ##                    draw = True
                    ##                    print 'Dart detected at ({0},{1})'.format(detected_x,detected_y)
                    ##                    cv.Circle(image_clone,(detected_x,detected_y),3,cv.RGB(255,0,0),3)
                    ##                    cv.ShowImage('Original',image_clone)

                    ##                    print 'at',cv.GetCaptureProperty(capture,cv.CV_CAP_PROP_POS_FRAMES)
                    return (detected_x, detected_y)

                darts_found = []

                detect(motion, cascade, darts_found)
                # if the number of pixels that changed is outside of the accepted
                # bound, then we say this is not a dart throw
                # the bounds are determined experimentally
                if not (pixels_lo_bound < cv.CountNonZero(motion) <
                        pixels_hi_bound):
                    darts_found = []

                for dart_rec in darts_found:
                    ##                    draw = False
                    x_dart = dart_rec[0]
                    y_dart = dart_rec[1]
                    width_dart = dart_rec[2]
                    height_dart = dart_rec[3]

                    cv.Rectangle(image_clone, (x_dart, y_dart),
                                 (x_dart + width_dart, y_dart + height_dart),
                                 cv.RGB(0, 0, 255), 3, 8, 0)

                    done = False
                    for x in range(x_dart, x_dart + width_dart, 1):
                        if done:
                            break
                        for y in range(y_dart + height_dart, y_dart, -1):
                            # Get2D looks at a matrix, so we have access the
                            # Yth row and the Xth column!!!
                            if cv.Get2D(motion, y, x) != cv.Scalar(0):
                                if non_zero_in_conv_table(
                                        motion, x, y) > dart_tip_threshold:
                                    if no_dart_prev:
                                        detected_x = x
                                        detected_y = y
                                    else:
                                        if x < detected_x:
                                            detected_x = x
                                            detected_y = y
                                    done = True
                                    break
##                if draw:
##                    cv.Circle(image,(detected_x,detected_y),3,cv.RGB(255,0,0),3)
##
                cv.ShowImage('Original', image_clone)
                cv.ShowImage("Motion", motion)
                key = cv.WaitKey(1)
                if (key == 27):
                    break
            else:
                break

        raise Exception('GetDart() failed unexpectedly')
Ejemplo n.º 21
0
def main():
    if len(sys.argv) == 1:
        print 'Usage: %s [inputfile]' % sys.argv[0]
        sys.exit(1)

    # initialize window
    cv.NamedWindow('video', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('video', 10, 10)

    cv.NamedWindow('threshold', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('threshold', 10, 500)

    cv.NamedWindow('flow', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('flow', 500, 10)

    cv.NamedWindow('edges', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('edges', 500, 500)

    cv.NamedWindow('combined', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('combined', 1000, 10)

    capture = cv.CreateFileCapture(sys.argv[1])
    if not capture:
        print 'Error opening capture'
        sys.exit(1)

    # Load bg image
    bg = cv.LoadImage('bg.png')

    # Discard some frames
    for i in xrange(2300):
        cv.GrabFrame(capture)

    frame = cv.QueryFrame(capture)
    frame_size = cv.GetSize(frame)

    # vars for playback
    fps = 25
    play = True
    velx = cv.CreateImage(frame_size, cv.IPL_DEPTH_32F, 1)
    vely = cv.CreateImage(frame_size, cv.IPL_DEPTH_32F, 1)
    combined = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    prev = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    curr = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    frame_sub = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 3)

    edges = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    prev_edges = None
    storage = cv.CreateMemStorage(0)

    blob_mask = cv0.cvCreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    cv0.cvSet(blob_mask, 1)

    hough_in = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    hough_storage = cv.CreateMat(100, 1, cv.CV_32FC3)
    '''
    cv.CvtColor(frame, prev, cv.CV_BGR2GRAY)
    frame = cv.QueryFrame(capture)
    cv.CvtColor(frame, curr, cv.CV_BGR2GRAY)

    # winSize can't have even numbers
    cv.CalcOpticalFlowLK(prev, curr, (3,3), velx, vely)
    cv.ShowImage('video', frame)
    cv.ShowImage('flow', velx)
    cv.WaitKey(0)
    '''

    while True:

        if play:
            frame = cv.QueryFrame(capture)
            cv.Sub(frame, bg, frame_sub)
            '''#detect people
            found = list(cv.HOGDetectMultiScale(frame, storage, win_stride=(8,8),
                padding=(32,32), scale=1.05, group_threshold=2))
            for r in found:
                (rx, ry), (rw, rh) = r
                tl = (rx + int(rw*0.1), ry + int(rh*0.07))
                br = (rx + int(rw*0.9), ry + int(rh*0.87))
                cv.Rectangle(frame, tl, br, (0, 255, 0), 3)
            '''

            #color thresholding
            hsv = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 3)
            cv.CvtColor(frame, hsv, cv.CV_BGR2HSV)
            mask = cv.CreateMat(frame_size[1], frame_size[0], cv.CV_8UC1)
            cv.InRangeS(hsv, (0.06 * 256, 0.2 * 256, 0.6 * 256, 0),
                        (0.16 * 256, 1.0 * 256, 1.0 * 256, 0), mask)
            cv.ShowImage('threshold', mask)

            #optical flow method
            # store previous frame
            prev, curr = curr, prev
            # convert next frame to single channel grayscale
            cv.CvtColor(frame_sub, curr, cv.CV_BGR2GRAY)
            #cv.CalcOpticalFlowLK(prev, curr, (3,3), velx, vely)
            #cv.Threshold(velx, velx, 8.0, 0, cv.CV_THRESH_TOZERO)
            cv.CalcOpticalFlowHS(prev, curr, 1, velx, vely, 0.5,
                                 (cv.CV_TERMCRIT_ITER, 10, 0))
            cv.Threshold(velx, velx, 0.5, 0, cv.CV_THRESH_TOZERO)
            cv.Threshold(vely, vely, 0.5, 0, cv.CV_THRESH_TOZERO)
            cv.Erode(
                vely, vely,
                cv.CreateStructuringElementEx(2, 2, 0, 0, cv.CV_SHAPE_ELLIPSE))
            cv.Add(vely, velx, vely)
            cv.ShowImage('flow', vely)

            #edge detection
            cv.Canny(curr, edges, 50, 100)
            cv.Dilate(
                edges, edges,
                cv.CreateStructuringElementEx(7, 7, 0, 0, cv.CV_SHAPE_ELLIPSE))
            cv.ShowImage('edges', edges)

            if prev_edges:
                cv.CalcOpticalFlowHS(prev_edges, edges, 1, velx, vely, 0.5,
                                     (cv.CV_TERMCRIT_ITER, 10, 0))
                cv.Threshold(velx, velx, 0.5, 0, cv.CV_THRESH_TOZERO)
                cv.Threshold(vely, vely, 0.5, 0, cv.CV_THRESH_TOZERO)
                cv.ShowImage('flow', vely)
            prev_edges = edges

            cv.Threshold(vely, combined, 0.5, 255, cv.CV_THRESH_BINARY)
            cv.Min(combined, edges, combined)
            cv.ShowImage('combined', combined)

            # blobs
            myblobs = CBlobResult(edges, blob_mask, 100, False)
            myblobs.filter_blobs(10, 10000)
            blob_count = myblobs.GetNumBlobs()

            for i in range(blob_count):

                my_enumerated_blob = myblobs.GetBlob(i)
                #               print "%d: Area = %d" % (i, my_enumerated_blob.Area())
                my_enumerated_blob.FillBlob(frame,
                                            hsv2rgb(i * 180.0 / blob_count), 0,
                                            0)

            cv.ShowImage('video', frame)
            ''' crashes
            #hough transform on dilated image
            #http://wiki.elphel.com/index.php?
            # title=OpenCV_Tennis_balls_recognizing_tutorial&redirect=no
            cv.Copy(edges, hough_in)
            cv.Smooth(hough_in, hough_in, cv.CV_GAUSSIAN, 15, 15, 0, 0)
            cv.HoughCircles(hough_in, hough_storage, cv.CV_HOUGH_GRADIENT,
                            4, frame_size[1]/10, 100, 40, 0, 0)
            print hough_storage
            '''

        k = cv.WaitKey(1000 / fps)
        if k == 27:  # ESC key
            break
        elif k == 'p':  # play/pause
            play = not play