def main():
    args = sys.argv[1:]
    imgpaths = ['contest_oc.png']
    T = cv.LoadImage('target_oc.png', cv.CV_LOAD_IMAGE_GRAYSCALE)
    T_smooth = cv.CreateImage((T.width, T.height), T.depth, T.channels)
    cv.Smooth(T, T_smooth, cv.CV_GAUSSIAN, param1=17, param2=17)
    allmatches = find_matches(imgpaths, T_smooth, C=0.8)
    for imgpath, matches in allmatches.iteritems():
        print "For image: {0}, {1} matches found.".format(
            imgpath, len(matches))
        I = cv.LoadImage(imgpath, cv.CV_LOAD_IMAGE_COLOR)
        for (x, y, score) in matches:
            cv.Circle(I, (x, y), 15, cv.RGB(0, 60, 255), thickness=4)
        cv.SaveImage("allmatches_result.png", I)
    print "Done."
Ejemplo n.º 2
0
    def setUp(self):
        """
        This method is called before each test
        """
        self.img_1c = cv.LoadImage(
            "data/tippy.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)  # 1 channel image
        self.img_3c = cv.LoadImage("data/tippy.jpg",
                                   cv.CV_LOAD_IMAGE_COLOR)  # 3 channel image
        self.img_fake_2c = cv.CreateImage((15, 15), cv.IPL_DEPTH_8U,
                                          2)  # 2 channels
        self.fake_img = 10  # non Image

        self.false_mode = "A"  # non True/False (or 0/1) argument
        self.fake_mode = 100  # non True/False (or 0/1) argument
        self.fake_name = 100  # non True/False (or 0/1) argument
Ejemplo n.º 3
0
def main(args):
    if args.output_directory:
        directory = args.output_directory
    else:
        directory = os.path.dirname(args.compared_image)
        print "No output directory specified. Defaulting to %s"%directory
    if not os.path.exists(directory):
        os.makedirs(directory)
    if args.output_prefix:
        prefix = args.output_prefix
    else:
        prefix_c = os.path.splitext(os.path.basename(args.compared_image))[0]
        prefix_r = os.path.splitext(os.path.basename(args.reference_image))[0]
        prefix = "%s_TO_%s"%(prefix_c, prefix_r) 
        print "No output prefix selected. Defaulting to %s"%prefix
    output_file = "%s/%s.matches"%(directory, prefix)
    if not args.input_match_file:
        args.input_match_file = output_file
    if not args.force_overwrite and os.path.exists( args.input_match_file ):
        match_set_old = MatchSet( args.compared_image, args.reference_image )
        match_set_old.read_from_file( args.input_match_file )
        for match in match_set_old.get_matches():
            compare_pts.append(match.compare_pt)
            reference_pts.append(match.reference_pt)
            strengths.append(match.strength)
    compared_image = cv.LoadImage( args.compared_image)
    reference_image = cv.LoadImage( args.reference_image )
    compare_window = ClickWindow( compared_image, args.compare_zoom_out, COMPARE)
    reference_window = ClickWindow( reference_image, args.reference_zoom_out, REFERENCE)

    global mode
    global strength
    while(True):
        cont = update_all_windows()
        if not cont:
            break
        if compare_window.click_pt and reference_window.click_pt:
            compare_pts.append(compare_window.click_pt)
            reference_pts.append(reference_window.click_pt)
            strengths.append(strength)
            compare_window.clear_click_pt()
            reference_window.clear_click_pt()
    if save_flag:
        match_set = MatchSet(args.compared_image, args.reference_image)
        for i in range( len(compare_pts) ):
            match_set.add_match( compare_pts[i], reference_pts[i], strengths[i] )
        match_set.save_to_file( output_file )
        print "Saved to %s"%output_file
Ejemplo n.º 4
0
def video_descriptor(obj, i, v_dictionary, v_noise):

    depth = cv.LoadImage(
        globals.path + 'img/' + obj + '-' + str(i) + '-depth.png',
        cv.CV_LOAD_IMAGE_GRAYSCALE)
    mask = cv.LoadImage(globals.path + 'mask.png', cv.CV_LOAD_IMAGE_GRAYSCALE)

    if v_noise > 0:
        rgb = cv2.imread(
            globals.path + 'img/' + obj + '-' + str(i) + '-rgb.png',
            cv.CV_LOAD_IMAGE_GRAYSCALE)
        noise = np.random.randn(*rgb.shape) * v_noise

        # Add this noise to image
        noisy = rgb + noise
        cv2.imwrite(globals.path + 'noisy.png', noisy)
        rgb = cv.LoadImage(globals.path + 'noisy.png',
                           cv.CV_LOAD_IMAGE_GRAYSCALE)
        #rgb = noisy

    else:
        rgb = cv.LoadImage(
            globals.path + 'img/' + obj + '-' + str(i) + '-rgb.png',
            cv.CV_LOAD_IMAGE_GRAYSCALE)

    #cv.fromarray(rgb)

    bridge = CvBridge()
    rgb_image = bridge.cv_to_imgmsg(rgb)
    depth_image = bridge.cv_to_imgmsg(depth)
    mask_image = bridge.cv_to_imgmsg(mask)

    #BASE Keypoint descriptors
    keypoint_descriptors = []
    rospy.wait_for_service('masked_base_descriptor_service')
    try:
        descriptor_request = rospy.ServiceProxy(
            'masked_base_descriptor_service', masked_service)
        response = descriptor_request(rgb=rgb_image,
                                      depth=depth_image,
                                      mask=mask_image)
        base_descriptor = bridge.imgmsg_to_cv(response.descriptor)

        keypoint_descriptors = np.array(base_descriptor)
        keypoint_descriptors = keypoint_descriptors.tolist()

    except rospy.ServiceException, e:
        print "Service call failed: %s" % e
Ejemplo n.º 5
0
  def __init__(self, path):
    """You provide the path of the dataset and then the input to channel 0 is the background subtraction mask."""
    self.path = path
    
    # Open the region of interest and convert it into a mask we can use...
    roi = cv.LoadImage(os.path.join(path, 'ROI.bmp'))
    self.roi = (cv2array(roi)!=0).astype(numpy.uint8)
    if len(self.roi.shape)==3: self.roi = self.roi[:,:,0]

    # Get the temporal range of the frames we are to analyse...
    data = open(os.path.join(path, 'temporalROI.txt'), 'r').read()
    tokens = data.split()
    assert(len(tokens)==2)
    self.start = int(tokens[0])
    self.end = int(tokens[1]) # Note that these are inclusive.
    
    # Confusion matrix - first index is truth, second guess, bg=0, fg=1...
    self.con = numpy.zeros((2,2), dtype=numpy.int32)
    
    # Shadow matrix - for all pixels that are in shadow records how many are background (0) and how many are foreground (1)...
    self.shadow = numpy.zeros(2, dtype=numpy.int32)
    
    # Basic stuff...
    self.frame = 0

    self.video = None
    self.channel = 0
Ejemplo n.º 6
0
def haarface (filename):
    
    source_image = cv.LoadImage(filename, cv.CV_LOAD_IMAGE_COLOR)
  
 

    hf = Haarface (source_image)
Ejemplo n.º 7
0
def thin_processing(enhanced_image):


    array = [0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,
         1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,
         0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,
         1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,
         1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,
         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
         1,1,0,0,1,1,0,0,1,1,0,1,1,1,0,1,
         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
         0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,
         1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,
         0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,
         1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0,
         1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,
         1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0,
         1,1,0,0,1,1,0,0,1,1,0,1,1,1,0,0,
         1,1,0,0,1,1,1,0,1,1,0,0,1,0,0,0]


    cv2.imwrite("enhanced.bmp", enhanced_image)
    image = cv.LoadImage("enhanced.bmp",0)
    iTwo = Two(image)
    iThin = thin(iTwo, array)
    invertThin = Two(iThin)
    #cv.WaitKey(0)

    return invertThin
Ejemplo n.º 8
0
def main(argv):
    if len(argv) < 10:
        print('Usage: %s input-file fx fy cx cy k1 k2 p1 p2 output-file' %
              argv[0])
        sys.exit(-1)

    src = argv[1]
    fx, fy, cx, cy, k1, k2, p1, p2, output = argv[2:]

    intrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)
    cv.Zero(intrinsics)
    intrinsics[0, 0] = float(fx)
    intrinsics[1, 1] = float(fy)
    intrinsics[2, 2] = 1.0
    intrinsics[0, 2] = float(cx)
    intrinsics[1, 2] = float(cy)

    dist_coeffs = cv.CreateMat(1, 4, cv.CV_64FC1)
    cv.Zero(dist_coeffs)
    dist_coeffs[0, 0] = float(k1)
    dist_coeffs[0, 1] = float(k2)
    dist_coeffs[0, 2] = float(p1)
    dist_coeffs[0, 3] = float(p2)

    src = cv.LoadImage(src)
    dst = cv.CreateImage(cv.GetSize(src), src.depth, src.nChannels)
    mapx = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_32F, 1)
    mapy = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_32F, 1)
    cv.InitUndistortMap(intrinsics, dist_coeffs, mapx, mapy)
    cv.Remap(src, dst, mapx, mapy,
             cv.CV_INTER_LINEAR + cv.CV_WARP_FILL_OUTLIERS, cv.ScalarAll(0))
    # cv.Undistort2(src, dst, intrinsics, dist_coeffs)

    cv.SaveImage(output, dst)
