Exemple #1
0
def main():
    n = int(input('Masukkan kapasitas barang: '))
    arrId = []
    arrBarang = []
    arrHarga = []

    while True:
        print('Kapasitas barang', n)
        print('Pilih Menu (Ketik 1/2/3 dan 0 untuk keluar')
        print('1. Input Data')
        print('2. Lihat Data')
        print('3. Lihat Data Terurut')

        menu = input('Ketikkan: ')

        if menu == '1':
            arrId, arrBarang, arrHarga = MyLib.InputData(
                arrId, arrBarang, arrHarga, n)
        elif menu == '2':
            MyLib.LihatData(arrId, arrBarang, arrHarga, n)
        elif menu == '3':
            MyLib.LihatDataTerurut(arrId, arrBarang, arrHarga, n)
        elif menu == '0':
            break
        else:
            print('Menu tidak ada.')

        input('Tekan sembarang untuk kembali ke menu')
Exemple #2
0
def testAll():
    ## test all the testing samples
    iniA         = 0 
    iniUp3x3     = 0
    if FLAGS.Ynormalize:
        data = sio.loadmat("CAVEdata/Ynum")
        Ynum = data['Ynum']
    else:
        Ynum = 1
    Y       = tf.placeholder(tf.float32, shape=(1, 512, 512, 3))  # supervised data (None,64,64,3)
    Z       = tf.placeholder(tf.float32, shape=(1, 512/32, 512/32, FLAGS.outDim))
    outX, X1, YA, _, HY = MHFnet.HSInet(Y, Z, iniUp3x3,iniA,FLAGS.upRank,FLAGS.outDim,FLAGS.HSInetL,FLAGS.subnetL)

    config = tf.ConfigProto(allow_soft_placement=True,log_device_placement=True)
    config.gpu_options.allow_growth = True
    saver = tf.train.Saver(max_to_keep = 5)
    save_path = FLAGS.train_dir
    ML.mkdir(FLAGS.test_dir)
    with tf.Session(config=config) as sess:        
        ckpt = tf.train.latest_checkpoint(save_path)
        saver.restore(sess, ckpt) 
        for root, dirs, files in os.walk('CAVEdata/X/'):
            for i in range(32):       
                data = sio.loadmat("CAVEdata/Y/"+files[i])
                inY  = data['RGB']
                inY  = np.expand_dims(inY, axis = 0)*Ynum
                data = sio.loadmat("CAVEdata/Z/"+files[i])
                inZ  = data['Zmsi']
                inZ  = np.expand_dims(inZ, axis = 0)
                pred_X,ListX,pred_HY,pred_YA = sess.run([outX, X1, HY, YA],feed_dict={Y:inY,Z:inZ})  
                pred_Lr = ListX[FLAGS.HSInetL-2]
                sio.savemat(FLAGS.test_dir+files[i], {'outX': pred_X,'outLR': pred_Lr,'outHY': pred_HY, 'outYA':pred_YA})     
                print(files[i] + ' done!')
Exemple #3
0
def TD_to_1D_All_Point(pk_or_kr):
    x = []
    y = []
    for i in range(number):
        for j in range(number):
            for k in range(number):
                x.append(
                    math.sqrt((i - number / 2)**2 + (j - number / 2)**2 +
                              (k - number / 2)**2))
                y.append(pk_or_kr[i][j][k])
    xx = list(set(x))
    xx.sort()
    stop = ml.Fib_Search(number / 2, xx)
    del xx[stop + 1:]
    del yy[stop + 1:]

    block = len(xx)
    yy_n = [0] * block
    yy = [0] * block
    for i in range(len(x)):
        j = ml.Fib_Search(x[i], xx)
        if j <> -1:
            yy_n[j] += 1
            yy[j] += y[i]
    for j in range(block):
        yy[j] = yy[j] / yy_n[j]
    return xx, yy
Exemple #4
0
def PrepareDataAndiniValue(prepare='Yes'):
    DataRoad = 'CAVEdata/'
    if prepare != 'No':
        print('Generating the training and testing data in folder CAVEdata')
        Ind = [
            2, 31, 25, 6, 27, 15, 19, 14, 12, 28, 26, 29, 8, 13, 22, 7, 24, 30,
            10, 23, 18, 17, 21, 3, 9, 4, 20, 5, 16, 32, 11, 1
        ]
        ML.mkdir(DataRoad + 'X/')
        n = 0
        for root, dirs, files in os.walk('rowData/CAVEdata/complete_ms_data/'):
            for i in range(32):
                n = n + 1
                print('processing ' + dirs[Ind[i] - 1])
                X = readImofDir('rowData/CAVEdata/complete_ms_data/' +
                                dirs[Ind[i] - 1] + '/' +
                                dirs[Ind[i] - 1]) / 255

                sio.savemat(DataRoad + 'X/' + dirs[Ind[i] - 1], {'msi': X})
                if n <= 20:
                    if n == 1:
                        allX = np.reshape(X, [512 * 512, 31])
                    else:
                        allX = np.vstack((allX, np.reshape(X,
                                                           [512 * 512, 31])))
            break
        allX = np.matrix(allX)
        sio.savemat(DataRoad + 'List', {'Ind': Ind})
    else:
        print('Using the prepared data and initial values in folder CAVEdata')
Exemple #5
0
def update() :
    MyLogger.logger.info("+Lance la mise à jour.")
    try:
        MyLogger.logger.info("+Update des fichiers.")
        MyLib.copytree(config_json["parametres"]["cheminWWW"]+config_json["parametres"]["cheminAPI"]+"deploy",config_json["parametres"]["cheminWWW"],True,config_json["noUpdate"],config_json["parametres"])
                
    except Exception as e:
        MyLogger.logger.error("Erreur pendant update : ("+format(e)+")")
        sys.exit("Erreur")
