예제 #1
0
    def calibrate(self):
        # Get the pattern parameters
        h_dim = utils.getAnswer(
            "Number of inner corners on the horizontal dimension ? ",
            '12345678910')

        v_dim = utils.getAnswer(
            "Number of inner corners on the vertical dimension ? ",
            '12345678910')

        # Enter the number of squares over each dimensions
        self.pattern_size = (int(h_dim), int(v_dim))
        print "Chessboard dimensions : {} x {}"\
            .format(self.pattern_size[0], self.pattern_size[1])

        get_square_size = False
        while not (get_square_size):
            sq_size = raw_input("Horizontal Size (in m) of the squares ? ")

            try:
                self.sq_size_h = float(sq_size)
                get_square_size = True

            except ValueError:
                print "Cannot determine dimension"

        get_square_size = False
        while not (get_square_size):
            sq_size = raw_input("Vertical Size (in m) of the squares ? ")

            try:
                self.sq_size_v = float(sq_size)
                get_square_size = True

            except ValueError:
                print "Cannot determine dimension"

        # Get the root folder, Get all the subfolders,
        # do all the subsequent calibrations and record the results
        path = raw_input("Root path for the calibration folders : ")

        for dirpath, dirnames, filenames in os.walk(path):

            for dir in dirnames:
                if not dir[0] == '.':
                    path = dirpath + dir

                    settings = (False, True, True, True, path,
                                self.pattern_size, (self.sq_size_h,
                                                    self.sq_size_v), False)

                    new_cam = cam_calib.cameraCalibration(settings)

                    print "\nCalibrating using files in folder : {}".format(
                        dir)

                    if (os.path.exists(path + '/calib_results.txt')):
                        print "Folder {} already contains calibration results"
                    else:
                        new_cam.calibrate()
예제 #2
0
    def calibrate(self):
        # Get the pattern parameters
        h_dim = utils.getAnswer(
        "Number of inner corners on the horizontal dimension ? ", '12345678910')

        v_dim = utils.getAnswer(
        "Number of inner corners on the vertical dimension ? ", '12345678910')

        # Enter the number of squares over each dimensions
        self.pattern_size = (int(h_dim), int(v_dim))
        print "Chessboard dimensions : {} x {}"\
            .format(self.pattern_size[0], self.pattern_size[1])
    
        get_square_size = False
        while not(get_square_size):
            sq_size = raw_input("Horizontal Size (in m) of the squares ? ")

            try:
                self.sq_size_h = float(sq_size)
                get_square_size = True

            except ValueError:
                print "Cannot determine dimension"

        get_square_size = False
        while not(get_square_size):
            sq_size = raw_input("Vertical Size (in m) of the squares ? ")

            try:
                self.sq_size_v = float(sq_size)
                get_square_size = True

            except ValueError:
                print "Cannot determine dimension"    

        # Get the root folder, Get all the subfolders, 
        # do all the subsequent calibrations and record the results 
        path = raw_input("Root path for the calibration folders : ")           
        
        for dirpath, dirnames, filenames in os.walk(path):

            for dir in dirnames :
                if not dir[0] == '.':
                    path = dirpath + dir
                    
                    settings = (False, True, True, True, path, self.pattern_size , 
                                (self.sq_size_h,self.sq_size_v), False)                
                    
                    new_cam = cam_calib.cameraCalibration(settings)
                    
                    print "\nCalibrating using files in folder : {}".format(dir)                
                    
                    if (os.path.exists(path +'/calib_results.txt')):
                        print "Folder {} already contains calibration results"
                    else :
                        new_cam.calibrate()
    def _record_pattern_cam(self):
        n_frames = 0

        pattern_points = np.zeros((np.prod(self.params.pattern_size), 3), np.float32)
        pattern_points[:, :2] = np.indices(self.params.pattern_size).T.reshape(-1, 2)

        cv2.namedWindow("captureStream", cv2.CV_WINDOW_AUTOSIZE)
        cv2.namedWindow("patternDetection", cv2.CV_WINDOW_AUTOSIZE)

        save_files = utils.getAnswer("Would you like to save picture files ? (y/n)", 'yn') == 'y'
        finished_parsing = False

        cam_online = utils.getCam()

        if cam_online:
            while not finished_parsing and (self.params.max_frames_i == -1 or n_frames < self.params.max_frames_i):
                success, new_frame = cam_online.read()

                if success:
                    # Convert to B&W (if necessary ?)
                    grey_frame = cv2.cvtColor(new_frame, cv2.COLOR_BGR2GRAY)
                    found, corners = cv2.findChessboardCorners(grey_frame, self.params.pattern_size)

                    cv2.imshow("captureStream", new_frame)
                    cv2.waitKey(2)

                    if found:
                        # Refine position
                        term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)

                        cv2.cornerSubPix(grey_frame, corners, (11, 11), (-1, -1), term)

                        # Draw detected pattern
                        cv2.drawChessboardCorners(new_frame, self.params.pattern_size, corners, found)
                        cv2.imshow("patternDetection", new_frame)
                        cv2.waitKey()

                        # Store values
                        self.img_points.append(corners.reshape(-1, 2))
                        self.obj_points.append(pattern_points)

                        n_frames += 1
                        print("{} patterns found".format(n_frames))

                        if save_files:
                            cv2.imwrite("calib_{}.bmp".format(n_frames), grey_frame)
                            cv2.imwrite("calib_{}_pattern.bmp_".format(n_frames), new_frame)

                self.frame_size = (len(new_frame[0]), len(new_frame))

        cv2.destroyAllWindows()