Ejemplo n.º 9
0
def LoadImage(filename, rotate180=False, RGB=False):
    '''wrapper around cv.LoadImage that also handles PGM.
	It always returns a colour image of the same size'''
    if filename.endswith('.pgm'):
        from ..image import scanner
        try:
            pgm = PGM(filename)
        except Exception as e:
            print('Failed to load %s: %s' % (filename, e))
            return None
        im_full = numpy.zeros((960, 1280, 3), dtype='uint8')
        if RGB:
            scanner.debayer_RGB(pgm.array, im_full)
        else:
            scanner.debayer(pgm.array, im_full)
        if rotate180:
            scanner.rotate180(im_full)
        return cv.GetImage(cv.fromarray(im_full))
    img = cv.LoadImage(filename)
    if rotate180:
        from ..image import scanner
        img = numpy.ascontiguousarray(cv.GetMat(img))
        scanner.rotate180(img)
        img = cv.GetImage(cv.fromarray(img))
    return img
def decode_v2_wrapper(imgpath,
                      markpath,
                      Icol,
                      H_GAP=7,
                      W_MARK=WIDTH_MARK,
                      H_MARK=HEIGHT_MARK,
                      idx2tol=None):
    I = cv.LoadImage(imgpath, cv.CV_LOAD_IMAGE_GRAYSCALE)
    result = decode_v2(I,
                       markpath,
                       Icol,
                       False,
                       _imgpath=imgpath,
                       H_GAP=H_GAP,
                       W_MARK=W_MARK,
                       H_MARK=H_MARK,
                       idx2tol=idx2tol)
    if result == None and not DEBUG_SKIP_FLIP:
        print_dbg("...Trying FLIP...")
        cv.ResetImageROI(I)
        result = decode_v2(I,
                           markpath,
                           Icol,
                           True,
                           _imgpath=imgpath,
                           H_GAP=H_GAP,
                           W_MARK=W_MARK,
                           H_MARK=H_MARK,
                           idx2tol=idx2tol)

    if result == None:
        return None, None, None
    else:
        decoding, isflip, bbs_out = result
        return (decoding, isflip, bbs_out)