Exemple #6
0
def update():
    MyLogger.logger.info("+Lance la mise à jour.")
    try:
        MyLogger.logger.info("+Update des fichiers.")
        MyLib.copytree(
            config_json["parametres"]["cheminWWW"] +
            config_json["parametres"]["cheminAPI"] + "deploy",
            config_json["parametres"]["cheminWWW"], True,
            config_json["noUpdate"], config_json["parametres"])

    except Exception as e:
        MyLogger.logger.error("Erreur pendant update : (" + format(e) + ")")
        sys.exit("Erreur")
Exemple #7
0
def update() :
    MyLogger.logger.info("Lance la mise à jour.")
    try:
        if arguments["mode"] == "full" or arguments["mode"] == "client" :
            MyLogger.logger.info("Update client")
            mergedListNoUpdate = config_json_project["client"]["update"]["noUpdate"] + config_json_private["client"]["update"]["noUpdate"]
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaClient/Deploy/",config_json_project["client"]["path"],True,mergedListNoUpdate)
            
            MyLogger.logger.info("Update client")
            mergedListNoUpdate = config_json_project["client"]["update"]["noUpdate"] + config_json_private["client"]["update"]["noUpdate"]
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaClient/Api/",config_json_project["client"]["path"]+"/API/",True,"")
        

        if arguments["mode"] == "full" or arguments["mode"] == "server" :
            MyLogger.logger.info("Update server")
            mergedListNoUpdate = config_json_project["server"]["update"]["noUpdate"] + config_json_private["server"]["update"]["noUpdate"]
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaServer/Deploy/",config_json_project["server"]["path"],True,mergedListNoUpdate)
            
            MyLogger.logger.info("Update server")
            mergedListNoUpdate = config_json_project["server"]["update"]["noUpdate"] + config_json_private["server"]["update"]["noUpdate"]
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaServer/Api/",config_json_project["server"]["path"]+"/API/",True,"")
            
    except Exception as e:
        MyLogger.logger.error("Erreur pendant update : ("+format(e)+")")
        sys.exit("Erreur")
Exemple #8
0
def install() :
    MyLogger.logger.info("+Lance l'installation.")
    try:
        MyLogger.logger.info("+Etape 1 : copie des fichiers.")
        MyLib.copytree(config_json["parametres"]["cheminWWW"]+config_json["parametres"]["cheminAPI"]+"deploy",config_json["parametres"]["cheminWWW"],True,"","")
            
        MyLogger.logger.info("+Etape 2 : personnalisation des fichiers.")
        for cur_fichier in config_json["fichiers"]:
            MyLogger.logger.debug("-Edition du fichier : "+cur_fichier["chemin"]+cur_fichier["nom"])
            MyLib.editFile(config_json["parametres"]["cheminWWW"] + cur_fichier["chemin"] + cur_fichier["nom"], config_json["valeurs"])
                
    except Exception as e:
        MyLogger.logger.error("Erreur pendant install : ("+format(e)+")")
        sys.exit("Erreur")
Exemple #9
0
def getC(Y, Z, inC, sizeC=32, ratio= 32):
    #用来估计RC的代码
    inC = np.reshape(inC,  [sizeC*sizeC,1])
    v1  = np.ones([sizeC*sizeC,1])
    h,w,outDim = Z.shape
#    print(outDim)
    Z = np.reshape(Z, [h*w,outDim])
    Ypatch = ML.im2Patch(Y, sizeC, ratio)
    YY = np.linalg.inv(np.matmul(Ypatch.T,Ypatch)+np.eye(sizeC*sizeC)*0.001)
    vYYv = np.matmul(np.matmul(v1.T,YY),v1)
#    inC = np.ones([sizeC,sizeC])/sizeC/sizeC
     
    numMS = Y.shape[2]
    
    for i in range(30):
        CY = np.matmul(Ypatch, inC)
        R  = np.matmul(np.matmul(np.linalg.inv(np.matmul(Z.T,Z)), Z.T),np.reshape(CY,[h*w,numMS]))
        ZR = np.matmul(Z,R)
        uZR = np.reshape(ZR,[1,h*w*numMS])

        inC = np.matmul((np.matmul(uZR,Ypatch)- (np.matmul(np.matmul(np.matmul(uZR,Ypatch),YY),v1) -1 )/vYYv*v1.T),YY)
        inC = inC.T
#    print(np.sum(inC))
    inC = np.reshape(inC,[sizeC,sizeC])
    inC = np.expand_dims(inC[::-1,::-1], axis = 2)
    inC = np.expand_dims(inC, axis = 3)
    return inC
Exemple #10
0
def getC2(Y, Z, allC, sizeC=32, ratio= 32):
    #用来估计RC的代码
    
    numA = allC.shape[2]
    allC = np.reshape(allC, [sizeC*sizeC, numA])
    
    alpha = np.ones([numA,1])
    
#    inC = np.reshape(inC,  [sizeC*sizeC,1])
    v1  = np.ones([numA,1])
    h,w,outDim = Z.shape
#    print(outDim)
    Z = np.reshape(Z, [h*w,outDim])
    Ypatch = ML.im2Patch(Y, sizeC, ratio)
    YCall  = np.matmul(Ypatch, allC)
    
    YY = np.linalg.inv(np.matmul(YCall.T,YCall)+np.eye(numA)*0.0000001)
    vYYv = np.matmul(np.matmul(v1.T,YY),v1)
#    inC = np.ones([sizeC,sizeC])/sizeC/sizeC
     
    for i in range(30):
        CY = np.matmul(YCall, alpha)
        R  = np.matmul(np.matmul(np.linalg.inv(np.matmul(Z.T,Z)), Z.T),np.reshape(CY,[h*w,3]))
        ZR = np.matmul(Z,R)
        uZR = np.reshape(ZR,[1,h*w*3])

        alpha = np.matmul((np.matmul(uZR,YCall)- (np.matmul(np.matmul(np.matmul(uZR,YCall),YY),v1) -1 )/vYYv*v1.T),YY)
        alpha = alpha.T
#    print(np.sum(inC))
    inC = np.matmul(allC, alpha)
    inC = np.reshape(inC,[sizeC,sizeC])
    inC = np.expand_dims(inC[::-1,::-1], axis = 2)
    inC = np.expand_dims(inC, axis = 3)
    return inC, R