예제 #4
0
 def calibrate(self):
     # If calibration type is unkown at this point, ask the user
     if (self.stereo == None):
         calib_type = utils.getAnswer('Stereo or Mono calibration ? (s/m) : ', 'sm')
         
         if (calib_type == 's'):
             self.stereo = True
         else:
             self.stereo = False
         
     # Start the appropriate calibration processes
     if self.stereo:
         self.stereoCalibrate()
     else :
         self.monoCalibrate()
예제 #5
0
    def calibrate(self):
        # If calibration type is unkown at this point, ask the user
        if (self.stereo == None):
            calib_type = utils.getAnswer(
                'Stereo or Mono calibration ? (s/m) : ', 'sm')

            if (calib_type == 's'):
                self.stereo = True
            else:
                self.stereo = False

        # Start the appropriate calibration processes
        if self.stereo:
            self.stereoCalibrate()
        else:
            self.monoCalibrate()
예제 #6
0
    def stereoCalibrate(self):
        print "If you calibrate from files, make sure stereo files are"
        print "in the left-right-left-right order"

        # Get settings & files
        self.stereo = True
        self.chooseCalibrationSettings()

        # Get patterns
        self.recordPatterns()

        # Compute the intrisic parameters first :
        rvecs = [
            np.zeros(3, dtype=np.float32) for i in xrange(self.max_frames_i)
        ]
        tvecs = [
            np.zeros(3, dtype=np.float32) for i in xrange(self.max_frames_i)
        ]

        # Call OpenCV routines to do the dirty work
        print "Computing intrisic parameters for the first camera"
        res = cv2.calibrateCamera(self.obj_points_l, self.img_points_l,
                                  self.frame_size, self.intrinsics_l,
                                  self.distorsion_l, rvecs, tvecs)

        rms, self.intrinsics_l, self.distorsion_l, rvecs, tvecs = res

        print "Computing intrisic parameters for the second camera"
        res = cv2.calibrateCamera(self.obj_points_r, self.img_points_r,
                                  self.frame_size, self.intrinsics_r,
                                  self.distorsion_r, rvecs, tvecs)

        rms, self.intrinsics_r, self.distorsion_r, rvecs, tvecs = res

        # Allocate arrays for the two camera matrix and distorsion matrices
        R = np.zeros((3, 3), dtype=np.float32)
        T = np.zeros((3, 1), dtype=np.float32)
        E = np.zeros((3, 3), dtype=np.float32)
        F = np.zeros((3, 3), dtype=np.float32)

        # Compute calibration parameters :
        print "Calibrating cameras.."
        print "Frame size : {}".format(self.frame_size)

        # set stereo flags
        stereo_flags = 0
        #        stereo_flags |= cv2.CALIB_FIX_INTRINSIC
        stereo_flags |= cv2.CALIB_USE_INTRINSIC_GUESS  # Refine intrinsic parameters
        #        stereo_flags |= cv2.CALIB_FIX_PRINCIPAL_POINT     # Fix the principal points during the optimization.
        #        stereo_flags |= cv2.CALIB_FIX_FOCAL_LENGTH        # Fix focal length
        #        stereo_flags |= cv2.CALIB_FIX_ASPECT_RATIO        # fix aspect ratio
        stereo_flags |= cv2.CALIB_SAME_FOCAL_LENGTH  # Use same focal length
        #        stereo_flags |= cv2.CALIB_ZERO_TANGENT_DIST       # Set tangential distortion to zero
        #        stereo_flags |= cv2.CALIB_RATIONAL_MODEL          # Use 8 param rational distortion model instead of 5 param plumb bob model

        res = cv2.stereoCalibrate(self.obj_points_l, self.img_points_l,
                                  self.img_points_r, self.frame_size,
                                  self.intrinsics_l, self.distorsion_l,
                                  self.intrinsics_r, self.distorsion_r)

        # flags=stereo_flags

        (rms, int_left, dist_left, int_right, dist_right, R, T, E, F) = res

        # Output
        print "Calibration done"
        print "Residual RMS : {}".format(rms)

        if (rms > 1.0):
            print "Calibration looks faulty, please re-run"

        print "\nCalibration parameters : \n Intrinsics -left \n {} \n\n Distorsion -left\n {}".format(\
            int_left, dist_left)

        print "\nCalibration parameters : \n Intrinsics -right \n {} \n\n Distorsion -right\n {}".format(\
            int_right, dist_right)

        print "\nRotation : \n{}\n".format(R)

        print "\nTranslation : \n{}\n".format(T)

        print "\nEssential matrix : \n{}\n".format(E)  # Essential matrix

        print "\nFundamental matrix : \n{}\n".format(F)  # Fundamental matrix

        # TODO : Compute perspective matrix !

        # Save calibration parameters
        save_file = utils.getAnswer(
            "Would you like to save the results ? (y/n) ", 'yn')

        b_write_success = False

        if save_file == "y":
            while (b_write_success == False):
                save_XML = utils.getAnswer("Save in XML format ? (y/n) ", "yn")

                filepath = raw_input(
                    "Where do you want to save the file ? (enter file path) ")

                try:
                    if (save_XML):

                        file = utils.handlePath(filepath,
                                                "camera_calibration.xml")

                        utils.saveParametersXML(int_left, dist_left, int_right,
                                                dist_right, R, T,
                                                self.frame_size, file)

                    else:
                        file_left = utils.handlePath(filepath, "_left.txt")
                        utils.saveParameters(int_left, dist_left, R, T,
                                             file_left)

                        file_right = utils.handlePath(filepath, "_right.txt")
                        utils.saveParameters(int_right, dist_right, R, T,
                                             file_right)

                    print "Parameters file written"
                    b_write_success = True

                except:
                    print "Wrong path, please correct"

                time.sleep(2)

        return