Ejemplo n.º 11
0
def application(request):
	tempfile = NamedTemporaryFile()

	try:
		if request.method != 'GET':
			raise MethodNotAllowed(['GET'])
		if request.args.get('url') is None:
			raise BadRequest('Missing parameter url')

		try:
			response = urllib2.urlopen(request.args.get('url'))
			data = response.read()
		except urllib2.HTTPError:
			raise NotFound('url does not exist')

		try:
			tempfile.file.write(data)
			image = cv.LoadImage(tempfile.name, 1)
		except Exception:
			raise BadRequest('No picture found on url')

		faces = detect(image)

		response = Response(json.dumps(faces))
	except HTTPException, e:
		return e
Ejemplo n.º 12
0
    def detect(self, image):
        """
        Determines the location of one or more faces in the given image.
        """
        if isinstance(image, basestring):
            image = cv.LoadImage(image)

        image_size = cv.GetSize(image)

        # Convert to grayscale.
        grayscale = cv.CreateImage(image_size, 8, 1)
        cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
        #cv.EqualizeHist(grayscale, grayscale)
        _image = image
        image = grayscale

        # Assume an image equal to the target size contains a single face.
        target_size = (self.target_width, self.target_height)
        if image_size == target_size:
            rect = 0, 0, self.target_width, self.target_height
            neighbors = None
            return [(rect, neighbors)], image

        # Locate one or more faces in the image.
        t0 = time.time()
        faces = cv.HaarDetectObjects(image, self.face_cascade,
                                     cv.CreateMemStorage(0), 1.2, 2, 0,
                                     (20, 20))
        t1 = time.time() - t0
        LOG.info('Haar detect took %.2f seconds.' % (t1, ))
        return faces, image