Exemple #11
0
def lines2vecs(lines):
  lines= [x for x in lines if len(x.strip())>0] #remove empty lines
  ncol= len(lines[0].split())
  TT= []
  for i,line in enumerate(lines):
    ww= line.split()
    v= plt.zeros(ncol,'float')
    for j in range(len(ww)): v[j]= ML.num(ww[j])
    TT.append(v)
  return TT
Exemple #12
0
def lines2vecs(lines):
    lines = [x for x in lines if len(x.strip()) > 0]  #remove empty lines
    ncol = len(lines[0].split())
    TT = []
    for i, line in enumerate(lines):
        ww = line.split()
        v = plt.zeros(ncol, 'float')
        for j in range(len(ww)):
            v[j] = ML.num(ww[j])
        TT.append(v)
    return TT
Exemple #13
0
 def backup(self):
     existsBackups = [
         int(fileName.replace(CFG_FILE_BASE_NAME, "").replace(u".bak", ""))
         for fileName in MyLib.getFiles(APP_DIR)
         if fileName.endswith(u".bak")
     ]
     if existsBackups:
         maxNum = max(existsBackups) + 1
     else:
         maxNum = 0
     self.save(fileName=os.path.join(
         APP_DIR, u"{0}{1}.bak".format(CFG_FILE_BASE_NAME, maxNum)))
Exemple #14
0
def install():
    MyLogger.logger.info("+Lance l'installation.")
    try:
        MyLogger.logger.info("+Etape 1 : copie des fichiers.")
        MyLib.copytree(
            config_json["parametres"]["cheminWWW"] +
            config_json["parametres"]["cheminAPI"] + "deploy",
            config_json["parametres"]["cheminWWW"], True, "", "")

        MyLogger.logger.info("+Etape 2 : personnalisation des fichiers.")
        for cur_fichier in config_json["fichiers"]:
            MyLogger.logger.debug("-Edition du fichier : " +
                                  cur_fichier["chemin"] + cur_fichier["nom"])
            MyLib.editFile(
                config_json["parametres"]["cheminWWW"] +
                cur_fichier["chemin"] + cur_fichier["nom"],
                config_json["valeurs"])

    except Exception as e:
        MyLogger.logger.error("Erreur pendant install : (" + format(e) + ")")
        sys.exit("Erreur")
Exemple #15
0
def test():
    data = sio.loadmat(FLAGS.test_data_name)
    Y    = data['RGB']
    Z    = data['Zmsi']
    X    = data['msi']   
    if FLAGS.Ynormalize:
        Ynum = 1 
#        Depending on the situation, this line may need to be changed as following:
#        data = sio.loadmat("CAVEdata/Ynum")
#        Ynum = data['Ynum']
    else:
        Ynum = 1
        
    ## banchsize H W C
    inY = np.expand_dims(Y, axis = 0)
    inY = tf.to_float(inY)*Ynum;
    
    inZ = np.expand_dims(Z, axis = 0)
    inZ = tf.to_float(inZ);
    
    inX = np.expand_dims(X, axis = 0)
    inX = tf.to_float(inX);
    
    iniA     = 0
    iniUp3x3 = 0
    
    outX, X1, YA, _, HY = MHFnet.HSInet(inY,inZ, iniUp3x3, iniA,FLAGS.upRank,FLAGS.outDim,FLAGS.HSInetL,FLAGS.subnetL)
    

    config = tf.ConfigProto(allow_soft_placement=True,log_device_placement=True)
    config.gpu_options.allow_growth = True
    saver = tf.train.Saver(max_to_keep = 5)
    save_path = FLAGS.train_dir
    
    with tf.Session(config=config) as sess:        
       ckpt = tf.train.latest_checkpoint(save_path)
       saver.restore(sess, ckpt) 
       pred_X,pred_YA,pred_HY,inX = sess.run([outX, YA, HY, inX])     
    
    toshow  = np.hstack((ML.normalized(ML.get3band_of_tensor(pred_HY)),ML.get3band_of_tensor(pred_YA)))
    toshow2 = np.hstack((ML.get3band_of_tensor(pred_X),ML.get3band_of_tensor(inX)))
    toshow  = np.vstack((toshow,toshow2))
    print('The vasaul result of Y_hat (left upper), Y*A (right upper), fusion result (left lower) and ground truth (right lower)')
    ML.imshow(toshow)
    ML.imwrite(toshow)
Exemple #16
0
    def read(self, fileName=CFG_FILE_NAME):
        workingDirs = {}
        try:
            f = open(fileName)
        except IOError as e:
            if e.errno != errno.ENOENT:
                print u"{0}. Код ошибки: {1}".format(e.strerror, e.errno)
                print u"Программа завершается."
                sys.exit()
        except:
            print u"Неизвестная ошибка."
            sys.exit()
        else:
            borderCnt = 0  # число прочитанных строк, содержащих BORDER_STR в начале
            for line in f:
                if line.startswith(BORDER_STR):
                    if borderCnt > 0:
                        break
                    borderCnt += 1
                elif line.startswith(WKDIR_LINE):
                    wkDirName = line[2:-1].decode("utf-8")
                    workingDirs[wkDirName] = {
                        "entries": {},
                        "new": [],
                        "exists": os.path.exists(wkDirName)
                    }
                    wkDir = workingDirs[wkDirName]
                elif line.startswith(ENTRY_STR):
                    entryName = line[1:-1].decode("utf-8")
                    wkDir["entries"][entryName] = {
                        "links": [],
                        "exists":
                        os.path.exists(os.path.join(wkDirName, entryName))
                    }
                    entryLinks = wkDir["entries"][entryName]["links"]
                else:
                    linkName = line[:-1].decode("utf-8")
                    entryLinks.append(linkName)

            # ищем неучтенные элементы в рабочих каталогах
            for wkDirName in workingDirs:
                wkDir = workingDirs[wkDirName]
                if wkDir["exists"]:
                    entries = MyLib.getEntries(wkDirName)
                    for entry in entries:
                        if not entry in wkDir["entries"]:
                            wkDir["new"].append(entry)
            f.close()

        self.workingDirs = workingDirs
        self.needToSave = False
        return workingDirs
