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)
예제 #2
0
    def __init__(self,
                 name,
                 size=2,
                 draw_center=True,
                 draw_grid=True,
                 meters_radius=4.0):
        """
			 name = name of window
			 meter_radus = 4.0
			 size = multiple of 400x200 to use for screen
			 meter_radius = how many per metrer 
		"""
        self.draw_center = draw_center
        self.draw_grid = draw_grid
        self.w = (int)(round(size * 400.0))
        self.h = (int)(round(size * 200.0))

        self.meters_disp = 4.0  #Range in meters of area around robot to display
        self.laser_win = name
        self.buffer = cv.cvCreateImage(cv.cvSize(self.w, 2 * self.h),
                                       cv.IPL_DEPTH_8U, 3)
        #print "RobotDisp: window width", self.buffer.width
        #print "RobotDisp: window height", self.buffer.height
        self.pixels_per_meter = self.h / self.meters_disp
        hg.cvNamedWindow(name, hg.CV_WINDOW_AUTOSIZE)
        hg.cvMoveWindow(name, 0, 50)

        self.font = cv.cvInitFont(cv.CV_FONT_HERSHEY_PLAIN, as_int(1),
                                  as_int(1), 0, 1, cv.CV_AA)
예제 #3
0
def main():
  
    usage = "%prog [options] <imgfile>"
    version = "%prog 0.2\n Longbin Chen, [email protected]"
    oparser = optparse.OptionParser(usage=usage, version=version)
    oparser.add_option('-d', '--display', action="store_true", dest = 'display', default = False, help = 'display the image')
    oparser.add_option('-m', '--drawnumber', action="store_true", dest = 'drawnumber', default = False, help = 'display the point numbers')
    oparser.add_option('-n', '--number', dest = 'num', type='int',default = 200 , help = 'the number of feature points')
    oparser.add_option('-t', '--threshold', dest = 'threshold', type='int',default = 100 , help = 'the threshold for image binarification')
    oparser.add_option('-o', '--output', dest = 'output', default = None, help = 'output file')
    oparser.add_option('-s', '--save', dest = 'save', default = None, help = 'save the img file')

    (options, args) = oparser.parse_args(sys.argv)

    if len(args) != 2:
        oparser.parse_args([sys.argv[0], "--help"])
        sys.exit(1)
        
    ct = ExtractMSS()
    ct.GetContour(args[1], options)

    if (options.display):
        ct.start = options.threshold
        ct.DrawKeyPoints()
        highgui.cvNamedWindow ("contour", 1)
        highgui.cvShowImage ("contour", ct.drawimg)
        highgui.cvWaitKey (0)       

    if (options.output):
        ct.mss.save(options.output)

    if (options.save):
        highgui.cvSaveImage(options.save, ct.drawimg)    
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)
예제 #5
0
def main():

    print "FaceIn! an OpenCV Python Face Recognition Program"
    
    highgui.cvNamedWindow ('Camera', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvMoveWindow ('Camera', 10, 10)
    device = 0 #use first device found
    capture = highgui.cvCreateCameraCapture (device)
    frame = highgui.cvQueryFrame (capture)
    frame_size = cv.cvGetSize (frame)
    fps = 30
        
    while 1:
        
        frame = highgui.cvQueryFrame (capture)
        
        detectFace(frame)
        # display the frames to have a visual output
        highgui.cvShowImage ('Camera', frame)

        # handle events
        k = highgui.cvWaitKey (5)

        if k % 0x100 == 27:
            # user has press the ESC key, so exit
            quit()
예제 #6
0
def main():

    print "FaceIn! an OpenCV Python Face Recognition Program"

    highgui.cvNamedWindow('Camera', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvMoveWindow('Camera', 10, 10)
    device = 0  #use first device found
    capture = highgui.cvCreateCameraCapture(device)
    frame = highgui.cvQueryFrame(capture)
    frame_size = cv.cvGetSize(frame)
    fps = 30

    while 1:

        frame = highgui.cvQueryFrame(capture)

        detectFace(frame)
        # display the frames to have a visual output
        highgui.cvShowImage('Camera', frame)

        # handle events
        k = highgui.cvWaitKey(5)

        if k % 0x100 == 27:
            # user has press the ESC key, so exit
            quit()
예제 #7
0
def show_image(window_name, img, wait=False):
    hg.cvStartWindowThread()
    RESIZABLE = 0
    hg.cvNamedWindow(window_name, RESIZABLE)
    hg.cvShowImage(window_name, img)
    if wait:
        print 'show_image: press any key to continue..'
        cv.highgui.cvWaitKey()
예제 #8
0
def run_me_server():
    sn       = SegmentNode()
    hg.cvNamedWindow('image', 1)

    rospy.TopicSub('image', RImage, sn.set_image)
    rospy.ready(sys.argv[0])
    segment_service = rospy.Service('hrl_grasp', srv.hrl_grasp, sn.segment)
    segment_service.register()
    rospy.spin()
 def _make_windows(self):
     windows = ['video', 'right', 'thresholded', 'motion', 'intensity', 'patch', 'big_patch']
     for n in windows:
         hg.cvNamedWindow(n, 1)
     hg.cvMoveWindow("video",       0,   0)
     hg.cvMoveWindow("right",       800, 0)
     hg.cvMoveWindow("thresholded", 800, 0)
     hg.cvMoveWindow("intensity",   0,   600)
     hg.cvMoveWindow("motion",      800, 600)
예제 #10
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)
예제 #11
0
파일: chroma.py 프로젝트: 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")    
예제 #12
0
 def _make_windows(self):
     windows = [
         'video', 'right', 'thresholded', 'motion', 'intensity', 'patch',
         'big_patch'
     ]
     for n in windows:
         hg.cvNamedWindow(n, 1)
     hg.cvMoveWindow("video", 0, 0)
     hg.cvMoveWindow("right", 800, 0)
     hg.cvMoveWindow("thresholded", 800, 0)
     hg.cvMoveWindow("intensity", 0, 600)
     hg.cvMoveWindow("motion", 800, 600)
예제 #13
0
    def run(self):
        """
        Consume images from the webcam at 25fps.
        If visualize is True, show the result in the screen.
        """
        if self.visualize:
            highgui.cvNamedWindow('DucksboardFace')

        while self.running:
            self.image = highgui.cvQueryFrame(self.camera)
            if self.visualize:
                highgui.cvShowImage('DucksboardFace', self.image)
            highgui.cvWaitKey(1000 / 25)
예제 #14
0
    def run(self):
        """
        Consume images from the webcam at 25fps.
        If visualize is True, show the result in the screen.
        """
        if self.visualize:
            highgui.cvNamedWindow('DucksboardFace')

        while self.running:
            self.image = highgui.cvQueryFrame(self.camera)
            if self.visualize:
                highgui.cvShowImage('DucksboardFace', self.image)
            highgui.cvWaitKey(1000 / 25)
예제 #15
0
def main(): # ctrl+c to end
    global h,s,v,h2,v2,s2,d,e
    highgui.cvNamedWindow("Camera 1", 1)
    highgui.cvNamedWindow("Orig", 1)
    highgui.cvCreateTrackbar("H", "Camera 1", h, 256, tb_h)
    highgui.cvCreateTrackbar("S", "Camera 1", s, 256, tb_s)
    highgui.cvCreateTrackbar("V", "Camera 1", v, 256, tb_v)
    highgui.cvCreateTrackbar("H2", "Camera 1", h2, 256, tb_h2)
    highgui.cvCreateTrackbar("S2", "Camera 1", s2, 256, tb_s2)
    highgui.cvCreateTrackbar("V2", "Camera 1", v2, 256, tb_v2)
    highgui.cvCreateTrackbar("Dilate", "Camera 1", d, 30, tb_d)
    highgui.cvCreateTrackbar("Erode", "Camera 1", e, 30, tb_e)
    
    cap = highgui.cvCreateCameraCapture(1)
    highgui.cvSetCaptureProperty(cap, highgui.CV_CAP_PROP_FRAME_WIDTH, IMGW)
    highgui.cvSetCaptureProperty(cap, highgui.CV_CAP_PROP_FRAME_HEIGHT, IMGH)
    c = 0
    t1 = tdraw = time.clock()
    t = 1
    font = cv.cvInitFont(cv.CV_FONT_HERSHEY_PLAIN, 1, 1)
    while c != 0x27:
        image = highgui.cvQueryFrame(cap)
        if not image:
            print "capture failed"
            break
            
        thresh = cv.cvCreateImage(cv.cvSize(IMGW,IMGH),8,1)
        cv.cvSetZero(thresh)
        cv.cvCvtColor(image,image,cv.CV_RGB2HSV)
        cv.cvInRangeS(image, (h,s,v,0), (h2,s2,v2,0), thresh)
        result = cv.cvCreateImage(cv.cvSize(IMGW,IMGH),8,3)
        cv.cvSetZero(result)
        
        cv.cvOr(image,image,result,thresh)
        for i in range(1,e):
            cv.cvErode(result,result)
        for i in range(1,d):
            cv.cvDilate(result,result)
            
        # floodfill objects back in, allowing threshold differences outwards
        
        t2 = time.clock()
        if t2 > tdraw+0.3:
            t = t2-t1
            tdraw=t2
        cv.cvPutText(result, "FPS: " + str(1 / (t)), (0,25), font, (255,255,255))
        t1 = t2
        highgui.cvShowImage("Orig", image)
        highgui.cvShowImage("Camera 1", result)
        c = highgui.cvWaitKey(10)
예제 #16
0
파일: chroma.py 프로젝트: 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")
예제 #17
0
def main():
	"""
	Just the test
	This method is a god resource on how to handle the results
	"""

	filename = sys.argv[1]
	image = highgui.cvLoadImage (filename)

	print "DO NOT EXPECT THE RUNNING TIME OF THIS TEST TO BE REPRESENTATIVE!"
	print ""
	print "THRESHOLDS AND EVERYTHING ELSE ARE HARDCODED!"

	cutRatios = [0.6667, lib.PHI, 0.6]
	settings = Settings(cutRatios)

	# Run the analysis with the above settings
	comps = naiveMethod.analyzeImage(image, settings)

	# This is just for drawing the results
	# The below methods can probably be combined but don't bother
	# {{{
	# Get and draw the cuts
	cuts = {}
	for ratio in settings.cutRatios:
		cuts[str(ratio)] = lib.findMeans(cv.cvGetSize(image), ratio)

	for ratio in cuts:
		lib.drawLines(image, None, cuts[ratio], lib.getRandomColor())

	# Get and draw the components
	for ratio in comps:
		for cut in comps[ratio]:
			lib.drawBoundingBoxes(image, comps[ratio][cut])
	# }}}

	winname = "Failure"

	highgui.cvNamedWindow (winname, highgui.CV_WINDOW_AUTOSIZE)

	while True:
		highgui.cvShowImage (winname, image)

		c = highgui.cvWaitKey(0)

		if c == 'q':
			print "Exiting ..."
			print ""
			sys.exit(0)
예제 #18
0
def showImage(image, name):
	"""Helper method for displaying an image"""
	winname = name

	highgui.cvNamedWindow (winname, highgui.CV_WINDOW_AUTOSIZE)

	while True:
		highgui.cvShowImage (winname, image)

		c = highgui.cvWaitKey(0)

		if c == 'q':
			print "Exiting ..."
			print ""
			sys.exit(0)
예제 #19
0
    def display(self, index=-1):
        """
        open a new window
        """
        if(index==-1):
            self.maxWindow = self.maxWindow+1;
            index= self.maxWindow;

        if(index > self.maxWindow):
            self.maxWindow = index;

        self.currentWindow = index;
        self.currentWindowName = "opencv-python window %d" % self.currentWindow
        cvNamedWindow(self.currentWindowName,0)
        return self.currentWindow
예제 #20
0
    def display(self, index=-1):
        """
        open a new window
        """
        if (index == -1):
            self.maxWindow = self.maxWindow + 1
            index = self.maxWindow

        if (index > self.maxWindow):
            self.maxWindow = index

        self.currentWindow = index
        self.currentWindowName = "opencv-python window %d" % self.currentWindow
        cvNamedWindow(self.currentWindowName, 0)
        return self.currentWindow
예제 #21
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)
예제 #22
0
파일: pyfaces.py 프로젝트: ruchir-hj/i-home
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 "
예제 #23
0
def compareImages(img1, img2, name1, name2):
	# Do NOT save images to disk in this method
	winname1 = name1
	winname2 = name2

	highgui.cvNamedWindow (winname1, highgui.CV_WINDOW_AUTOSIZE)
	highgui.cvNamedWindow (winname2, highgui.CV_WINDOW_AUTOSIZE)

	while True:
		highgui.cvShowImage (winname1, img1)
		highgui.cvShowImage (winname2, img2)

		c = highgui.cvWaitKey(0)

		if c == 'q':
			print "Exiting ..."
			print ""
			sys.exit(0)