Ejemplo n.º 13
0
def _do_decode_ballots(ballots, mark_path, queue=None):
    """ 
    Decode ES&S barcode for all ballots
    Input:
        ballots   : {int ballotID: [imgpath_side0, ...]}.
        mark_path : path to example timing mark representing '1' in bitstring
        queue     : used for multiprocessing
    Output:
        results: {ballotid: [(bitstring, is_flipped, bit_locations), ...]}
    """

    try:
        mark = cv.LoadImage(mark_path, cv.CV_LOAD_IMAGE_GRAYSCALE)
        results = {}
        for ballotid, imgpaths in ballots.iteritems():
            balresults = []
            for imgpath in imgpaths:
                bitstring, is_flipped, bit_locations = es_s.decode(
                    imgpath, mark, bits)
                balresults.append((bitstring, is_flipped, bit_locations))
            results[ballotid] = balresults
            if queue:
                queue.put(True)
        return results
    except:
        traceback.print_exc()
def negative_cropped_oriented_boxes(xml_filename, image_filename):
    image = cv.LoadImage(image_filename)
    size = cv.GetSize(image)
    # Transform the generator to a list, to avoid reparsing the xml file
    oriented_boxes = list(read_oriented_boxes(xml_filename))
    taboo_list = list(oriented_boxes)
    for i in range(3):
        for box in oriented_boxes:
            x, y, width, height, angle, flip = box
            for trial in range(10):
                # Propose a negative box (it can extend outside the image a little)
                n_angle = random.uniform(-pi, pi)
                n_x = random.uniform(width / 2, size[0] - 1 - width / 2)
                n_y = random.uniform(height / 2, size[1] - 1 - height / 2)
                n_flip = random.choice([0, 1])
                candidate = [n_x, n_y, width, height, n_angle, n_flip]
                for b in taboo_list:
                    if oriented_boxes_overlap(b, candidate):
                        # Candidate is invalid. Try another random location
                        break
                else:
                    # No overlap with any other box, this is a valid negative example
                    taboo_list.append(
                        candidate)  # We dont want to resample the same
                    yield crop_single_oriented_box(candidate, image)
                    # Exit the rejection sampling loop and move on to the next box
                    break