Exemple #17
0
def test():
    data = sio.loadmat(FLAGS.test_data_name)
    Y = data['RGB']
    Z = data['Zmsi']
    X = data['msi']

    ## banchsize H W C
    inY = np.expand_dims(Y, axis=0)
    inY = tf.to_float(inY)

    inZ = np.expand_dims(Z, axis=0)
    inZ = tf.to_float(inZ)

    inX = np.expand_dims(X, axis=0)
    inX = tf.to_float(inX)

    iniA = 0
    iniUp3x3 = 0

    outX, X1, YA, _, HY = MHFnet.HSInet(inY, inZ, iniUp3x3, iniA, FLAGS.upRank,
                                        FLAGS.outDim, FLAGS.HSInetL,
                                        FLAGS.subnetL)

    config = tf.ConfigProto(allow_soft_placement=True,
                            log_device_placement=True)
    config.gpu_options.allow_growth = True
    saver = tf.train.Saver(max_to_keep=5)
    save_path = FLAGS.train_dir

    with tf.Session(config=config) as sess:
        ckpt = tf.train.latest_checkpoint(save_path)
        saver.restore(sess, ckpt)
        pred_X, pred_YA, pred_HY, inX = sess.run([outX, YA, HY, inX])

    toshow = np.hstack((ML.normalized(ML.get3band_of_tensor(pred_HY)),
                        ML.get3band_of_tensor(pred_YA)))
    toshow2 = np.hstack(
        (ML.get3band_of_tensor(pred_X), ML.get3band_of_tensor(inX)))
    toshow = np.vstack((toshow, toshow2))
    ML.imshow(toshow)
    ML.imwrite(toshow)
Exemple #18
0
def PrepareDataAndiniValue():
    DataRoad = 'CAVEdata/'
    folder = os.path.exists(DataRoad + 'iniA.mat')
    if not folder:
        print('Generating the training and testing data in folder CAVEdata')
        Ind = [
            2, 31, 25, 6, 27, 15, 19, 14, 12, 28, 26, 29, 8, 13, 22, 7, 24, 30,
            10, 23, 18, 17, 21, 3, 9, 4, 20, 5, 16, 32, 11, 1
        ]
        #random index
        data = sio.loadmat('rowData/CAVEdata/response coefficient')
        R = data['A']
        ML.mkdir(DataRoad + 'X/')
        ML.mkdir(DataRoad + 'Y/')
        ML.mkdir(DataRoad + 'Z/')
        n = 0

        for root, dirs, files in os.walk('rowData/CAVEdata/complete_ms_data/'):
            for i in range(32):
                n = n + 1
                Z = np.zeros([16, 16, 31])
                print('processing ' + dirs[Ind[i] - 1])
                #                if dirs[Ind[i]-1]=='watercolors_ms':
                #                    X = readImofDir('rowData/CAVEdata/complete_ms_data/'+dirs[Ind[i]-1])/255
                #                else:
                X = readImofDir('rowData/CAVEdata/complete_ms_data/' +
                                dirs[Ind[i] - 1] + '/' +
                                dirs[Ind[i] - 1]) / 255
                Y = np.tensordot(X, R, (2, 0))
                for j in range(32):
                    for k in range(32):
                        Z = Z + X[j:512:32, k:512:32, :] / 32 / 32
                sio.savemat(DataRoad + 'X/' + dirs[Ind[i] - 1], {'msi': X})
                sio.savemat(DataRoad + 'Y/' + dirs[Ind[i] - 1], {'RGB': Y})
                sio.savemat(DataRoad + 'Z/' + dirs[Ind[i] - 1], {'Zmsi': Z})
                if n <= 20:
                    if n == 1:
                        allX = np.reshape(X, [512 * 512, 31])
                        allY = np.reshape(Y, [512 * 512, 3])
                    else:
                        allX = np.vstack((allX, np.reshape(X,
                                                           [512 * 512, 31])))
                        allY = np.vstack((allY, np.reshape(Y, [512 * 512, 3])))
            break
        allX = np.matrix(allX)
        allY = np.matrix(allY)
        iniA = (allY.T * allY).I * (allY.T * allX)
        sio.savemat(DataRoad + 'iniA', {'iniA': iniA})

        sio.savemat(DataRoad + 'List', {'Ind': Ind})

        initemp = np.eye(31)
        iniUp1 = np.tile(initemp, [3, 3, 1, 1])
        sio.savemat(DataRoad + 'iniUp', {'iniUp1': iniUp1})
    else:
        print('Using the prepared data and initial values in folder CAVEdata')