예제 #24
0
def main():
    usage = "%s [options]  <imgfile> " % (sys.argv[0])
    version = "%prog 0.2\n Longbin Chen, [email protected]"
    oparser = optparse.OptionParser(usage=usage, version=version)
    oparser.add_option('-d', '--display', action="store_true", dest = 'display', default = False, help = 'display the image')
    oparser.add_option('-c','--contour', action="store_true", dest = 'contour', default = False, help = 'show object contour')
    oparser.add_option('-i','--image', action="store_true", dest = 'image', default = False, help = 'show original images')
    oparser.add_option('-n', '--number', dest = 'num', type='int', default = 200 , help = 'the number of feature points')
    oparser.add_option('-x','--enlarge', dest = 'enlarge', default = 1.0 , type = float,  help = 'resize images, default:1.0')
    oparser.add_option('-o', '--output', dest = 'output', default = None, help = 'output file')
    oparser.add_option('-p', '--pointfile', dest = 'pointfile', default = None, help = 'use pointfile ')
    oparser.add_option('-r', '--harris', dest = 'harris', default = False, action = "store_true", help = 'use harris detector')
    oparser.add_option('-s', '--save', dest = 'save', default = None, help = 'save the img file')
    

    (options, args) = oparser.parse_args(sys.argv)

    if len(args) != 2:
        oparser.parse_args([sys.argv[0], "--help"])
        sys.exit(1)
    if (options.pointfile == None and options.harris == None): 
        print >> sys.stderr, "either of  pointfile and harris can be valid"
        sys.exit(1)

    highgui.cvNamedWindow ("Corner1", 1)
    ct = Linker(options.contour, options.image, options.enlarge, options.num)
    if (options.pointfile): 
        ct.LoadPoints(options.pointfile)
        ct.LinkPoints(args[1])
    else:
        ct.HarrisPoints(args[1])
        ct.LinkPoints(args[1])
    highgui.cvShowImage ("Corner1", ct.drawimg)
    highgui.cvWaitKey (0)   
    if (options.save):
        highgui.cvSaveImage(options.save, ct.drawimg)    
    if (options.output):
        f = open(options.output, "w")
        f.write(OUT.getvalue())
        f.close()
        OUT.close()