예제 #7
0
    def recordPattern_cam(self):
        n_frames = 0

        pattern_points = np.zeros((np.prod(self.pattern_size), 3),\
            np.float32)

        pattern_points[:, :2] = np.indices(self.pattern_size).T\
            .reshape(-1, 2)

        cv2.namedWindow("captureStream", cv2.CV_WINDOW_AUTOSIZE)
        cv2.namedWindow("patternDetection", cv2.CV_WINDOW_AUTOSIZE)

        save_files = utils.getAnswer(
            "Would you like \
            to save picture files ? (y/n)  ", 'yn')

        finished_parsing = False

        if (self.cam != ''):
            while not (finished_parsing) and ((self.max_frames_i == -1) or
                                              (n_frames < self.max_frames_i)):
                success, new_frame = self.cam.read()

                if (success):
                    grey_frame = np.array([])
                    corners = np.array([])

                    # Convert to B&W (if necessary ?)
                    grey_frame = cv2.cvtColor(new_frame, cv2.COLOR_BGR2GRAY)

                    found, corners = cv2.findChessboardCorners(\
                        grey_frame, self.pattern_size)

                    cv2.imshow("captureStream", new_frame)
                    cv2.waitKey(2)

                    if found:
                        # Refine position
                        term = (cv2.TERM_CRITERIA_EPS +
                                cv2.TERM_CRITERIA_COUNT, 30, 0.1)

                        cv2.cornerSubPix(grey_frame, corners, (11, 11),
                                         (-1, -1), term)

                        # Draw detected pattern
                        cv2.drawChessboardCorners(new_frame, self.pattern_size,
                                                  corners, found)

                        cv2.imshow("patternDetection", new_frame)
                        cv2.waitKey()

                        # Store values
                        self.img_points.append(corners.reshape(-1, 2))
                        self.obj_points.append(pattern_points)

                        n_frames = n_frames + 1
                        print "{} patterns found".format(n_frames)

                        if save_files == 'y':
                            cv2.imwrite("calib_{}.bmp".format(n_frames),
                                        grey_frame)

                            cv2.imwrite(
                                "calib_{}_pattern.bmp_".format(n_frames),
                                new_frame)

        self.frame_size = (len(new_frame[0]), len(new_frame))

        cv2.destroyAllWindows()
예제 #8
0
    def chooseCalibrationSettings(self):
        # Get the path where all the files are stored
        if (len(self.file_path) == 0):
            file_read = False

            while not file_read:
                path = raw_input("Path for the calibration files : ")
                file_read = self.readFiles(path)

            self.file_path = path

        else:
            file_read = self.readFiles(self.file_path)

        # Get the pattern dimensions in terms of patch number:
        if (self.pattern_size == (0, 0)):
            h_dim = utils.getAnswer(
                "Number of inner corners on the horizontal dimension ? ",
                '12345678910')

            v_dim = utils.getAnswer(
                "Number of inner corners on the vertical dimension ? ",
                '12345678910')

            # Enter the number of squares over each dimensions
            self.pattern_size = (int(h_dim), int(v_dim))
            print "Chessboard dimensions : {} x {}"\
                .format(self.pattern_size[0], self.pattern_size[1])

        # Get every patch dimension :
        if ((self.sq_size_h, self.sq_size_v) == (0.0, 0.0)):
            get_square_size = False
            while not (get_square_size):
                sq_size = raw_input("Horizontal Size (in m) of the squares ? ")

                try:
                    self.sq_size_h = float(sq_size)
                    get_square_size = True

                except ValueError:
                    print "Cannot determine dimension"

            get_square_size = False
            while not (get_square_size):
                sq_size = raw_input("Vertical Size (in m) of the squares ? ")

                try:
                    self.sq_size_v = float(sq_size)
                    get_square_size = True

                except ValueError:
                    print "Cannot determine dimension"

        # Get the max number of frames:
        if (self.max_frames_i != -1):
            get_max_frames = False
            while not (get_max_frames):
                max_frames = raw_input("How many frames ? ")

                try:
                    self.max_frames_i = int(max_frames)
                    get_max_frames = True

                except ValueError:
                    print "Cannot determine max number of frames"
예제 #9
0
# -*- coding: utf-8 -*-

import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting Orders
utils.parameters['limit'] = 2
utils.getAnswer(utils.getUrl('pedidos?'), requests.get)

# Posting new SalesOrders
utils.init()