Exemple #19
0
def dilatacao(img, elem):

    pad = elem.shape[0]
    paddedImg = ml.paddingImage(img, padding_size=(pad // 2))
    imgNew = np.zeros(img.shape)

    for i in range(0, img.shape[0]):
        for j in range(0, img.shape[1]):
            non_zeros = np.count_nonzero(elem *
                                         paddedImg[i:i + pad, j:j + pad])
            if non_zeros == 0:
                imgNew[i, j] = 0
            else:
                imgNew[i, j] = 255

    return imgNew
Exemple #20
0
def update():
    MyLogger.logger.info("Lance la mise à jour.")
    try:
        if arguments["mode"] == "full" or arguments["mode"] == "client":
            MyLogger.logger.info("Update client")
            mergedListNoUpdate = config_json_project["client"]["update"][
                "noUpdate"] + config_json_private["client"]["update"][
                    "noUpdate"]
            MyLib.copytree(
                config_json_project["pathToFw"] + "/OdaClient/Deploy/",
                config_json_project["client"]["path"], True,
                mergedListNoUpdate)

            MyLogger.logger.info("Update client")
            mergedListNoUpdate = config_json_project["client"]["update"][
                "noUpdate"] + config_json_private["client"]["update"][
                    "noUpdate"]
            MyLib.copytree(config_json_project["pathToFw"] + "/OdaClient/Api/",
                           config_json_project["client"]["path"] + "/API/",
                           True, "")

        if arguments["mode"] == "full" or arguments["mode"] == "server":
            MyLogger.logger.info("Update server")
            mergedListNoUpdate = config_json_project["server"]["update"][
                "noUpdate"] + config_json_private["server"]["update"][
                    "noUpdate"]
            MyLib.copytree(
                config_json_project["pathToFw"] + "/OdaServer/Deploy/",
                config_json_project["server"]["path"], True,
                mergedListNoUpdate)

            MyLogger.logger.info("Update server")
            mergedListNoUpdate = config_json_project["server"]["update"][
                "noUpdate"] + config_json_private["server"]["update"][
                    "noUpdate"]
            MyLib.copytree(config_json_project["pathToFw"] + "/OdaServer/Api/",
                           config_json_project["server"]["path"] + "/API/",
                           True, "")

    except Exception as e:
        MyLogger.logger.error("Erreur pendant update : (" + format(e) + ")")
        sys.exit("Erreur")
Exemple #21
0
def im2Patch(Y, sizeC, ratio):
    k = 0
    H,W,C = Y.shape
    h = int(H/ratio)
    w = int(W/ratio)
    Ypatch = np.zeros([h*w*C, sizeC*sizeC],'f')
#    print(Ypatch.shape)
#    padY = mypadding(Y, (sizeC-ratio)/2)
    padY = np.squeeze(ML.mypadding(np.expand_dims(Y, axis = 0), int((sizeC-ratio)/2)),axis = 0)
    
    for i in range(sizeC):
        for j in range(sizeC):
            temp = padY[i:h*ratio+i:ratio,j:w*ratio+j:ratio,:]
#            print(temp.shape)
            Ypatch[:,k] = np.reshape(temp,[h*w*C])
            k=k+1
    
    return Ypatch
Exemple #22
0
    def read(self, fileName = CFG_FILE_NAME):
        workingDirs = {}
        try:
            f = open(fileName)
        except IOError as e:
            if e.errno != errno.ENOENT:
                print u"{0}. Код ошибки: {1}".format(e.strerror, e.errno)
                print u"Программа завершается."
                sys.exit()
        except:
            print u"Неизвестная ошибка."
            sys.exit()
        else:
            borderCnt = 0       # число прочитанных строк, содержащих BORDER_STR в начале
            for line in f:
                if line.startswith(BORDER_STR):
                    if borderCnt > 0:
                        break
                    borderCnt += 1
                elif line.startswith(WKDIR_LINE):
                    wkDirName = line[2:-1].decode("utf-8")
                    workingDirs[wkDirName] = {"entries": {}, "new": [], "exists": os.path.exists(wkDirName)}
                    wkDir = workingDirs[wkDirName]
                elif line.startswith(ENTRY_STR):
                    entryName = line[1:-1].decode("utf-8")
                    wkDir["entries"][entryName] = {"links": [], "exists": os.path.exists(os.path.join(wkDirName, entryName))}
                    entryLinks = wkDir["entries"][entryName]["links"]
                else:
                    linkName = line[:-1].decode("utf-8")
                    entryLinks.append(linkName)

            # ищем неучтенные элементы в рабочих каталогах
            for wkDirName in workingDirs:
                wkDir = workingDirs[wkDirName]
                if wkDir["exists"]:
                    entries = MyLib.getEntries(wkDirName)
                    for entry in entries:
                        if not entry in wkDir["entries"]:
                            wkDir["new"].append(entry)
            f.close()

        self.workingDirs = workingDirs
        self.needToSave = False
        return workingDirs
Exemple #23
0
def main():
    print("Element List Output")
    MyLib.loopListOutput()

    print("")

    print("Calculate List")
    MyLib.calculateList()

    print("")

    print("Ball Club Winning Chance")
    MyLib.winningChance()
Exemple #24
0
def PrepareDataAndiniValue():
    DataRoad = 'CAVEdata_2/'
    folder = os.path.exists(DataRoad)
    if not folder:
        Ind = [
            2, 31, 25, 6, 27, 15, 19, 14, 12, 28, 26, 29, 8, 13, 22, 7, 24, 30,
            10, 23, 18, 17, 21, 3, 9, 4, 20, 5, 16, 32, 11, 1
        ]
        #random index
        data = sio.loadmat('rowData/CAVEdata/response coefficient')
        R = data['A']
        ML.mkdir(DataRoad + 'X/')
        ML.mkdir(DataRoad + 'Y/')
        ML.mkdir(DataRoad + 'Z/')
        n = 0

        for root, dirs, files in os.walk('rowData/CAVEdata/complete_ms_data/'):
            files.sort()
            for i in range(32):
                n = n + 1
                if Ind[i] == 32:
                    X = readImofDir('rowData/CAVEdata/complete_ms_data/' +
                                    files[Ind[i] - 1]) / 255
                else:
                    X = readImofDir('rowData/CAVEdata/complete_ms_data/' +
                                    files[Ind[i] - 1]) / (2**16 - 1)
                Y = np.tensordot(X, R, (2, 0))
                for j in range(32):
                    for k in range(32):
                        Z = X + X[:, j:512:32, k:512:32, :] / 32 / 32
                sio.savemat(DataRoad + 'X/' + files[Ind[i] - 1], {'msi': X})
                sio.savemat(DataRoad + 'Y/' + files[Ind[i] - 1], {'RGB': Y})
                sio.savemat(DataRoad + 'Z/' + files[Ind[i] - 1], {'Zmsi': Z})
                if n <= 20:
                    if n == 1:
                        allX = np.reshape(X, [512 * 512, 31])
                        allY = np.reshape(Y, [512 * 512, 3])
                    else:
                        allX = np.hstack((allX, np.reshape(X,
                                                           [512 * 512, 31])))
                        allY = np.hstack((allY, np.reshape(Y, [512 * 512, 3])))
        allX = np.matrix(allX)
        allY = np.matrix(allY)
        iniA = (allY.T * allY).I * (allY.T * allX)
        sio.savemat(DataRoad, {'iniA': iniA})

        initemp = np.eye(31)
        iniUp1 = np.tile(initemp, [3, 3, 1, 1])
        sio.savemat(DataRoad, {'iniUp': iniUp1})
    else:
        print('Using the prepared data and initial values in folder CAVEdata')
Exemple #25
0
def TD_to_1D(pk_or_kr):
    if pk_or_kr[0] == 0:  #Normal plot
        partition = range(number / 2)
        block = len(partition)
        y = [0] * block
        y_n = [0] * block
        for i in range(number):
            for j in range(number):
                for k in range(number):
                    distance = math.sqrt(i**2 + j**2 + k**2)
                    distance = math.sqrt((i - number / 2)**2 +
                                         (j - number / 2)**2 +
                                         (k - number / 2)**2)
                    if distance < number / 2:
                        y[int(distance)] += pk_or_kr[1][i][j][k]
                        y_n[int(distance)] += 1
        for i in range(block):
            if y_n[i] <> 0:
                y[i] = y[i] / y_n[i]
        return partition, y

    elif pk_or_kr[0] == 1:  #Log plot
        partition = ml.Create_Partition(number / 2, 0)
        block = len(partition) - 1
        y = [0] * block
        y_n = [0] * block
        for i in range(number):
            for j in range(number):
                for k in range(number):
                    distance = math.sqrt((i - number / 2)**2 +
                                         (j - number / 2)**2 +
                                         (k - number / 2)**2)
                    for l in range(block):
                        if distance >= partition[l] and distance < partition[
                                l + 1]:
                            y_n[l] += 1
                            y[l] += pk_or_kr[1][i][j][k]
        del partition[-1]
        for i in range(block):
            if y_n[i] <> 0:
                y[i] = y[i] / y_n[i]
        return partition, y
Exemple #26
0
def main():
    # input
    x = int(input("Masukkan angka pertama untuk aritmatika:"))
    y = int(input("Masukkan angka kedua untuk aritmatika:"))
    s = float(input("Masukkan sisi persegi (float):"))
    a, t = map(float, input("Masukkan a & t segitiga (float)(float):").split())

    #output dengan memanggil fungsi pada aritmatika untuk masukan int
    print("Hasil Penjumlahan:", MyLib.Tambah(x, y))
    print("Hasil Pengurangan:", MyLib.Kurang(x, y))
    #berikut ini contoh men-assign hasil fungsi ke variable
    hasilkali = MyLib.Kali(x, y)
    print("Hasil Perkalian:", hasilkali)
    print("Hasil Pembagian:", MyLib.Bagi(x, y))

    #Luas
    print("Luas persegi:", MyLib.LuasPersegi(s))
    print("Luas segitiga:", MyLib.LuasSegitiga(a, t))
Exemple #27
0
            sys.exit("Erreur")
        else:
            arguments["fichier_conf"] = x
    elif i == 3:
        arguments["action"] = x
        if x not in ["install", "update", "more"]:
            MyLogger.logger.warning(
                "+Votre premier argument (" + x +
                ") est incorrect, seul 'install','update','more' sont aurorisés."
            )
            sys.exit("Erreur")
        else:
            MyLogger.logger.info("+Mode d'action choisi : " + x + ".")
    if len(arguments) == 0:
        arguments["action"] = "more"

#Initialisation
config_json = MyLib.charger_config(arguments["fichier_conf"])

#Affichage
if arguments["action"] == "install":
    install()
elif arguments["action"] == "update":
    update()
elif arguments["action"] == "more":
    more()

#Message de fin.
MyLogger.logger.info("+Fin du script.")
sys.exit(0)
    if i == 2 :
        arguments["jsonFile"] = x
    elif i == 3 :
        arguments["action"] = x
        if x not in ["lunch","more"] :
            MyLogger.logger.warning("Votre premier argument ("+x+") est incorrect, seul 'more','lunch' sont aurorisés.")
            sys.exit("Erreur")
        else :
            MyLogger.logger.info("Mode d'action choisi : "+x+".")
            arguments["action"] = x
            
    if len(arguments) == 0 :
        arguments["action"] = "more"

#Initialisation
config_json = MyLib.charger_config(arguments["jsonFile"])

#Message de bienvenue.
MyLogger.logger.info ("Chargement du json pour "+config_json["parameters"]["labelInstance"]+" reussi.")

#Affichage        
if arguments["action"] == "lunch" :
    lunch()
elif arguments["action"] == "more" :
    more()

#Message de fin.
MyLogger.logger.info ("Fin du script.")
sys.exit(0)

    
Exemple #29
0
"""

from PIL import Image
import numpy as np
import MyLib as ml

img1 = Image.open('images/ruidosa1.tif')
img1 = np.array(img1)

img2 = Image.open('images/ruidosa2.tif')
img2 = np.array(img2)

imgOrig = Image.open('images/original.tif')
imgOrig = np.array(imgOrig)

padding_size = ml.getPaddingSize(img1.shape, (11, 11))
img1Media = ml.conv2D(img1, ml.MEAN_FILTER_11, padding=padding_size, padding_type='repeat')
img1Mediana = ml.medianFilter(img1, (11, 11), padding_size, padding_type='repeat')
img1MedianaAdaptativa = ml.adaptativeMedian(img1, (17, 17))

titles1 = ["Imagem Original: ruidosa1.tif", "Filtro Média (11x11)", "Filtro Mediana (11x11)", "Filtro Mediana Adaptativa"]
images1 = [img1, img1Media, img1Mediana, img1MedianaAdaptativa]

print("PSNR da imagem: ruidosa1.tif")
print("Original: {}".format(ml.PSNR(imgOrig, img1)))
print("Media: {}".format(ml.PSNR(imgOrig, img1Media)))
print("Mediana: {}".format(ml.PSNR(imgOrig, img1Mediana)))
print("Mediana Adaptativa: {}".format(ml.PSNR(imgOrig, img1MedianaAdaptativa)))

padding_size = ml.getPaddingSize(img2.shape, (11, 11))
img2Media = ml.conv2D(img2, ml.MEAN_FILTER_11, padding=padding_size, padding_type='repeat')
Exemple #30
0
import numpy as np

import MyLib

print(MyLib.func1(1, 2))
print(MyLib.func2())

x = 0
MyLib.func3(x)
print(x)

v = MyLib.Vec3(1, 2, 3)
print(v[1])

print(v + np.array([1, 2, 3]))
Exemple #31
0
# -*- coding: utf-8 -*-
""" Processamento Digital de Imagens
    Aluno: Leonardo Santos Paulucio
    Lista de Exercicios 1 - Pós-Graduação
    Data: 09/05/19
"""

from PIL import Image
import numpy as np
import MyLib as ml

img = Image.open('images/Fig4.19(a).jpg')
img = np.array(img)

imgMed = ml.conv2D(img, ml.MEAN_FILTER2)  # Filtro media ponderada
# histograma = ml.calculaHistograma(img)            # Comentado, pois foi utilizado para escolher o threshold
# plt.plot(histograma[0], histogram[1])
# plt.show()
imgBin = ml.binarizaImg(imgMed, 200)  # Binarizacao da imagem
im = ml.conv2D(imgBin, ml.LAPLACE_FILTER)  # Filtro Laplaciano

images = [img, imgMed, imgBin, im]
titles = [
    "Imagem Original", "Resultado após Filtro Média Ponderada",
    "Imagem Binarizada", "Filtro Laplaciano"
]
ml.show_images(images, 2, titles)
Exemple #32
0
        # 9. Caso contrário, saímos. Os vértices em FECHADA são os vértices do ajuste poligonal dos pontos pertencentes a P.

    return closeStack


imgOrig = Image.open('images/pontos.bmp')
imgOrig = np.array(imgOrig)

points = findPoints(imgOrig, 255)
sorted = sortPoints(points)
images = [imgOrig]
title = ['Imagen Original']

fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 15)

for i in [1, 20, 50, 100, 300]:
    img = Image.fromarray(deepcopy(imgOrig))
    f = connectPoints(sorted, img, threshold=i)
    title.append('Resultado com Threshold = {}'.format(i))

    draw = ImageDraw.Draw(img)
    draw.line(f, fill=255, width=1)

    for i, p in enumerate(sorted):
        draw.text(p, str(i), font=fnt, fill=(255))

    img = np.array(img)
    images.append(img)

ml.show_images(images, 3, title)
Exemple #33
0
 def getServer(self):
     r = MyLib.post("messages.getLongPollServer", lp_version=3).json()
     self._key = r['response']['key']
     self._server = r['response']['server']
     self._ts = r['response']['ts']
Exemple #34
0
def install() :
    MyLogger.logger.info("Lance l'installation.")
    try:
        if arguments["mode"] == "full" or arguments["mode"] == "client" :
            MyLogger.logger.info("Install client")
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaClient/Deploy/",config_json_project["client"]["path"],True,"")

            MyLogger.logger.info("Personnalisation des fichiers clients.")
            for cur_fichier in config_json_private["client"]["install"]["fileToCusto"]:
                MyLogger.logger.debug("Edition du fichier : "+cur_fichier["pathInProject"]+cur_fichier["file"])
                MyLib.editFile(config_json_project["client"]["path"] + cur_fichier["pathInProject"] + cur_fichier["file"], config_json_project["client"]["install"]["values"])
            
            MyLogger.logger.info("Install client API")
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaClient/Api/",config_json_project["client"]["path"]+"/API/",True,"")

        if arguments["mode"] == "full" or arguments["mode"] == "server" :
            MyLogger.logger.info("Install server")
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaServer/Deploy/",config_json_project["server"]["path"],True,"")

            MyLogger.logger.info("Personnalisation des fichiers server.")
            for cur_fichier in config_json_private["server"]["install"]["fileToCusto"]:
                MyLogger.logger.debug("Edition du fichier : "+cur_fichier["pathInProject"]+cur_fichier["file"])
                MyLib.editFile(config_json_project["server"]["path"] + cur_fichier["pathInProject"] + cur_fichier["file"], config_json_project["server"]["install"]["values"])
            
            MyLogger.logger.info("Install server API")
            MyLib.copytree(config_json_project["pathToFw"]+"/OdaServer/Api/",config_json_project["server"]["path"]+"/API/",True,"")
            
    except Exception as e:
        MyLogger.logger.error("Erreur pendant install : ("+format(e)+")")
        sys.exit("Erreur")
Exemple #35
0
  Ok= False
  if os.path.isfile("error.log"):
    res= open("error.log",'r').read()
    if res.strip()=="PERFECT": Ok= True
    else: print "error.log="+res ; raw_input()
  else:
    print "error.log NOT FOUND"
  return Ok
#---------------------------------------------------------------------//

i0= 0
i=  0 
for sFile in files:
  if os.path.isfile("error.log"): os.remove("error.log")

  sCommand= ML.inn_scan_list(sFile,"TEST","COMPUTE")
  sDirout=  ML.inn_scan_word(sFile,"CONDITIONS","OUTPUT").replace('\\','/')
  sPath= os.path.dirname(sDirout)
  if not os.path.exists(sPath): os.makedirs(sPath)
  
  print '\n=========processing '+ sFile + '==========================\n'
  os.system("%s %s %s" % (sExe,sFile,Debug))
  
  if not check_done(): continue
  
  if "GEMPATH" in sCommand:
    if 1:
      s=sDirout+"_phase_grams.restab"
      titr= ML.extractFileName(s)
      lines= open(s,'r').readlines()
      labels,tData= ML.lines2table(lines)
Exemple #36
0
 def backup(self):
     existsBackups = [int(fileName.replace(CFG_FILE_BASE_NAME, "").replace(u".bak", "")) for fileName in MyLib.getFiles(APP_DIR) if fileName.endswith(u".bak")]
     if existsBackups:
         maxNum = max(existsBackups) + 1
     else:
         maxNum = 0
     self.save(fileName = os.path.join(APP_DIR, u"{0}{1}.bak".format(CFG_FILE_BASE_NAME, maxNum)))
    train_loss = sum_loss/N        
    train_data.append(float(train_loss))
    if epoch % show_interval == 0:
        print '\tepoch :'+str(epoch)
        print '\ttrain mean loss='+str(train_loss)+" next save :"+str(min_loss)
        print '\ttime sum : {}[sec] ave : {}[sec]'.format(sum_time,sum_time/time_count) 
#%%
    key = cv2.waitKey(1)
    if key in [myl.KEY_ESC, ord('q')]:
        break
    
    if min_loss > train_loss and not train_loss == 0 :
        network.saveModel('model/_model_pred'+str(epoch))
        min_loss = train_loss*save_rate   

    if epoch > n_epoch:
        print '\n!test clear! : '+str(train_loss)
        break
#%%
print '\n---Save model\n'
network.saveModel('model/_model_pred'+str(epoch))

print '\n---Save graph\n'
g_size = (8,6)
g_legend = ["train_loss"]
g_title = "Loss of digit recognition. lasl train loss :"+str(train_loss)  
g_file_name = 'graph_train_loss'+str(epoch)+'.png'
myl.showGraphData(train_data,g_size,g_legend,g_title,g_file_name)

cv2.destroyAllWindows()
Exemple #38
0
            MyLogger.logger.warning("+Votre second argument est ("+x+") est incorrect, un fichier de configuration .api.oda.json est attendu.")
            sys.exit("Erreur")
        else :
            arguments["fichier_conf"] = x
    elif i == 3 :
        arguments["action"] = x
        if x not in ["install", "update", "more"] :
            MyLogger.logger.warning("+Votre premier argument ("+x+") est incorrect, seul 'install','update','more' sont aurorisés.")
            sys.exit("Erreur")
        else :
            MyLogger.logger.info("+Mode d'action choisi : "+x+".")
    if len(arguments) == 0 :
        arguments["action"] = "more"

#Initialisation
config_json = MyLib.charger_config(arguments["fichier_conf"])    

#Affichage
if arguments["action"] == "install" :
    install()
elif arguments["action"] == "update" :
    update()
elif arguments["action"] == "more" :
    more()

#Message de fin.
MyLogger.logger.info ("+Fin du script.")
sys.exit(0)

    
Exemple #39
0
graph.windowSize(1000, 1000)
graph.canvasSize(1000, 1000)

x0 = 600
y0 = 300
r = 200

graph.penColor(0, 0, 0)
graph.penSize(0.05)
graph.brushColor(155, 155, 155)

graph.circle(x0, y0, r)

indent = r / 10

MyLib.sector(x0 - r / 5, y0 + r / 5, r, (3 / 2) * pi, 2 * pi, 1, 0)
MyLib.sector(x0 - r / 5 - indent, y0 + r / 5 + indent, r, (3 / 2) * pi, 2 * pi,
             1, 0)
MyLib.sector(x0 - r / 5 - 2.5 * indent, y0 + r / 5 + 2.5 * indent, r,
             (3 / 2) * pi, 2 * pi, 1, 0)

MyLib.sector(x0 + r / 4, y0 + r / 2, r, pi, (3 / 2) * pi - pi / 6, 1, 0)
MyLib.sector(x0 + r / 4 + 2 * indent, y0 + r / 2 + 2 * indent, r, pi,
             (3 / 2) * pi - pi / 6, 1, 0)
MyLib.sector(x0 + r / 4 + 4 * indent, y0 + r / 2 + 4 * indent, r, pi + pi / 10,
             (3 / 2) * pi - pi / 6, 1, 0)

graph.penColor(255, 255, 255)

smr = r / 2
x1 = x0 - r * sin(pi / 4) - smr * sin(pi / 4)
Exemple #40
0
                freemanChain.append(i)
                points.remove(currentPoint)
                sortedPoints.append(currentPoint)
                currentPoint = nextPoint
                break

    sortedPoints.append(currentPoint)
    sortedPoints.append(startPoint)
    return freemanChain, sortedPoints


img = Image.open('images/Fig11.10.jpg')
img = np.array(img)

# Getting object border
border = ml.conv2D(img, ml.LAPLACE_FILTER)

images = [deepcopy(border)]

# Getting border points
vertices = getPoints(border)

gridSize = 43
# Creating grid
grid = makeGrid(border, gridSize)

# Resampling border points to grid
points = convert2grid(vertices, grid)

# Finding Freeman chain
f, p = getFreemanChain(points, gridSize)
Exemple #41
0
import MyLib

print(MyLib.myAdd(1, 2))
Exemple #42
0
            MyLogger.logger.info("Mode d'action choisi : "+x+".")
    if i == 3 :
        arguments["mode"] = x
        if x not in ["client", "server", "full"] :
            MyLogger.logger.warning("Votre argument ("+x+") est incorrect, seul 'client','server','full' sont aurorisés.")
            sys.exit("Erreur")
        else :
            MyLogger.logger.info("Mode d'action choisi : "+x+".")
    elif i == 4 :
        if ".json" not in x:
            MyLogger.logger.warning("Votre argument est ("+x+") est incorrect, un fichier de configuration .json est attendu.")
            sys.exit("Erreur")
        else :
            arguments["fichier_conf"] = x
            #Initialisation
            config_json_private = MyLib.charger_config(pathFile + "/" + "private.config.odafw.json")
            config_json_project = MyLib.charger_config(arguments["fichier_conf"])

#Affichage
if arguments["action"] == "install" :
    install()
elif arguments["action"] == "update" :
    update()
elif arguments["action"] == "more" :
    more()

#Message de fin.
MyLogger.logger.info ("Fin du script.")
MyLogger.logger.info ("-------------------------------------------------------")
sys.exit(0)