예제 #25
0
파일: chroma.py 프로젝트: 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")
예제 #26
0
파일: util.py 프로젝트: Calm-wy/kwc-ros-pkg
def display_images(image_list, max_x=1200, max_y=1000, save_images=False):
    """
	Display a list of OpenCV images tiled across the screen
	with maximum width of max_x and maximum height of max_y

	save_images - will save the images(with timestamp)
	"""

    curtime = time.localtime()
    date_name = time.strftime('%Y_%m_%d_%I%M%S', curtime)

    loc_x, loc_y = 0, 0
    wins = []
    for i, im in enumerate(image_list):
        if save_images:
            if im.nChannels == 1 and im.depth == cv.IPL_DEPTH_32F:
                clr = cv.cvCreateImage(cv.cvSize(im.width, im.height),
                                       cv.IPL_DEPTH_8U, 1)
                cv.cvConvertScale(im, clr, 255.0)
                im = clr
            highgui.cvSaveImage('image%d_' % i + date_name + '.png', im)

        window_name = 'image %d' % i
        wins.append((window_name, im))
        highgui.cvNamedWindow(window_name, highgui.CV_WINDOW_AUTOSIZE)
        highgui.cvMoveWindow(window_name, loc_x, loc_y)
        loc_x = loc_x + im.width
        if loc_x > max_x:
            loc_x = 0
            loc_y = loc_y + im.height
            if loc_y > max_y:
                loc_y = 0
    while True:
        for name, im in wins:
            highgui.cvShowImage(name, im)
        keypress = highgui.cvWaitKey(10)
        if keypress == '\x1b':
            break
예제 #27
0
def main():
    ct = Corner()
    usage = "%s [options] <imgfile>" % (sys.argv[0])
    version = "%prog 0.2\n Longbin Chen, [email protected]"
    oparser = optparse.OptionParser(usage=usage, version=version)
    oparser.add_option('-d', '--display', action="store_true", dest = 'display', default = False, help = 'display the image')
    oparser.add_option('-n', '--number', dest = 'num', type='int',default = 200 , help = 'the number of feature points')
    oparser.add_option('-o', '--output', dest = 'output', default = None, help = 'output file')
    oparser.add_option('-s', '--save', dest = 'save', default = None, help = 'save the img file')

    (options, args) = oparser.parse_args(sys.argv)

    if len(args) != 2:
        oparser.parse_args([sys.argv[0], "--help"])
        sys.exit(1)
    ct.GetCorner(args[1], options.num)
    if (options.display):
        ct.DrawKeyPoints()
        highgui.cvNamedWindow ("Corner1", 1)
        highgui.cvShowImage ("Corner1", ct.drawimg)
        highgui.cvWaitKey (0)   
    if (options.save):
        highgui.cvSaveImage(options.save, ct.drawimg)    
예제 #28
0
def visualize(eigens):
    l1 = eigens[:,:,0]
    l2 = eigens[:,:,1]    
    m1 = np.min(l1)
    m2 = np.min(l2)
    r1 = np.max(l1) - m1 
    r2 = np.max(l2) - m2
    if r1 == 0:
        r1 = 1
    if r2 == 0:
        r2 = 1      
    l1cv = ut.np2cv(np.array( (1 - ((l1-m1) / r1)) * 255, dtype='uint8'))
    l2cv = ut.np2cv(np.array( (1 - ((l2-m2) / r2)) * 255, dtype='uint8'))
    hg.cvNamedWindow('eigen value 1', 1)
    hg.cvNamedWindow('eigen value 2', 1)
    hg.cvShowImage('eigen value 1', l1cv)
    hg.cvShowImage('eigen value 2', l2cv)
    while True:
        k = hg.cvWaitKey(33)
        if k == ' ':
            return
        if k == 'x':
            exit()
예제 #29
0
def visualize(eigens):
    l1 = eigens[:, :, 0]
    l2 = eigens[:, :, 1]
    m1 = np.min(l1)
    m2 = np.min(l2)
    r1 = np.max(l1) - m1
    r2 = np.max(l2) - m2
    if r1 == 0:
        r1 = 1
    if r2 == 0:
        r2 = 1
    l1cv = ut.np2cv(np.array((1 - ((l1 - m1) / r1)) * 255, dtype="uint8"))
    l2cv = ut.np2cv(np.array((1 - ((l2 - m2) / r2)) * 255, dtype="uint8"))
    hg.cvNamedWindow("eigen value 1", 1)
    hg.cvNamedWindow("eigen value 2", 1)
    hg.cvShowImage("eigen value 1", l1cv)
    hg.cvShowImage("eigen value 2", l2cv)
    while True:
        k = hg.cvWaitKey(33)
        if k == " ":
            return
        if k == "x":
            exit()
예제 #30
0
파일: util.py 프로젝트: janfrs/kwc-ros-pkg
def display_images(image_list, max_x = 1200, max_y = 1000, save_images=False):
	"""
	Display a list of OpenCV images tiled across the screen
	with maximum width of max_x and maximum height of max_y

	save_images - will save the images(with timestamp)
	"""

	curtime=time.localtime()
	date_name = time.strftime('%Y_%m_%d_%I%M%S', curtime)

	loc_x, loc_y = 0, 0
	wins = []
	for i, im in enumerate(image_list):
		if save_images:
			if im.nChannels == 1 and im.depth == cv.IPL_DEPTH_32F:
				clr = cv.cvCreateImage(cv.cvSize(im.width, im.height), cv.IPL_DEPTH_8U, 1)
				cv.cvConvertScale(im, clr, 255.0)
				im = clr
			highgui.cvSaveImage('image%d_'%i+date_name+'.png', im)

		window_name = 'image %d' % i
		wins.append((window_name, im)) 
		highgui.cvNamedWindow(window_name, highgui.CV_WINDOW_AUTOSIZE)
		highgui.cvMoveWindow(window_name, loc_x, loc_y)
		loc_x = loc_x + im.width
		if loc_x > max_x:
			loc_x = 0
			loc_y = loc_y + im.height
			if loc_y > max_y:
				loc_y = 0
	while True:
		for name, im in wins:
			highgui.cvShowImage(name, im)
		keypress = highgui.cvWaitKey(10)
		if keypress == '\x1b':
			break