Ejemplo n.º 15
0
    def find_faces(self, file_name=None):
        try:
            import cv
        except ImportError:
            return

        if file_name is None:
            return

        logger.debug("%s: %s" % (self.__class__.__name__, file_name))

        imcolor = cv.LoadImage(file_name)  #@UndefinedVariable
        detectors = [
            "haarcascade_frontalface_default.xml",
            "haarcascade_profileface.xml"
        ]
        for detector in detectors:
            haarFace = cv.Load(os.path.join(settings.STATIC_ROOT,
                                            detector))  # @UndefinedVariable
            storage = cv.CreateMemStorage()  #@UndefinedVariable
            detectedFaces = cv.HaarDetectObjects(
                imcolor, haarFace, storage,
                min_size=(200, 200))  #@UndefinedVariable
            if detectedFaces:
                for face in detectedFaces:
                    fata = DetectedFace(imagine=self,
                                        x=face[0][0],
                                        y=face[0][1],
                                        width=face[0][2],
                                        height=face[0][3])
                    fata.save()

        self.is_face_processed = True
        self.save()
Ejemplo n.º 16
0
 def Cam_Video(self):
     # Recebe uma imagem e manda mostrar na tela
     Actions.Receive_File()
     if (self.ui.Record_Button.isFlat()):
         frame = cv.LoadImage("img/img.jpg")
         cv.WriteFrame(self._writer, frame)
     self.Image_Show("img/img.jpg")
    def calctaille(out_img):
    total=0         
    nb=0
    for j in range(0 , cv.GetSize(out_img)[0]):
        cpt=0
        for i in range(0 , cv.GetSize(out_img)[1]):
            if out_img[i,j] == 255:
                cpt += 1
                
        total=total+cpt
        if cpt != 0:
            nb += 1 
    moy = total / nb
    print "La taille est de : " + str(moy)

#Fonction appelee lorsque l'on clique avec la souris
    def printcoords(event):
        #On affiche dans la console les coordonnees X & Y
        print (event.x,event.y)
    seed = (event.x,event.y)
    threshold = 20
    img = cv.LoadImage(File, cv.CV_LOAD_IMAGE_GRAYSCALE)
    out_img = simple_region_growing(img, seed, threshold)
    calctaille(out_img)
    cv.SaveImage('sortie.png', out_img)
    print "Ouvrez le fichier sortie.png pour visualiser"
    #Evenement du clic de la souris
    canvas.bind("<Button 1>",printcoords)
    
    cv.WaitKey(0)
    root.mainloop()
Ejemplo n.º 18
0
def loadSegments():
    global segments
    segments = os.listdir(segment_dir)
    segments = map(
        lambda name: (os.path.splitext(name)[0][0],
                      cv.LoadImage(os.path.join(segment_dir, name), cv.
                                   CV_LOAD_IMAGE_GRAYSCALE)), segments)
Ejemplo n.º 19
0
    def __get_key_points(self, image_path):

        DESCRIPTORS_MIN = 300
        DESCRIPTORS_MAX = 420

        keypoints = 0
        descriptors = 0

        range = 600
        range_gap = 40
        do_surf = True

        image = cv.LoadImage(image_path, cv.CV_LOAD_IMAGE_GRAYSCALE)

        while (do_surf):

            (keypoints, descriptors) = cv.ExtractSURF(image, None,
                                                      cv.CreateMemStorage(),
                                                      (1, range, 3, 1))
            do_surf = False

            print "Descriptors: %d (range=%d)" % (len(descriptors), range)

            if (len(descriptors) < DESCRIPTORS_MIN):
                range = range - range_gap

            if (len(descriptors) > DESCRIPTORS_MAX):
                range = range + range_gap

            if (len(descriptors) >= DESCRIPTORS_MIN
                    and len(descriptors) <= DESCRIPTORS_MAX):
                do_surf = False

        return (keypoints, descriptors)