p = {}
p['referencia'] = '123456'
p['fecha_pedido'] = '2019-12-01T10:00:00'
p['fecha_autoriza'] = '2019-12-01T10:35:10'
p['subtotal'] = '1000'
p['total'] = '1160'
p['email'] = '*****@*****.**'
p['entregara'] = 'MySelf'
p['telefono'] = ''
p['direccion'] = 'Priv Reforma # 108'
p['entrecalles'] = 'Abasolo y Montero'
p['colonia'] = 'Los Treviño'
p['ciudad'] = 'Santa Catarina'
p['estado'] = 'Nuevo León'
p['observaciones'] = 'Bodega Blanca'
p['cp'] = '61588'
p['estatus'] = 'pendiente'
p['mensajeria'] = ''
p['guias'] = ''
예제 #10
0
# -*- coding: utf-8 -*-

import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting Kits
# utils.parameters['beforeid'] =
# utils.parameters['afterid'] =
utils.parameters['ids'] = "5999"
utils.getAnswer(utils.getUrl('kits?'), requests.get)

utils.init()
p = []
componentes = []
componentes.append({"sku": '12345698', 'cantidad': 1})

p.append({
    'sku': '123456',
    'comentario': 'Prueba de post',
    "componentes": componentes
})
utils.getAnswer(utils.getUrl('kits?'), requests.post, p)
예제 #11
0
import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting countries
utils.getAnswer(utils.getUrl('paises?'), requests.get)
    def _choose_calibration_settings(self):
        # Get the path where all the files are stored
        if len(self.params.file_path) == 0:
            file_read = False
            path = None

            while not file_read:
                path = raw_input("Path for the calibration files : ")
                file_read = self._read_files(path)

            self.params.file_path = path

        else:
            self._read_files(self.params.file_path)

        # Get the pattern dimensions in terms of patch number:
        if self.params.pattern_size == (0, 0):
            h_dim = utils.getAnswer("Number of inner corners on the horizontal dimension ? ", '12345678910')
            v_dim = utils.getAnswer("Number of inner corners on the vertical dimension ? ", '12345678910')

            # Enter the number of squares over each dimensions
            self.params.pattern_size = (int(h_dim), int(v_dim))
            print("Chessboard dimensions : {} x {}".format(self.params.pattern_size[0], self.params.pattern_size[1]))

        # Get every patch dimension :
        if (self.params.sq_size_h, self.params.sq_size_v) == (0.0, 0.0):
            get_square_size = False

            while not get_square_size:
                sq_size = raw_input("Horizontal Size (in m) of the squares ? ")

                try:
                    self.params.sq_size_h = float(sq_size)
                    get_square_size = True

                except ValueError:
                    print("Cannot determine dimension")

            get_square_size = False

            while not get_square_size:
                sq_size = raw_input("Vertical Size (in m) of the squares ? ")

                try:
                    self.params.sq_size_v = float(sq_size)
                    get_square_size = True

                except ValueError:
                    print ("Cannot determine dimension")

        # Get the max number of frames:
        if self.params.max_frames_i != -1:
            get_max_frames = False
            while not get_max_frames:
                max_frames = raw_input("How many frames ? ")

                try:
                    self.params.max_frames_i = int(max_frames)
                    get_max_frames = True

                except ValueError:
                    print "Cannot determine max number of frames"
예제 #13
0
    def monoCalibrate(self):
        # Get settings
        self.chooseCalibrationSettings()

        # Get patterns
        self.recordPatterns()

        # Compute intrinsic parameters
        rvecs = [np.zeros(3) for i in xrange(self.max_frames_i)] # Rotation and translation matrix
        tvecs = [np.zeros(3) for i in xrange(self.max_frames_i)]

        _obj_points = np.array(self.obj_points, dtype = np.float32)
        _img_points = np.array(self.img_points, dtype = np.float32)

        rms, self.intrinsics, self.distorsion, _rvecs, _tvecs = cv2.calibrateCamera(_obj_points, _img_points, self.frame_size, self.intrinsics, self.distorsion, rvecs, tvecs)

        print "Calibration done"
        np.set_printoptions(precision=2)    
        np.set_printoptions(suppress=True)
        
        # TODO: cleanup print output, looks like a mess
        print "Residual RMS (pxl units) :\n"
        print(rms)

        print "\nRotations :\n"
        print(rvecs)

        print "\nTranslations :\n"
        print(tvecs)

        print "\nCalibration parameters :"
        print "Intrinsics \n"
        print(self.intrinsics)
        
        print "Distorsion \n"
        print(self.distorsion)

        # Save calibration parameters
        if not(self.auto_save):    
            save_file = utils.getAnswer("Would you like to save the results ? (y/n) ", 'yn')
    
            b_write_success = False
    
            if save_file == "y" :
                while(b_write_success == False) :
                    filepath = raw_input("Where do you want to save the file ? (enter file path) ")
                    filepath = utils.handlePath(filepath, "calib_results.txt")
    
                    # Create a file object in "write" mode
                    try :
                        utils.saveParameters(self.intrinsics, self.distorsion,
                                            rvecs, tvecs, rms, filepath)
                        b_write_success = True
    
                    except :
                        print "Wrong path, please correct"
    
                    time.sleep(2)

        else:
            calib_file_path = utils.handlePath(self.file_path, "calib_results.txt")
            
            utils.saveParameters(self.intrinsics, self.distorsion,
                                            rvecs, tvecs, rms, calib_file_path) 
            
            print "Saved calibration file"            
            
        return