예제 #31
0
파일: nodes.py 프로젝트: janfrs/kwc-ros-pkg
    def __init__(self, name, size=2, draw_center=True, draw_grid=True, meters_radius=4.0):
		"""
			 name = name of window
			 meter_radus = 4.0
			 size = multiple of 400x200 to use for screen
			 meter_radius = how many per metrer 
		"""
		self.draw_center = draw_center
		self.draw_grid   = draw_grid
		self.w = (int) (round(size * 400.0))
		self.h = (int) (round(size * 200.0))


		self.meters_disp = 4.0  #Range in meters of area around robot to display
		self.laser_win = name
		self.buffer = cv.cvCreateImage(cv.cvSize(self.w, 2*self.h), cv.IPL_DEPTH_8U, 3)
		#print "RobotDisp: window width", self.buffer.width
		#print "RobotDisp: window height", self.buffer.height
		self.pixels_per_meter = self.h / self.meters_disp
		hg.cvNamedWindow(name, hg.CV_WINDOW_AUTOSIZE)
		hg.cvMoveWindow(name, 0, 50)

		self.font = cv.cvInitFont(cv.CV_FONT_HERSHEY_PLAIN, 
				as_int(1), as_int(1), 0, 1, cv.CV_AA)
예제 #32
0
def main():
	if len(sys.argv)<2:
		print "throw a image my way"
		sys.exit(-1)
	
	print "Im testing"

	class Phony():
		pass

	tmp = Phony()
	setattr(tmp, 'id', 1)
	setattr(tmp, 'location', sys.argv[1])
	
	test = Painting(tmp)
	print test.getWidth()
	print test.getHeight()
	winname ="Test"
	highgui.cvNamedWindow(winname, highgui.CV_WINDOW_AUTOSIZE)
	while True:
		highgui.cvShowImage(winname,test.getImage())
		c = highgui.cvWaitKey(0)
		if c == 'q':
			sys.exit(0)
예제 #33
0
def main():

    usage = "%prog [options] <imgfile>"
    version = "%prog 0.2\n Longbin Chen, [email protected]"
    oparser = optparse.OptionParser(usage=usage, version=version)
    oparser.add_option("-d", "--display", action="store_true", dest="display", default=False, help="display the image")
    oparser.add_option(
        "-m", "--drawnumber", action="store_true", dest="drawnumber", default=False, help="display the point numbers"
    )
    oparser.add_option("-n", "--number", dest="num", type="int", default=200, help="the number of feature points")
    oparser.add_option(
        "-t", "--threshold", dest="threshold", type="int", default=100, help="the threshold for image binarification"
    )
    oparser.add_option("-o", "--output", dest="output", default=None, help="output file")
    oparser.add_option("-s", "--save", dest="save", default=None, help="save the img file")

    (options, args) = oparser.parse_args(sys.argv)

    if len(args) != 2:
        oparser.parse_args([sys.argv[0], "--help"])
        sys.exit(1)

    ct = ExtractMSS()
    ct.GetContour(args[1], options)

    if options.display:
        ct.DrawKeyPoints()
        highgui.cvNamedWindow("contour", 1)
        highgui.cvShowImage("contour", ct.drawimg)
        highgui.cvWaitKey(0)

    if options.output:
        ct.mss.save(options.output)

    if options.save:
        highgui.cvSaveImage(options.save, ct.drawimg)
예제 #34
0
파일: camera.py 프로젝트: Foued70/pycam
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")
예제 #35
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")
예제 #36
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
예제 #37
0
def run(exposure, video=None, display=False, debug=False):
    if display:
        hg.cvNamedWindow("video", 1)
        hg.cvMoveWindow("video",   0,   0)

    if debug:
        hg.cvNamedWindow('right',       1)
        hg.cvMoveWindow("right", 800,   0)
        hg.cvNamedWindow("thresholded", 1)
        hg.cvNamedWindow('motion',      1)
        hg.cvNamedWindow('intensity',   1)

        hg.cvMoveWindow("thresholded", 800, 0)
        hg.cvMoveWindow("intensity",   0,   600)
        hg.cvMoveWindow("motion",      800, 600)

    if video is None:
        #video    = cam.VidereStereo(0, gain=96, exposure=exposure)
        video    = cam.StereoFile('measuring_tape_red_left.avi','measuring_tape_red_right.avi')

    frames = video.next()
    detector       = LaserPointerDetector(frames[0], LaserPointerDetector.SUN_EXPOSURE, 
                                            use_color=False, use_learning=True)
    detector_right = LaserPointerDetector(frames[1], LaserPointerDetector.SUN_EXPOSURE, 
                                            use_color=False, use_learning=True, classifier=detector.classifier)
    stereo_cam     = cam.KNOWN_CAMERAS['videre_stereo2']

    for i in xrange(10):
        frames = video.next()
        detector.detect(frames[0])
        detector_right.detect(frames[1])

    lt = cv.cvCreateImage(cv.cvSize(640,480), 8, 3)
    rt = cv.cvCreateImage(cv.cvSize(640,480), 8, 3)
    for l, r in video:
        start_time = time.time()
        #l = stereo_cam.camera_left.undistort_img(l)
        #r = stereo_cam.camera_right.undistort_img(r)
        cv.cvCopy(l, lt)
        cv.cvCopy(r, rt)
        l = lt
        r = rt
        undistort_time = time.time()

        _, _, right_cam_detection, stats = detector_right.detect(r)
        if debug:
            draw_blobs(r, stats)
            draw_detection(r, right_cam_detection)
            hg.cvShowImage('right', r)

        image, combined, left_cam_detection, stats = detector.detect(l)
        detect_time = time.time()

        if debug: 
            motion, intensity = detector.get_motion_intensity_images()
            show_processed(l, [combined, motion, intensity], left_cam_detection, stats, detector)
        elif display:
            #draw_blobs(l, stats)
            draw_detection(l, left_cam_detection)
            hg.cvShowImage('video', l)
            hg.cvWaitKey(10)

        if right_cam_detection != None and left_cam_detection != None:
            x  = np.matrix(left_cam_detection['centroid']).T
            xp = np.matrix(right_cam_detection['centroid']).T
            result = stereo_cam.triangulate_3d(x, xp)
            print '3D point located at', result['point'].T, 
            print 'distance %.2f error %.3f' % (np.linalg.norm(result['point']),  result['error'])
        triangulation_time = time.time()

        diff = time.time() - start_time
        print 'Main: Running at %.2f fps, took %.4f s' % (1.0 / diff, diff)