Ejemplo n.º 20
0
def train_test():
	train_subdir = "data/train/"
	test_subdir = "data/test/"
	img_kinds = ["happy", "anger", "neutral", "surprise"]
	models = {}
	params = "-t 0 -c 3"
	svm_params = {	"happy": params,
					"anger": params,
					"neutral": params,
					"surprise": params}

	#train the models
	print 'BUILDING TRAIN MODELS'
	for img_kind in img_kinds:
		print "\t" + img_kind
		problem = build_problem(img_kind, train_subdir)
		param = svm.svm_parameter(svm_params[img_kind])
		models[img_kind] = svmutil.svm_train(problem, param)
	print '================================'

	#for each image in test set let's see what is the answe
	total_count = 0
	correct_count = 0
	wrong_count = 0

	print 'TESTING MODELS'
	for img_kind in img_kinds:
		images = glob.glob(test_subdir + "f_" + img_kind + "*.jpg")
		for image in images:
			print "\t" + image
			image_data = cv.LoadImage(image)
			
			# Let's see what are the results from the models
			results = {}
			for kind in img_kinds:
				test_data = get_image_features(image_data, True, kind)
				predict_input_data = []
				predict_input_data.append(test_data)

				# do svm query
				(val, val_2, label) = svmutil.svm_predict([1] ,predict_input_data, models[kind])
				results[kind] = label[0][0]
			
			sorted_results = sorted(results.iteritems(), key=operator.itemgetter(1))
			result = sorted_results[len(sorted_results)-1][0]

			total_count += 1
			if result == img_kind:
				print 'YES :' + result
				correct_count += 1
			else:
				print 'NO  :' + result
				print sorted_results
				wrong_count += 1
			print '-----------------------'
	print '================================'
	print "Total Pictures: " + str(total_count)
	print "Correct: " + str(correct_count)
	print "Wrong: " + str(wrong_count)
	print "Accuracy: " + str(correct_count/float(total_count) * 100)
Ejemplo n.º 21
0
def main():
    # Uses xawtv. Gstreamer can be used instead, but I found it much slower
    os.system("v4lctl snap jpeg 640x480 face.jpg")
    image = cv.LoadImage("face.jpg")
    detectObject(image)
    displayObject(image)
    cv.SaveImage("face.jpg", image)
    def getNextImage(self):
        """returns a image which can be used for calibration"""

        #return kinect frame
        if self.source == "kinect":
            if self.imageDepth == 8:
                return convert_16to8(self.depth_retreiver.get_image())
                #The new openni image_raw gives 8bit image
                return self.depth_retreiver.get_image()

            elif self.imageDepth == 11 or self.imageDepth == 16:
                return self.depth_retreiver.get_image()
            else:
                print "Illegal image depth: '" + str(
                    self.imageDepth) + "'. Using 8 bit"
                return convert_16to8(self.depth_retreiver.get_image())

        # return testimage
        elif self.source == "file":
            # return None if there are no more images in the filelist
            if len(self.filelist) <= self.currentFrame:
                print "No more images in filelist..."
                return None
            else:
                return cv.LoadImage(self.filelist[self.currentFrame],
                                    cv.CV_LOAD_IMAGE_GRAYSCALE)
Ejemplo n.º 23
0
def process(infile):
    image = cv.LoadImage(infile)
    if image:
        faces = detect_object(image)

    im = Image.open(infile)
    path = os.path.abspath(infile)
    #save_path = os.path.splitext(path)[0]+"_face"
    save_path = "face"
    if os.path.isdir(save_path):
        shutil.rmtree(save_path)
    try:
        os.mkdir(save_path)
    except:
        pass
    if faces:
        draw = ImageDraw.Draw(im)
        count = 0
        for f in faces:
            count += 1
            draw.rectangle(f, outline=(255, 0, 0))
            a = im.crop(f)
            file_name = os.path.join(save_path, str(count) + ".jpg")
            #       print file_name
            a.save(file_name)

        drow_save_path = os.path.join(save_path, "out.jpg")
        im.save(drow_save_path, "JPEG", quality=80)
    else:
        print "Error: cannot detect faces on %s" % infile