예제 #14
0
파일: guias.py 프로젝트: hvalles/marketsync
# -*- coding: utf-8 -*-

import requests
import utils # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting Tracking Numbers
utils.parameters['orders'] = '131303'
# utils.parameters['beforeid'] = 
# utils.parameters['afterid'] = 
# Genera la guia y la descarga, solamente una guia a la vez
utils.getAnswer(utils.getUrl('guias?'), requests.post) 

# El get funciona para multiples guias pero solamente las descarga ya deben de existir
#utils.getAnswer(utils.getUrl('guias?'), requests.get)
예제 #15
0
v['bullet1'] = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
v['bullet2'] = 'Lorem Ipsum has been the industry s standard dummy text ever since the 1500s'
v['bullet3'] = ''
v['bullet4'] = ''
v['bullet5'] = ''

v['atributos'] = [{
    'atributo': 'EAN',
    'valor': '9856472536978'
}, {
    'atributo': 'SELLER_SKU',
    'valor': '9815-1'
}]

items = [v]
utils.getAnswer(utils.getUrl('variacion?'), requests.post, items)

# PUT Variacion

utils.init()
v = {}
v['product_id'] = 163766
v['sku'] = '9815-1'
v['color'] = "Negro Noche"
v['base'] = "Negro".upper()  # ;ist be upper case
v['stock'] = 0
v['imagen1'] = 'https://www.w3schools.com/w3css/img_lights.jpg'
v['imagen2'] = 'https://www.w3schools.com/w3css/img_snowtops2.jpg'
v['imagen3'] = 'https://www.w3schools.com/w3css/img_snowtops3.jpg'
v['imagen4'] = 'https://www.w3schools.com/w3css/img_snowtops4.jpg'
v['imagen5'] = ''
예제 #16
0
import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting colors
utils.getAnswer(utils.getUrl('colores?'), requests.get)
예제 #17
0
# -*- coding: utf-8 -*-

import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting Kits
# utils.parameters['beforeid'] =
# utils.parameters['afterid'] =
utils.parameters['orders'] = "1052"
utils.getAnswer(utils.getUrl('cobros?'), requests.get)

# utils.init()
# utils.parameters['orders'] = "1052"
# p={
#     'caja':'5',
#     'monto':'659',
#     'sucursal':'La Fe',
#     'ticket':'123456'
# }
# utils.getAnswer(utils.getUrl('cobros?'), requests.post, [p])

# utils.init()
# utils.parameters['ids'] = "4"
# p={
#     'motivo':'Cliente se arrepintio',
# }
# utils.getAnswer(utils.getUrl('cobros?'), requests.put, [p])
예제 #18
0
import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting stand alone category
utils.parameters['ids'] = 7209  # remover this parameter to get all categories
utils.getAnswer(utils.getUrl('categorias?'), requests.get)

# Getting attributes from a category
utils.getAnswer(utils.getUrl('categorias/atributos/7416?'), requests.get)
예제 #19
0
    def monoCalibrate(self):
        # Get settings
        self.chooseCalibrationSettings()

        # Get patterns
        self.recordPatterns()

        # Compute intrinsic parameters
        rvecs = [np.zeros(3) for i in xrange(self.max_frames_i)
                 ]  # Rotation and translation matrix
        tvecs = [np.zeros(3) for i in xrange(self.max_frames_i)]

        _obj_points = np.array(self.obj_points, dtype=np.float32)
        _img_points = np.array(self.img_points, dtype=np.float32)

        rms, self.intrinsics, self.distorsion, _rvecs, _tvecs = cv2.calibrateCamera(
            _obj_points, _img_points, self.frame_size, self.intrinsics,
            self.distorsion, rvecs, tvecs)

        print "Calibration done"
        np.set_printoptions(precision=2)
        np.set_printoptions(suppress=True)

        # TODO: cleanup print output, looks like a mess
        print "Residual RMS (pxl units) :\n"
        print(rms)

        print "\nRotations :\n"
        print(rvecs)

        print "\nTranslations :\n"
        print(tvecs)

        print "\nCalibration parameters :"
        print "Intrinsics \n"
        print(self.intrinsics)

        print "Distorsion \n"
        print(self.distorsion)

        # Save calibration parameters
        if not (self.auto_save):
            save_file = utils.getAnswer(
                "Would you like to save the results ? (y/n) ", 'yn')

            b_write_success = False

            if save_file == "y":
                while (b_write_success == False):
                    filepath = raw_input(
                        "Where do you want to save the file ? (enter file path) "
                    )
                    filepath = utils.handlePath(filepath, "calib_results.txt")

                    # Create a file object in "write" mode
                    try:
                        utils.saveParameters(self.intrinsics, self.distorsion,
                                             rvecs, tvecs, rms, filepath)
                        b_write_success = True

                    except:
                        print "Wrong path, please correct"

                    time.sleep(2)

        else:
            calib_file_path = utils.handlePath(self.file_path,
                                               "calib_results.txt")

            utils.saveParameters(self.intrinsics, self.distorsion, rvecs,
                                 tvecs, rms, calib_file_path)

            print "Saved calibration file"

        return
예제 #20
0
# -*- coding: utf-8 -*-

import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

################# Recuperacion de productos
utils.parameters['limit'] = 3
utils.getAnswer(utils.getUrl('fulfillment?'), requests.get)
예제 #21
0
import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