예제 #38
0
def learn_run(exposure = LaserPointerDetector.SUN_EXPOSURE, num_examples_to_collect=200, display_during_run = True):
    hg.cvNamedWindow("video",       1)
    hg.cvNamedWindow("thresholded", 1)
    hg.cvNamedWindow('motion',      1)
    hg.cvNamedWindow('intensity',   1)

    hg.cvMoveWindow("video",       0,   0)
    hg.cvMoveWindow("thresholded", 800, 0)

    hg.cvMoveWindow("intensity",   0,   600)
    hg.cvMoveWindow("motion",      800, 600)

    video     = cam.VidereStereo(0, gain=96, exposure=exposure)
    frames    = video.next()
    detector  = LaserPointerDetector(frames[0], exposure=exposure, 
                                    dataset=PatchClassifier.DEFAULT_DATASET_FILE,
                                    use_color=False, use_learning=False)
    detector2 = LaserPointerDetector(frames[1], exposure=exposure, 
                                    dataset=PatchClassifier.DEFAULT_DATASET_FILE,
                                    use_color=False, use_learning=False)

    def append_examples_to_file(dataset, file = PatchClassifier.DEFAULT_DATASET_FILE):
        try:
            loaded_set = load_pickle(file)
            dataset.append(loaded_set)
        except IOError:
            pass
        dump_pickle(dataset, file)
        print 'Saved examples!'

    #Gather positive examples from laser detector
    if confirmation_prompt('gather positive examples?'):
        print 'Lets gather some positive examples... we need', num_examples_to_collect, 'examples'
        positive_examples_for_classifier = []
        count_down(0)
        for i in xrange(10):
            frames = video.next()
            detector.detect(frames[0])
            detector2.detect(frames[1])

        for img in video:
            image                 = None
            combined              = None
            motion                = None
            intensity             = None
            laser_blob            = None
            intensity_motion_blob = None

            for raw_image, detect in zip(img, [detector, detector2]):
                before = time.time()
                image, combined, laser_blob, intensity_motion_blob = detect.detect(raw_image)
                diff = time.time() - before
                #print 'took %.2f seconds to run or %.2f fps' % (diff, 1.0/diff)
                if laser_blob != None:
                    instance = blob_to_input_instance(image, laser_blob)
                    if instance is not None:
                        positive_examples_for_classifier.append(instance)
                        print 'got', len(positive_examples_for_classifier), 'instances'
                motion, intensity = detect.get_motion_intensity_images()

            show_processed(image, [combined, motion, intensity], laser_blob, intensity_motion_blob, detector2)
            if len(positive_examples_for_classifier) > num_examples_to_collect:
                break
        positive_instances_dataset = matrix_to_dataset(ut.list_mat_to_mat(positive_examples_for_classifier, axis=1))
        append_examples_to_file(positive_instances_dataset)

    if confirmation_prompt('gather negative examples?'):
        #Gather negative examples from laser detector
        print 'lets gather some negative examples... we need', num_examples_to_collect,' examples'
        negative_examples_for_classifier = []
        count_down(10)
        for i in xrange(10):
            frames = video.next()
            detector.detect(frames[0])
            detector2.detect(frames[1])

        for img in video:
            image                 = None
            combined              = None
            motion                = None
            intensity             = None
            laser_blob            = None
            intensity_motion_blob = None
            for raw_image, detect in zip(img, [detector, detector2]):
                image, combined, laser_blob, intensity_motion_blob = detect.detect(raw_image)
                if laser_blob != None:
                    instance = blob_to_input_instance(image, laser_blob)
                    if instance is not None:
                        negative_examples_for_classifier.append(instance)
                        print 'got', len(negative_examples_for_classifier), 'instances'
                motion, intensity = detect.get_motion_intensity_images()

            show_processed(image, [combined, motion, intensity], laser_blob, intensity_motion_blob, detector2)
            if len(negative_examples_for_classifier) > (num_examples_to_collect*2):
                break
        negative_instances_dataset = matrix_to_dataset(ut.list_mat_to_mat(negative_examples_for_classifier, axis=1))
        append_examples_to_file(negative_instances_dataset)

    if confirmation_prompt('run classifier?'):
        run(exposure, video = video, display=display_during_run)
예제 #39
0
        mouse_selection.width -= mouse_selection.x
        mouse_selection.height -= mouse_selection.y


#############################################################################
# so, here is the main part of the program