Ejemplo n.º 24
0
	def rotacion_y_posicion_robot(self,robo_x=200,robo_y=100,robo_th=80):
		"""
		\brief graficar el robot en el lienzo de mapa 
		\param self no se necesita incluirlo al utilizar la funcion ya que se lo pone solo por ser la definicion de una clase
		\param robo_x coordenada x de la odometria del robot 
		\param robo_y coordenada y de la odometria del robot 
		\param robo_th Valor Th del robot
		\return Nada
		"""
		image_mapa=cv.LoadImage(self.nombre_archivo1, cv.CV_LOAD_IMAGE_COLOR)
		dimensiones_robot=self.dimensiones_robot
		image1=cv.CreateImage(dimensiones_robot,8,3)
		image_mascara=cv.CreateImage(dimensiones_robot,8,1)
		
		##rotacion
		#Rotar el robot
		src_center=dimensiones_robot[0]/2,dimensiones_robot[1]/2
		rot_mat=cv.CreateMat( 2, 3, cv.CV_32FC1 )
		cv.GetRotationMatrix2D(src_center, robo_th, 1.0,rot_mat);
		cv.WarpAffine(self.robot,image1,rot_mat)
		#crear filtro para negro
		cv.InRangeS(image1,cv.RGB(0,0,0),cv.RGB(14,14,14),image_mascara)
		cv.Not(image_mascara,image_mascara)
		#cv.ReleaseImage(image1)
		
		#reducir y posicion
		cv.SetImageROI(image_mapa,(robo_x,robo_y, dimensiones_robot[0], dimensiones_robot[1]));
		cv.Copy(image1,image_mapa,mask=image_mascara)
		cv.ResetImageROI(image_mapa);
		cv.SaveImage(self.nombre_archivo, image_mapa) #Saves the image#
Ejemplo n.º 25
0
def main(args):
    image = cv.LoadImage( args.input_image)
    featuremap = FeatureMap()
    featuremap.read_from_file( args.input_features )
    classifier = load_classifier_from_file( args.classifier )
    if not classifier.is_trained():
        print "Warning: using an untrained classifier. This will probably break."
    label_set = LabelSet()
    label_set.read_from_file( args.label_set )

    window = ClickWindow( image, args.zoom_out)

    while(True):
        cont = update_all_windows()
        if not cont:
            break
        if window.update_label:
            click_pt = window.click_pt
            closest_pt = min( featuremap.get_feature_points(),
                              key = lambda pt: l2_dist(pt,click_pt) )
            feature = featuremap.get_feature( closest_pt )
            shape = featuremap.get_shape( closest_pt )
            size = featuremap.get_size( closest_pt )

            label = classifier.predict_label( feature )
            label_name = "None" if label==0 else label_set.get_label_name(label)
            label_color = cv.RGB(0,0,0) if label==0 else label_set.get_label_color(label)
            print "Predicted label: %d (%s)"%(label, label_name);
            window.set_patch( closest_pt, shape, size, label_color )
            window.update_label = False
Ejemplo n.º 26
0
def imagen_homografia(n):
     
    global points, width, height,teclado
     
    urllib.urlretrieve("http://192.168.0.100:8080/photo.jpg", "foto.jpg")
    foto=cv.LoadImage('foto.jpg')
    im_in= cv.CloneImage(foto)
    #CALIBRACION
    width, height = cv.GetSize(im_in)
    im = cv.CloneImage(foto)
    if n == 0 and (teclado ==1 or teclado ==3):
      cv.ShowImage('Escoger 4 puntos',im)
      cv.SetMouseCallback('Escoger 4 puntos', mouse, im)
      cv.WaitKey(0)
      guardarpoints(points)      
      h**o = homografia(im_in.width, im_in.height, im.width, im.height)
      cv.Save('homography.cvmat', h**o)
    else:
      points = cargarpoints()
      h**o = homografia(im_in.width, im_in.height, im.width, im.height)
    out_big = cv.CloneImage(im_in)
    cv.WarpPerspective(im_in, out_big, h**o)
    out_small = cv.CloneImage(im)
    cv.Resize(out_big, out_small)
    return out_small, out_big