items = []
# Los markets pueden variar consulte la lista de markets disponibles en:
# Markets may change see markets list at:
# /api/markets
items.append({'product_id': 162700, 'seller_sku': '7811X', 'stock': 1})
items.append({'product_id': 162700, 'seller_sku': '7911X', 'stock': 2})
items.append({'product_id': 162700, 'seller_sku': '8011X', 'stock': 4})
items.append({'product_id': 162700, 'seller_sku': '8111X', 'stock': 5})
items.append({'product_id': 162700, 'seller_sku': '1182X', 'stock': 6})

utils.getAnswer(utils.getUrl('stock?'), requests.put, items)

# Verbo POST
# Fecha a considerar el corte de inventario
utils.init()
data = {'update_stock': '2019-12-01T00:01:02'}
utils.getAnswer(utils.getUrl('stock?'), requests.post, data)
예제 #22
0
    def stereoCalibrate(self):
        print "If you calibrate from files, make sure stereo files are"
        print "in the left-right-left-right order"

        # Get settings & files
        self.stereo = True
        self.chooseCalibrationSettings()

        # Get patterns
        self.recordPatterns()

        # Compute the intrisic parameters first :
        rvecs = [np.zeros(3, dtype = np.float32) for i in xrange(self.max_frames_i)]
        tvecs = [np.zeros(3, dtype = np.float32) for i in xrange(self.max_frames_i)]

        # Call OpenCV routines to do the dirty work
        print "Computing intrisic parameters for the first camera"
        res = cv2.calibrateCamera(self.obj_points_l, self.img_points_l,
                                  self.frame_size,
                                  self.intrinsics_l, self.distorsion_l,
                                  rvecs, tvecs)

        rms, self.intrinsics_l, self.distorsion_l, rvecs, tvecs = res

        print "Computing intrisic parameters for the second camera"
        res = cv2.calibrateCamera(self.obj_points_r, self.img_points_r,
                                  self.frame_size,
                                  self.intrinsics_r, self.distorsion_r,
                                  rvecs, tvecs)
                                  
        rms, self.intrinsics_r, self.distorsion_r, rvecs, tvecs = res

        # Allocate arrays for the two camera matrix and distorsion matrices
        R = np.zeros((3, 3), dtype = np.float32)
        T = np.zeros((3, 1), dtype = np.float32)
        E = np.zeros((3, 3), dtype = np.float32)
        F = np.zeros((3, 3), dtype = np.float32)

        # Compute calibration parameters :
        print "Calibrating cameras.."
        print "Frame size : {}".format(self.frame_size)

        # set stereo flags
        stereo_flags = 0
#        stereo_flags |= cv2.CALIB_FIX_INTRINSIC
        stereo_flags |= cv2.CALIB_USE_INTRINSIC_GUESS     # Refine intrinsic parameters
#        stereo_flags |= cv2.CALIB_FIX_PRINCIPAL_POINT     # Fix the principal points during the optimization.
#        stereo_flags |= cv2.CALIB_FIX_FOCAL_LENGTH        # Fix focal length
#        stereo_flags |= cv2.CALIB_FIX_ASPECT_RATIO        # fix aspect ratio
        stereo_flags |= cv2.CALIB_SAME_FOCAL_LENGTH       # Use same focal length
#        stereo_flags |= cv2.CALIB_ZERO_TANGENT_DIST       # Set tangential distortion to zero
#        stereo_flags |= cv2.CALIB_RATIONAL_MODEL          # Use 8 param rational distortion model instead of 5 param plumb bob model

        res = cv2.stereoCalibrate(self.obj_points_l,
                                  self.img_points_l, self.img_points_r,
                                  self.frame_size,
                                  self.intrinsics_l, self.distorsion_l,
                                  self.intrinsics_r, self.distorsion_r)

                                  # flags=stereo_flags

        (rms, int_left, dist_left, int_right, dist_right, R, T, E, F) = res

        # Output
        print "Calibration done"
        print "Residual RMS : {}".format(rms)

        if (rms > 1.0):
            print "Calibration looks faulty, please re-run"

        print "\nCalibration parameters : \n Intrinsics -left \n {} \n\n Distorsion -left\n {}".format(\
            int_left, dist_left)

        print "\nCalibration parameters : \n Intrinsics -right \n {} \n\n Distorsion -right\n {}".format(\
            int_right, dist_right)

        print "\nRotation : \n{}\n".format(R)

        print "\nTranslation : \n{}\n".format(T)

        print "\nEssential matrix : \n{}\n".format(E) # Essential matrix

        print "\nFundamental matrix : \n{}\n".format(F) # Fundamental matrix

        # TODO : Compute perspective matrix !

        # Save calibration parameters
        save_file = utils.getAnswer("Would you like to save the results ? (y/n) ", 'yn')

        b_write_success = False

        if save_file == "y" :
            while(b_write_success == False) :
                save_XML = utils.getAnswer("Save in XML format ? (y/n) ", "yn")

                filepath = raw_input("Where do you want to save the file ? (enter file path) ")

                try :
                  if (save_XML) :

                    file = utils.handlePath(filepath, "camera_calibration.xml")

                    utils.saveParametersXML(int_left,
                                            dist_left,
                                            int_right,
                                            dist_right,
                                            R,
                                            T,
                                            self.frame_size,
                                            file)

                  else :
                    file_left = utils.handlePath(filepath, "_left.txt")
                    utils.saveParameters(int_left, dist_left, R, T, file_left)

                    file_right = utils.handlePath(filepath, "_right.txt")
                    utils.saveParameters(int_right, dist_right, R, T, file_right)

                  print "Parameters file written"
                  b_write_success = True

                except :
                    print "Wrong path, please correct"

                time.sleep(2)

        return