if __name__ == '__main__':

    print "OpenCV Python wrapper test"
    print "OpenCV version: %s (%d, %d, %d)" % (
        cv.CV_VERSION, cv.CV_MAJOR_VERSION, cv.CV_MINOR_VERSION,
        cv.CV_SUBMINOR_VERSION)

    # first, create the necessary windows
    highgui.cvNamedWindow('Camera', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvNamedWindow('Histogram', highgui.CV_WINDOW_AUTOSIZE)

    # move the new window to a better place
    highgui.cvMoveWindow('Camera', 10, 40)
    highgui.cvMoveWindow('Histogram', 10, 270)

    global mouse_origin
    global mouse_selection
    global mouse_select_object
    mouse_select_object = False
    global track_object
    track_object = 0

    global track_comp
    global track_box
예제 #40
0
#! /usr/bin/env python

import opencv
from opencv import highgui

cap = highgui.cvCreateFileCapture("../c/tree.avi")
img = highgui.cvQueryFrame(cap)
print "Got frame of dimensions (", img.width, " x ", img.height, " )"

highgui.cvNamedWindow("win", highgui.CV_WINDOW_AUTOSIZE)
highgui.cvShowImage("win", img)
highgui.cvMoveWindow("win", 200, 200)
highgui.cvWaitKey(0)

예제 #41
0
def tile_nsave(vecs):
    patches = []
    for i in xrange(vecs.shape[1]):
        patch, context = reconstruct_input(vecs[:, i])
        patches.append(patch)
    tile_width = math.ceil(math.pow(vecs.shape[1], .5))
    large_image = tile_images(15, 15, tile_width, tile_width, patches, 3)
    return large_image


show_pca = False
save_pca_bases = False
process_inputs = False
separate_negatives_positives = True
dataset = load_pickle('PatchClassifier.dataset.pickle')
hg.cvNamedWindow('image', 1)
hg.cvNamedWindow('context', 1)
pca_basis = normalize_for_display(dataset.projection_basis)

if show_pca:
    for i in range(pca_basis.shape[1]):
        print 'basis', i
        display(pca_basis[:, i], 'pca_basis' + str(i))

if save_pca_bases:
    large_image = tile_nsave(pca_basis)
    large_image = scale_image(large_image, 8)
    hg.cvSaveImage('pca_large_image.png', large_image)

if process_inputs:
    large_image = tile_nsave(dataset.inputs)
예제 #42
0
    if len(sys.argv) > 1:
        filename = sys.argv[1]

    # load the image gived on the command line
    image = highgui.cvLoadImage(filename)

    if not image:
        print "Error loading image '%s'" % filename
        sys.exit(-1)

    # create the output image
    col_edge = cv.cvCreateImage(cv.cvSize(image.width, image.height), 8, 3)

    # convert to grayscale
    gray = cv.cvCreateImage(cv.cvSize(image.width, image.height), 8, 1)
    edge = cv.cvCreateImage(cv.cvSize(image.width, image.height), 8, 1)
    cv.cvCvtColor(image, gray, cv.CV_BGR2GRAY)

    # create the window
    highgui.cvNamedWindow(win_name, highgui.CV_WINDOW_AUTOSIZE)

    # create the trackbar
    highgui.cvCreateTrackbar(trackbar_name, win_name, 1, 100, on_trackbar)

    # show the image
    on_trackbar(0)

    # wait a key pressed to end
    highgui.cvWaitKey(0)
예제 #43
0
def main():

    a_window = highgui.cvNamedWindow('a_window', highgui.CV_WINDOW_AUTOSIZE)
    '''
    image=cv.LoadImage('desktopBlue.jpg', cv.CV_LOAD_IMAGE_COLOR)
    dst = cv.cvCreateImage((600,200), 8, 3)
    cv.cvLine(dst,(100,200),(100,100),(0,0,1))
    cv.cvCircle(dst,(-10,-10),10,(0,0,0))
    highgui.cvShowImage('a_window',dst)
    highgui.cvWaitKey(10000)

    '''

    dst = cv.cvCreateImage((700, 700), 8, 3)
    cv.cvLine(dst, (20, 20), (20, 680), (0xFF, 0xFF, 0xFF), 2, 0)
    cv.cvLine(dst, (20, 680), (680, 680), (0xFF, 0xFF, 0xFF), 2, 0)

    no = int(raw_input("Enter total no. of points"))
    a = []
    for i in range(no):
        no1 = int(raw_input("Enter x coord: "))
        no2 = int(raw_input("Enter y coord: "))
        a.append([no1, no2, 0])
    print a
    slope = []
    for i in range(no):
        a[i][2] = 1
        j = 0
        slope = [[find_slope(a[i][0], a[i][1], a[j][0], a[j][1]), j]]
        j = j + 1
        while (j < no):
            slope.append([find_slope(a[i][0], a[i][1], a[j][0], a[j][1]), j])
            j = j + 1

        slope.sort()
        j = 1
        temp_arr = []
        temp_arr.append(slope[0])
        while (j < no):
            #            print "temparr:"+str(temp_arr)
            if (i == slope[j][1]):
                j = j + 1
                continue
            if (slope[j][0] == temp_arr[0][0]):
                if (a[slope[j][1]][2] == 0):
                    temp_arr.append(slope[j])

            else:
                if (len(temp_arr) >= 2):
                    print "Following points are in a line:"
                    for k in range(len(temp_arr)):
                        print "[" + str(a[temp_arr[k][1]][0]) + "," + str(
                            a[temp_arr[k][1]][1]) + "]"
                        a[temp_arr[k][1]][2] = 1
                    print "[" + str(a[i][0]) + "," + str(a[i][1]) + "]"
                    for k in range(len(temp_arr) - 1):
                        cv.cvLine(dst, (20 + a[temp_arr[k][1]][0] * 10,
                                        680 - a[temp_arr[k][1]][1] * 10),
                                  (20 + a[temp_arr[k + 1][1]][0] * 10,
                                   680 - a[temp_arr[k + 1][1]][1] * 10),
                                  (0, 0, 0xFF), 2, 0)
                    cv.cvLine(dst, (20 + a[i][0] * 10, 680 - a[i][1] * 10),
                              (20 + a[temp_arr[k + 1][1]][0] * 10,
                               680 - a[temp_arr[k + 1][1]][1] * 10),
                              (0, 0, 0xFF), 2, 0)

                temp_arr = []
                temp_arr.append(slope[j])
            j = j + 1

        if (len(temp_arr) >= 2):
            print "Following points are in a line:"
            for k in range(len(temp_arr)):
                print "[" + str(a[temp_arr[k][1]][0]) + "," + str(
                    a[temp_arr[k][1]][1]) + "]"
                a[temp_arr[k][1]][2] = 1
            print "[" + str(a[i][0]) + "," + str(a[i][1]) + "]"
            for k in range(len(temp_arr) - 1):
                cv.cvLine(dst, (20 + a[temp_arr[k][1]][0] * 10,
                                680 - a[temp_arr[k][1]][1] * 10),
                          (20 + a[temp_arr[k + 1][1]][0] * 10,
                           680 - a[temp_arr[k + 1][1]][1] * 10), (0, 0, 0xFF),
                          2, 0)
                cv.cvLine(dst, (20 + a[i][0] * 10, 680 - a[i][1] * 10),
                          (20 + a[temp_arr[k + 1][1]][0] * 10,
                           680 - a[temp_arr[k + 1][1]][1] * 10), (0, 0, 0xFF),
                          2, 0)

        slope = []
    for k in range(no):
        cv.cvLine(dst, (20 + a[k][0] * 10, 680 - a[k][1] * 10),
                  (20 + a[k][0] * 10, 680 - a[k][1] * 10), (0xFF, 0, 0), 4, 0)

    highgui.cvShowImage('a_window', dst)
    highgui.cvWaitKey(90000)
예제 #44
0
def main():
    usage = "%s [options]  <imgfile> " % (sys.argv[0])
    version = "%prog 0.2\n Longbin Chen, [email protected]"
    oparser = optparse.OptionParser(usage=usage, version=version)
    oparser.add_option('-d',
                       '--display',
                       action="store_true",
                       dest='display',
                       default=False,
                       help='display the image')
    oparser.add_option('-c',
                       '--contour',
                       action="store_true",
                       dest='contour',
                       default=False,
                       help='show object contour')
    oparser.add_option('-i',
                       '--image',
                       action="store_true",
                       dest='image',
                       default=False,
                       help='show original images')
    oparser.add_option('-n',
                       '--number',
                       dest='num',
                       type='int',
                       default=200,
                       help='the number of feature points')
    oparser.add_option('-x',
                       '--enlarge',
                       dest='enlarge',
                       default=1.0,
                       type=float,
                       help='resize images, default:1.0')
    oparser.add_option('-o',
                       '--output',
                       dest='output',
                       default=None,
                       help='output file')
    oparser.add_option('-p',
                       '--pointfile',
                       dest='pointfile',
                       default=None,
                       help='use pointfile ')
    oparser.add_option('-r',
                       '--harris',
                       dest='harris',
                       default=False,
                       action="store_true",
                       help='use harris detector')
    oparser.add_option('-s',
                       '--save',
                       dest='save',
                       default=None,
                       help='save the img file')

    (options, args) = oparser.parse_args(sys.argv)

    if len(args) != 2:
        oparser.parse_args([sys.argv[0], "--help"])
        sys.exit(1)
    if (options.pointfile == None and options.harris == None):
        print >> sys.stderr, "either of  pointfile and harris can be valid"
        sys.exit(1)

    highgui.cvNamedWindow("Corner1", 1)
    ct = Linker(options.contour, options.image, options.enlarge, options.num)
    if (options.pointfile):
        ct.LoadPoints(options.pointfile)
        ct.LinkPoints(args[1])
    else:
        ct.HarrisPoints(args[1])
        ct.LinkPoints(args[1])
    highgui.cvShowImage("Corner1", ct.drawimg)
    highgui.cvWaitKey(0)
    if (options.save):
        highgui.cvSaveImage(options.save, ct.drawimg)
    if (options.output):
        f = open(options.output, "w")
        f.write(OUT.getvalue())
        f.close()
        OUT.close()
예제 #45
0
def main(args):
    global capture
    global hmax, hmin
    highgui.cvNamedWindow('Camera', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvNamedWindow('Hue', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvNamedWindow('Satuation', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvNamedWindow('Value', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvNamedWindow('Laser', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvMoveWindow('Camera', 0, 10)
    highgui.cvMoveWindow('Hue', 0, 350)
    highgui.cvMoveWindow('Satuation', 360, 10)
    highgui.cvMoveWindow('Value', 360, 350)
    highgui.cvMoveWindow('Laser', 700, 40)

    highgui.cvCreateTrackbar("Brightness Trackbar", "Camera", 0, 255,
                             change_brightness)
    highgui.cvCreateTrackbar("hmin Trackbar", "Hue", hmin, 180, change_hmin)
    highgui.cvCreateTrackbar("hmax Trackbar", "Hue", hmax, 180, change_hmax)
    highgui.cvCreateTrackbar("smin Trackbar", "Satuation", smin, 255,
                             change_smin)
    highgui.cvCreateTrackbar("smax Trackbar", "Satuation", smax, 255,
                             change_smax)
    highgui.cvCreateTrackbar("vmin Trackbar", "Value", vmin, 255, change_vmin)
    highgui.cvCreateTrackbar("vmax Trackbar", "Value", vmax, 255, change_vmax)

    print "grabbing camera"
    capture = highgui.cvCreateCameraCapture(0)
    print "found camera"
    highgui.cvSetCaptureProperty(capture, highgui.CV_CAP_PROP_FRAME_WIDTH, 320)
    highgui.cvSetCaptureProperty(capture, highgui.CV_CAP_PROP_FRAME_HEIGHT,
                                 240)

    frame = highgui.cvQueryFrame(capture)
    frameSize = cv.cvGetSize(frame)

    hsv = cv.cvCreateImage(frameSize, 8, 3)
    mask = cv.cvCreateImage(frameSize, 8, 1)
    hue = cv.cvCreateImage(frameSize, 8, 1)
    satuation = cv.cvCreateImage(frameSize, 8, 1)
    value = cv.cvCreateImage(frameSize, 8, 1)
    laser = cv.cvCreateImage(frameSize, 8, 1)

    while 1:
        frame = highgui.cvQueryFrame(capture)

        cv.cvCvtColor(frame, hsv, cv.CV_BGR2HSV)
        #cv.cvInRangeS(hsv,hsv_min,hsv_max,mask)
        cv.cvSplit(hsv, hue, satuation, value, None)

        cv.cvInRangeS(hue, hmin, hmax, hue)
        cv.cvInRangeS(satuation, smin, smax, satuation)
        cv.cvInRangeS(value, vmin, vmax, value)
        #cv.cvInRangeS(hue,0,180,hue)

        cv.cvAnd(hue, value, laser)
        #cv.cvAnd(laser, value, laser)

        cenX, cenY = averageWhitePoints(laser)
        #print cenX,cenY
        draw_target(frame, cenX, cenY)
        #draw_target(frame,200,1)

        highgui.cvShowImage('Camera', frame)
        highgui.cvShowImage('Hue', hue)
        highgui.cvShowImage('Satuation', satuation)
        highgui.cvShowImage('Value', value)
        highgui.cvShowImage('Laser', laser)

        k = highgui.cvWaitKey(10)
        if k == " ":
            highgui.cvDestroyAllWindows()
            highgui.cvReleaseCapture(capture)
            sys.exit()
예제 #46
0
def main():

    ct1 = CurvePoint()
    ct2 = CurvePoint()
    sc = CntSC()
    ang = CntAngle()

    usage = "%prog [options] <imgfile1> <imgfile2>"
    version = "%prog 0.2\nLongbin Chen, [email protected]"
    oparser = optparse.OptionParser(usage=usage, version=version)
    oparser.add_option('-d',
                       '--display',
                       action="store_true",
                       dest='display',
                       default=False,
                       help='display the image')
    oparser.add_option('-n',
                       '--number',
                       dest='num',
                       type="int",
                       default=200,
                       help='the number of feature points')
    oparser.add_option('-s',
                       '--save',
                       dest='save',
                       default=None,
                       help='save the img file')

    oparser.add_option('-o',
                       '--output',
                       dest='output',
                       default=None,
                       help='output file')

    (options, args) = oparser.parse_args(sys.argv)

    if len(args) != 3:
        oparser.parse_args([sys.argv[0], "--help"])
        sys.exit(1)

    ct1.GetContour(args[1], options.num)
    allkeys = []
    for c in ct1.allselected:
        allkeys = allkeys + c
    sc.ExtractFeature(allkeys)
    ang.ExtractFeature(allkeys, 0)
    allkeys = []
    ct2.GetContour(args[2], options.num)
    for c in ct2.allselected:
        allkeys = allkeys + c
    sc.ExtractFeature(allkeys)
    ang.ExtractFeature(allkeys, 0)

    sumscore = []
    matcher = SmithWaterman()
    ct1.bDrawNumber = 0
    ct2.bDrawNumber = 0
    if (options.display):
        ct1.DrawKeyPoints()
        ct2.DrawKeyPoints()
    myfont = cv.cvInitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5)
    idx = -1
    putoriginal(args[1], ct1.drawimg)
    putoriginal(args[2], ct2.drawimg)
    cv.cvNot(ct1.drawimg, ct1.drawimg)
    cv.cvNot(ct2.drawimg, ct2.drawimg)
    for c1 in ct1.allselected:
        idx += 1
        cscore = -100000000
        cpt1 = getdata(c1)
        bX = []
        bY = []
        bestcurve = None
        for c2 in ct2.allselected:
            cpt2 = getdata(c2)
            cost, align, X, Y = matcher.Align(cpt1, cpt2)
            normalized_score = cost - log10(len(c2) + 1) * 1000
            print len(c1), len(c2), cost, normalized_score, cscore
            if (normalized_score > cscore):
                cscore = normalized_score
                bX = X[:]
                bY = Y[:]
                bestcurve = c2
        if (options.display):
            ptcount = 0
            for i in range(len(bX)):
                xi = bX[i]
                yi = bY[i]
                #if (xi == -1):
                #cv.cvDrawCircle(ct2.drawimg, cv.cvPoint(int(bestcurve[yi].x), int(bestcurve[yi].y)),4, cv.cvScalar(255,0,0,0))
                #cv.cvPutText(ct2.drawimg, 'O', cv.cvPoint(int(c2[yi].x), int(c2[yi].y)), myfont, cv.cvScalar(255, 0, 0,0))
                #if (yi == -1):
                #cv.cvDrawCircle(ct1.drawimg, cv.cvPoint(int(c1[xi].x), int(c1[xi].y)),4, cv.cvScalar(255,0,0,0))
                #cv.cvPutText(ct1.drawimg, 'O', cv.cvPoint(int(c1[xi].x), int(c1[xi].y)), myfont, cv.cvScalar(255, 0, 0,0))
                if (xi != -1 and yi != -1):
                    ptcount += 1
                    cv.cvDrawCircle(ct1.drawimg,
                                    cv.cvPoint(int(c1[xi].x), int(c1[xi].y)),
                                    2, clrs[idx])
                    cv.cvPutText(ct1.drawimg, str(ptcount),
                                 cv.cvPoint(int(c1[xi].x), int(c1[xi].y)),
                                 myfont, clrs[idx])
                    cv.cvDrawCircle(
                        ct2.drawimg,
                        cv.cvPoint(int(bestcurve[yi].x), int(bestcurve[yi].y)),
                        2, clrs[idx])
                    cv.cvPutText(
                        ct2.drawimg, str(ptcount),
                        cv.cvPoint(int(bestcurve[yi].x), int(bestcurve[yi].y)),
                        myfont, clrs[idx])
        sumscore.append(cscore)
    print sumscore
    if (options.display):
        highgui.cvNamedWindow("contour1", 1)
        highgui.cvNamedWindow("contour2", 1)
        highgui.cvShowImage("contour1", ct1.drawimg)
        highgui.cvShowImage("contour2", ct2.drawimg)
        highgui.cvWaitKey(0)
    if (options.save):
        mergeimg = mergeimage_83(ct1.drawimg, ct2.drawimg)
        highgui.cvSaveImage("_sw_result.bmp", mergeimg)
예제 #47
0
    if len(sys.argv)>1:
        filename = sys.argv[1]

    # load the image gived on the command line
    image = highgui.cvLoadImage (filename)

    if not image:
        print "Error loading image '%s'" % filename
        sys.exit(-1)

    # create the output image
    col_edge = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 3)

    # convert to grayscale
    gray = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 1)
    edge = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 1)
    cv.cvCvtColor (image, gray, cv.CV_BGR2GRAY)

    # create the window
    highgui.cvNamedWindow (win_name, highgui.CV_WINDOW_AUTOSIZE)

    # create the trackbar
    highgui.cvCreateTrackbar (trackbar_name, win_name, 1, 100, on_trackbar)

    # show the image
    on_trackbar (0)

    # wait a key pressed to end
    highgui.cvWaitKey (0)
예제 #48
0
# -*- coding:utf8 -*-
import opencv
from opencv import highgui as hg

capture = hg.cvCreateCameraCapture(0)
hg.cvNamedWindow("Snapshot")

frames = []
for i in range(10):
    frame = hg.cvQueryFrame(capture)
    frames.append(opencv.cvClone(frame))
    hg.cvShowImage("Snapshot", frame)
hg.cvWaitKey(1000)

hg.cvNamedWindow("hello")
for i in range(10):
    hg.cvShowImage("hello", frames[i])
    hg.cvWaitKey(1000)
"""
import copy
dst=copy.copy(frames[1])
opencv.cvSub(frames[2], frames[1], dst)
hg.cvShowImage("Snapshot", dst)
from IPython.Shell import IPShellEmbed
IPShellEmbed()()
hg.cvWaitKey(10000)
"""
예제 #49
0
import pyrob.util

#def callback_array(iar):
#    left = iar.images[0]
#    right = iar.images[1]
#
#    start   = time.time()
#    leftcv  = to_cv(left)
#    rightcv = to_cv(right)
#    print '%.4f' % (time.time() - start)
#
#    print iar.header.seq,
#    hg.cvShowImage('left', leftcv)
#    hg.cvShowImage('right', rightcv)
#    hg.cvWaitKey(5)


def callback_image(im):
    t = time.time()
    cvim = pyrob.util.ros2cv(im)
    hg.cvShowImage('left', cvim)
    hg.cvWaitKey(5)
    print 'total', time.time() - t


if __name__ == '__main__':
    hg.cvNamedWindow('left', 1)
    rospy.TopicSub('image', Image, callback_image)
    rospy.ready('test_pycv')
    rospy.spin()
예제 #50
0
        p ^= 255

    rgb = {}
    rgb[sector_data[sector][0]] = 255
    rgb[sector_data[sector][1]] = 0
    rgb[sector_data[sector][2]] = p

    return cv.cvScalar(rgb[2], rgb[1], rgb[0], 0)


#############################################################################
# so, here is the main part of the program

if __name__ == '__main__':

    highgui.cvNamedWindow('Blob View', highgui.CV_WINDOW_AUTOSIZE)

    import sys

    try:
        # try to get the device number from the command line
        device = int(sys.argv[1])

        # got it ! so remove it from the arguments
        del sys.argv[1]
    except (IndexError, ValueError):
        # no device number on the command line, assume we want the 1st device
        device = highgui.CV_CAP_ANY

    if len(sys.argv) == 1:
        # no argument on the command line, try to use the camera
예제 #51
0

brightness = 1.0
contrast = 1.0
shots = 0

# so, here is the main part of the program

if __name__ == '__main__':

    # a small welcome
    print "OpenCV Python capture video"

    # first, create the necessary window
    highgui.cvStartWindowThread()
    highgui.cvNamedWindow('Camera', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvStartWindowThread()
    highgui.cvNamedWindow('Color Segmentation', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvStartWindowThread()
    highgui.cvNamedWindow('Canny', highgui.CV_WINDOW_AUTOSIZE)

    # move the new window to a better place
    highgui.cvMoveWindow('Camera', 10, 10)

    try:
        # try to get the device number from the command line
        device = int(sys.argv[1])

        # got it ! so remove it from the arguments
        del sys.argv[1]
    except (IndexError, ValueError):
    return cv.cvScalar (rgb [2], rgb [1], rgb [0], 0)

#############################################################################
# so, here is the main part of the program

if __name__ == '__main__':

    # a small welcome
    print "OpenCV Python wrapper test"
    print "OpenCV version: %s (%d, %d, %d)" % (cv.CV_VERSION,
                                               cv.CV_MAJOR_VERSION,
                                               cv.CV_MINOR_VERSION,
                                               cv.CV_SUBMINOR_VERSION)

    # first, create the necessary windows
    highgui.cvNamedWindow ('Camera', highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvNamedWindow ('Histogram', highgui.CV_WINDOW_AUTOSIZE)

    # move the new window to a better place
    highgui.cvMoveWindow ('Camera', 10, 40)
    highgui.cvMoveWindow ('Histogram', 10, 270)

    try:
        # try to get the device number from the command line
        device = int (sys.argv [1])

        # got it ! so remove it from the arguments
        del sys.argv [1]
    except (IndexError, ValueError):
        # no device number on the command line, assume we want the 1st device
        device = 0
예제 #53
0
        filename = sys.argv[1]

    slider_pos = 70

    # 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)
예제 #54
0
	for j in range(1,5):
		sum = sum + cv.cvGet2D(image,i,j)[0]

print sum
#print cv.cvmGet(iimg.integralImage,size.height-1,size.width-1)
print calcBox(iimg.integralImage,1,1,4)

boxSize = 16
bestValue = -999999.9
best_i = 0
best_j = 0
for i in range(size.height-boxSize):
	for j in range(size.width-boxSize):
		box1 = calcBox(iimg.integralImage,i,j,boxSize)
		box2 = calcBox(iimg.integralImage,i+6,j+6,4)
		value = box2*box2/box1
		if(value > bestValue):
			bestValue = value
			best_i = i
			best_j = j

print "Best I",best_i,"Best j",best_j

draw_target(image,best_i,best_j)

print calcBox(iimg.integralImage,160,230,16)
print calcBox(iimg.integralImage,152,222,32)
highgui.cvNamedWindow("Original",1)
highgui.cvShowImage("Original",image)
highgui.cvWaitKey()
예제 #55
0
    # check that capture device is OK
    if not capture:
        print "Error opening capture device"
        sys.exit(1)

    # display a small howto use it
    print "Hot keys: \n" \
          "\tESC - quit the program\n" \
          "\tr - auto-initialize tracking\n" \
          "\tc - delete all the points\n" \
          "\tn - switch the \"night\" mode on/off\n" \
          "To add/remove a feature point click it\n"

    # first, create the necessary windows
    highgui.cvNamedWindow('LkDemo', highgui.CV_WINDOW_AUTOSIZE)

    # register the mouse callback
    highgui.cvSetMouseCallback('LkDemo', on_mouse, None)

    while 1:
        # do forever

        # 1. capture the current image
        frame = highgui.cvQueryFrame(capture)
        if frame is None:
            # no image captured... end the processing
            break

        if image is None:
            # create the images we need