Ejemplo n.º 27
0
 def detect(self, obj, event):
     # First, reset image, in case of previous detections:
     active_handle = self.get_active('Media')
     media = self.dbstate.db.get_media_from_handle(active_handle)
     self.load_image(media)
     min_face_size = (50, 50)  # FIXME: get from setting
     self.cv_image = cv.LoadImage(self.full_path,
                                  cv.CV_LOAD_IMAGE_GRAYSCALE)
     o_width, o_height = self.cv_image.width, self.cv_image.height
     cv.EqualizeHist(self.cv_image, self.cv_image)
     cascade = cv.Load(HAARCASCADE_PATH)
     faces = cv.HaarDetectObjects(self.cv_image, cascade,
                                  cv.CreateMemStorage(0), 1.2, 2,
                                  cv.CV_HAAR_DO_CANNY_PRUNING,
                                  min_face_size)
     references = self.find_references()
     rects = []
     o_width, o_height = [
         float(t) for t in (self.cv_image.width, self.cv_image.height)
     ]
     for ((x, y, width, height), neighbors) in faces:
         # percentages:
         rects.append((x / o_width, y / o_height, width / o_width,
                       height / o_height))
     self.draw_rectangles(rects, references)
Ejemplo n.º 28
0
def main():
    global val1, val2
    img = cv.LoadImage(sys.argv[1])
    if img:
        cv.NamedWindow("bar")
        img2 = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 1)
        img21 = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 1)
        img3 = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_16S, 1)
        img4 = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 1)
        cv.CvtColor(img, img2, cv.CV_BGR2GRAY)
        cv.EqualizeHist(img2, img21)
        stor = cv.CreateMemStorage()
        cv.AdaptiveThreshold(img21, img4, 255,
                             cv.CV_ADAPTIVE_THRESH_GAUSSIAN_C,
                             cv.CV_THRESH_BINARY_INV, 7, 7)
        cont = cv.FindContours(img4, stor, cv.CV_RETR_LIST,
                               cv.CV_CHAIN_APPROX_NONE)
        img5 = cv.CloneImage(img)
        while cont:
            if validate_contour(cont):
                cv.DrawContours(img5, cont, (255, 255, 255), (255, 255, 255),
                                0, 2, 8, (0, 0))
            cont = cont.h_next()
        cv.ShowImage("bar", img5)
        cv.WaitKey(0)
    def test(self):
        arr = cv.LoadImage("../samples/c/lena.jpg", 0)
        original = cv.CloneImage(arr)
        size = cv.GetSize(arr)
        eig_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
        temp_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
        threshes = [ x / 100. for x in range(1,10) ]

        results = dict([(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris = 1)) for t in threshes])

        # Check that GoodFeaturesToTrack has not modified input image
        self.assert_(arr.tostring() == original.tostring())

        # Check for repeatability
        for i in range(10):
            results2 = dict([(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris = 1)) for t in threshes])
            self.assert_(results == results2)

        for t0,t1 in zip(threshes, threshes[1:]):
             r0 = results[t0]
             r1 = results[t1]

             # Increasing thresh should make result list shorter
             self.assert_(len(r0) > len(r1))

             # Increasing thresh should monly truncate result list
             self.assert_(r0[:len(r1)] == r1)
Ejemplo n.º 30
0
def images_from_random_people(all_people, max_pics, recognizer):
    num_to_train = 8
    id_counter = 2
    random.shuffle(all_people)
    all_people = all_people
    num_training_added = 0
    for person in all_people:
        label_dict[recognizer][id_counter] = person
        if "DS_STORE" in face_dir + person:
            continue
        try:
            all_pictures = os.listdir(face_dir + person + "/")
        except:
            continue
        if len(all_pictures) < 20:
            continue
        random.shuffle(all_pictures)
        all_pictures = all_pictures[:max_pics]
        for picture_name in all_pictures:
            picture_dir = face_dir + person + "/"
            full_path = picture_dir + picture_name
            try:
                face = cv.LoadImage(full_path, cv2.IMREAD_GRAYSCALE)
            except IOError:
                continue
            yield face[:, :], id_counter
        num_training_added += 1
        if num_training_added > num_to_train:
            break
        id_counter += 1