예제 #23
0
import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Put Publicar

items = []
items.append({'product_id': 162699, 'market_id': 1})  # Claro
items.append({'product_id': 162699, 'market_id': 2})  # Linio
items.append({'product_id': 162699, 'market_id': 4})  # MeLi
items.append({'product_id': 162699, 'market_id': 5})  # Walmart
items.append({'product_id': 162699, 'market_id': 6})  # Amazon

utils.getAnswer(utils.getUrl('productos/agotar?'), requests.put, data=items)
예제 #24
0
import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.
import sys

# Verbo GET
utils.init()
utils.getAnswer(utils.getUrl('ubicado?'), requests.get)

# Verbo POST
items = []
items.append({
    'ubicacion': 'INC-001',
    'seller_sku': '0697-1000-0010',
    'stock': 1
})
items.append({
    'ubicacion': 'INC-001',
    'seller_sku': '0697-1000-0020',
    'stock': 2
})
items.append({
    'ubicacion': 'INC-002',
    'seller_sku': '0697-1000-0010',
    'stock': 4
})
items.append({
    'ubicacion': 'INC-002',
    'seller_sku': '0697-1000-0020',
    'stock': 5
})
items.append({
예제 #25
0
import requests
import utils  # Review config.example file and rename it to config.py, do not forget to erase your keys.

# Getting markets
utils.getAnswer(utils.getUrl('markets?'), requests.get)

# Posting market
utils.init()
# One market at a time
market = {'market_id': 1, 'activo': 1, 'proteccion': 1}
utils.getAnswer(utils.getUrl('markets?'), requests.post, market)
    def _calibrate_stereo(self):
        print("-- If you calibrate from files, make sure stereo files are \n in the left-right-left-right order --")

        # Get settings & files
        self._choose_calibration_settings()

        # Get patterns
        self._record_patterns()

        # Compute the intrisic parameters first :
        rvecs = [np.zeros(3, dtype=np.float32) for _ in xrange(self.params.max_frames_i)]
        tvecs = [np.zeros(3, dtype=np.float32) for _ in xrange(self.params.max_frames_i)]

        self.intrinsics.append(np.zeros((4, 4), dtype=np.float32))
        self.intrinsics.append(np.zeros((4, 4), dtype=np.float32))

        self.distorsion.append(np.zeros(8, dtype=np.float32))
        self.distorsion.append(np.zeros(8, dtype=np.float32))

        # Call OpenCV routines to do the dirty work
        print("Computing intrisic parameters for the first camera")
        res = cv2.calibrateCamera(self.obj_points_l, self.img_points_l, self.frame_size,
                                  self.intrinsics[0], self.distorsion[0], rvecs, tvecs)

        rms, self.intrinsics[0], self.distorsion[0], rvecs, tvecs = res

        print("Computing intrisic parameters for the second camera")
        res = cv2.calibrateCamera(self.obj_points_r, self.img_points_r, self.frame_size,
                                  self.intrinsics[1], self.distorsion[1], rvecs, tvecs)

        rms, self.intrinsics[1], self.distorsion[1], rvecs, tvecs = res

        # Compute calibration parameters :
        print("Calibrating cameras.. \nFrame size : {}".format(self.frame_size))

        # set stereo flags
        stereo_flags = 0
        #        stereo_flags |= cv2.CALIB_FIX_INTRINSIC
        stereo_flags |= cv2.CALIB_USE_INTRINSIC_GUESS     # Refine intrinsic parameters
        #        stereo_flags |= cv2.CALIB_FIX_PRINCIPAL_POINT     # Fix the principal points during the optimization.
        #        stereo_flags |= cv2.CALIB_FIX_FOCAL_LENGTH        # Fix focal length
        #        stereo_flags |= cv2.CALIB_FIX_ASPECT_RATIO        # fix aspect ratio
        stereo_flags |= cv2.CALIB_SAME_FOCAL_LENGTH       # Use same focal length
        #        stereo_flags |= cv2.CALIB_ZERO_TANGENT_DIST       # Set tangential distortion to zero
        #        stereo_flags |= cv2.CALIB_RATIONAL_MODEL
        #  Use 8 param rational distortion model instead of 5 param plumb bob model

        res = cv2.stereoCalibrate(self.obj_points_l,
                                  self.img_points_l, self.img_points_r,
                                  self.frame_size,
                                  self.intrinsics[0], self.distorsion[0],
                                  self.intrinsics[1], self.distorsion[1])

        (rms, int_left, dist_left, int_right, dist_right, rotations, translations, essential, fundamental) = res

        # Output
        print "Calibration done. Residual RMS : {}".format(rms)

        if rms > 1.0:
            print "Calibration looks faulty, please re-run"

        print "\nCalibration parameters : \n Intrinsics -left \n {} \n\n Distorsion -left\n {}".format(
            int_left, dist_left)

        print "\nCalibration parameters : \n Intrinsics -right \n {} \n\n Distorsion -right\n {}".format(
            int_right, dist_right)

        print "\nRotation : \n{}\n".format(rotations)
        print "\nTranslation : \n{}\n".format(translations)
        print "\nEssential matrix : \n{}\n".format(essential)
        print "\nFundamental matrix : \n{}\n".format(fundamental)

        # Save calibration parameters
        save_file = utils.getAnswer("Would you like to save the results ? (y/n) ", 'yn') == 'y'

        b_write_success = False

        if save_file:
            while not b_write_success:
                filepath = raw_input("Where do you want to save the file ? (enter file path) ")

                try:
                    file_left = utils.handlePath(filepath, "_overall.txt")
                    self._json_save(rotations, translations,  rms, file_left)

                    print "Parameters file written"
                    b_write_success = True

                except IOError:
                    print "Wrong path, please correct"

                time.sleep(2)

        return
예제 #27
0
    'market_id': 1,
    'oferta': 101,
    'precio': 201
})  # Claro
items.append({
    'product_id': 163766,
    'market_id': 2,
    'oferta': 102,
    'precio': 202
})  # Linio
items.append({
    'product_id': 163766,
    'market_id': 4,
    'oferta': 104,
    'precio': 204
})  # MeLi
items.append({
    'product_id': 163766,
    'market_id': 5,
    'oferta': 105,
    'precio': 205
})  # Walmart
items.append({
    'product_id': 163766,
    'market_id': 6,
    'oferta': 106,
    'precio': 206
})  # Amazon

utils.getAnswer(utils.getUrl('precios?'), requests.put, items)
    def _calibrate_mono(self):
        self._choose_calibration_settings()
        self._record_patterns()

        # Compute intrinsic parameters
        rvecs = [np.zeros(3) for _ in xrange(self.params.max_frames_i)]
        tvecs = [np.zeros(3) for _ in xrange(self.params.max_frames_i)]

        self.intrinsics.append(np.zeros((3, 3), dtype=np.float32))
        self.distorsion.append(np.zeros(8, dtype=np.float32))

        # Optimisation flags
        flags = 0
        if self.params.focal_guess > 0.:
            self.intrinsics[0][0, 0] = self.params.focal_guess
            self.intrinsics[0][1, 1] = self.params.focal_guess
            self.intrinsics[0][0, 2] = self.frame_size[0]/2
            self.intrinsics[0][1, 2] = self.frame_size[1]/2
            self.intrinsics[0][2, 2] = 1.
            flags |= cv2.CALIB_USE_INTRINSIC_GUESS
            print("Using an initial intrisic matrix guess : \n {}".format(
                self.intrinsics[0]))

        # flags |= cv2.CALIB_FIX_INTRINSIC
        # flags |= cv2.CALIB_FIX_PRINCIPAL_POINT
        # flags |= cv2.CALIB_FIX_FOCAL_LENGTH   # Fix focal length
        # flags |= cv2.CALIB_FIX_ASPECT_RATIO   # fix aspect ratio
        # flags |= cv2.CALIB_ZERO_TANGENT_DIST  # Set tangential distortion to zero
        # flags |= cv2.CALIB_RATIONAL_MODEL     # Use 8 param rational distortion model instead of 5 param plumb bob model

        ret = cv2.calibrateCamera(np.array(self.obj_points).astype(np.float32),
                                  np.array(self.img_points).astype(np.float32),
                                  self.frame_size, self.intrinsics[0],
                                  self.distorsion[0],
                                  rvecs, tvecs, flags)

        [rms, self.intrinsics[0], self.distorsion[0], rvecs, tvecs] = ret

        print("Calibration done")
        print("\nResidual RMS (pixels): {}".format(rms))
        print("\nCalibration parameters: Intrinsics \n {}".format(self.intrinsics[0]))
        print("\nDistorsion: \n {}".format(self.distorsion[0]))
        print("\nNumber of pictures used: {}".format(self.n_pattern_found))

        # Save calibration parameters
        if not self.params.auto_save:
            b_write_success = False

            if utils.getAnswer("Save the results ? (y/n) ", 'yn') == "y":
                while not b_write_success:
                    filepath = raw_input("Where do you want to save the file ?")
                    filepath = utils.handlePath(filepath, "calib_results")

                    try:
                        self._json_save(rvecs, tvecs, rms, filepath + '.json')
                        b_write_success = True

                    except ValueError:
                        print("Wrong path, please correct")

        else:
            calib_file_path = utils.handlePath(self.params.file_path, "calib_results")
            self._json_save(rvecs, tvecs, rms, calib_file_path + '.json')
            print("Saved calibration file")

        # Test the distorsion parameters:
        if utils.getAnswer("Would you like to test the distorsion parameters ? (y/n)", 'yn') == 'y':
            root_folder = os.path.dirname(self.pict_names[0])
            dist_folder = os.path.join(root_folder, 'undistorted')
            if not os.path.exists(dist_folder):
                os.makedirs(dist_folder)

            for pict, name in zip(self.pictures, self.pict_names):
                undistorted = self._undistort_frame(pict)
                pict_name = os.path.basename(name)
                cv2.imwrite(os.path.join(dist_folder, pict_name[:-3] + 'undistorted.jpg'), undistorted)
                print("Image {} rectified".format(pict_name))

        return