Exemplo n.º 1
0
 def do_POST(self):
     if self.path == "/ws/ezsp-query":
         post_data = self.get_postdata()
         eq = post_data["ezsp-query"]
         ans = ws.ezspquery(eq[0])
         bs = bytes(ans, "utf-8")
         self.wfile.write(bs)
     elif self.path == "/ws/write-order-to-srv":
         post_data = self.get_postdata()
         ans = ws.create_order(post_data["data"][0])
         bs = bytes(ans, "utf-8")
         self.wfile.write(bs)
     elif self.path == "/auth":
         post_data = self.get_postdata2()
         login = post_data["username"]
         password = post_data["userpassrord"]
         if auth.baseauth(self, login[0], password[0]):
             pass
         else:
             self.ans_like_404()
     elif self.path == "/registration":
         post_data = self.get_postdata2()
         login = post_data["username"]
         password = post_data["userpassrord"]
         registration.registration(login[0], password[0])
         self.ans_like_text_file("html/index.html", "text/html")
     elif self.path == "/tam":
         length = int(self.headers["Content-Length"])
         rb = self.rfile.read(length)
         f = open("tam/report.req", "w", encoding="utf-8")
         f.write(rb.decode("utf-8"))
         f.close()
Exemplo n.º 2
0
 def do_POST( self ):
     if self.path == "/ws/ezsp-query":
         post_data = self.get_postdata()
         eq = post_data[ "ezsp-query" ]
         ans = ws.ezspquery( eq[0] )
         bs = bytes( ans, "utf-8" )
         self.wfile.write( bs )
     elif self.path == "/ws/write-order-to-srv":
         post_data = self.get_postdata()
         ans = ws.create_order( post_data[ "data" ][ 0 ] )
         bs = bytes( ans, "utf-8" )
         self.wfile.write( bs )
     elif self.path == "/auth":
         post_data = self.get_postdata2()
         login = post_data[ "username" ]
         password = post_data[ "userpassrord"]
         if auth.baseauth(self, login[0], password[0]):
             pass
         else:
             self.ans_like_404()
     elif self.path == "/registration":
         post_data = self.get_postdata2()
         login = post_data[ "username" ]
         password = post_data[ "userpassrord"]
         registration.registration(login[0], password[0])
         self.ans_like_text_file( "html/index.html", "text/html" )
     elif self.path == "/tam":
         length = int( self.headers[ "Content-Length" ] )
         rb = self.rfile.read( length )
         f = open( "tam/report.req", "w", encoding = "utf-8" )
         f.write( rb.decode( "utf-8" ) )
         f.close()
Exemplo n.º 3
0
def registration_mode():
    encoded_card_id = base64.b64encode(generated_id.encode('utf-8'))
    text = "등록되지 않은 카드입니다. 등록이 필요합니다."
    tts = gTTS(text=text, lang='ko')
    f = open(filename, 'wb')
    tts.write_to_fp(f)
    f.close()
    playsound(filename)
    registration.registration(encoded_card_id)
Exemplo n.º 4
0
def atdchk():
    conn = sqlite3.connect("memberlist.db")
    cur = conn.cursor()

    #target_card = nfctoid.scan_id()
    target_card = nfctoid_test.scan_id()
    print(target_card + "가 인식되었습니다.")

    cur.execute("SELECT COUNT(CARD) FROM MEMBERS WHERE CARD = '" +
                target_card + "'")
    card_rows = cur.fetchall()
    if card_rows[0][0] == 1:
        cur.execute("SELECT ATD FROM MEMBERS WHERE CARD = '" + target_card +
                    "'")
        atd_rows = cur.fetchall()
        atdnum = atd_rows[0][0]

        now = datetime.datetime.now()
        year_now = now.year
        month_now = now.month
        day_now = now.day

        cur.execute("SELECT LASTCHECKED FROM MEMBERS WHERE CARD = '" +
                    target_card + "'")
        last_date = cur.fetchall()[0][0]  #last_date is a str

        converted_date = datetime.datetime.strptime(
            last_date.split()[0],
            "%Y-%m-%d").date()  # This will be changed into date object.
        year_checked = converted_date.year
        month_checked = converted_date.month
        day_checked = converted_date.day
        if randint(0, 2) == 0:  #for test code
            day_now = day_checked + 1

        cur.execute("SELECT NAME FROM MEMBERS WHERE CARD = '" + target_card +
                    "'")
        name = cur.fetchall()

        if day_checked == day_now and month_checked == month_now and year_checked == year_now:
            print(name[0][0] + "님은 이미 오늘 출석하셨습니다.")
            print("오늘은 " + str(year_now) + "년 " + str(month_now) + "월 " +
                  str(day_now) + "일입니다.")
            print("마지막으로 출석한 날짜는 " + str(year_checked) + "년 " +
                  str(month_checked) + "월 " + str(day_checked) + "일입니다.\n")
        else:
            cur.execute(
                "UPDATE MEMBERS SET ATD = ?, LASTCHECKED = DATETIME('NOW','LOCALTIME') WHERE CARD = ?",
                (atdnum + 1, target_card))
            conn.commit()
            print(name[0][0] + "님, 출석이 완료되었습니다. 감사합니다!")
            print("오늘은 " + str(year_now) + "년 " + str(month_now) + "월 " +
                  str(day_now) + "일입니다.")  #for test code
    else:
        registration.registration(target_card)
Exemplo n.º 5
0
def registration_api():
    user = flask.request.get_json()
    try:
        post_check.registration(user)
    except ValidationError:
        return "Bad Request"
    return registration(user)
Exemplo n.º 6
0
def atdchk():
    conn = sqlite3.connect("memberlist.db")
    cur = conn.cursor()

    target_card = nfctoid.scan_id()
    print(target_card + "가 인식되었습니다.")

    cur.execute("SELECT COUNT(CARD) FROM MEMBERS WHERE CARD = '" + target_card + "'")
    card_rows = cur.fetchall()
    if card_rows[0][0] == 1:
        cur.execute("SELECT ATT FROM MEMBERS WHERE CARD = '" + target_card + "'")
        att_rows = cur.fetchall()
        attnum = att_rows[0][0]
        cur.execute("UPDATE MEMBERS SET ATT = ?, LASTCHECKED = DATETIME('NOW','LOCALTIME') WHERE CARD = ?", (attnum+1, target_card))
        conn.commit()
    else:
        registration.registration()
Exemplo n.º 7
0
def processImage(imgPath, directory, modality):

    # for debugging
    print(imgPath)

    # Determine prefix and directory
    if not directory:
        directory = os.path.dirname(os.path.abspath(imgPath))
    elif not os.path.exists(directory):
        os.makedirs(directory)

    prefix = os.path.basename(imgPath).split('.')[0]

    # check if 'reg' keyword exists in prefix, if not then register to fixedImage
    if 'reg' not in prefix:
        print(
            '\'reg\' keyword is not present in input image. Registering with reference image ...'
        )

        if modality == 't1':
            regPath = registration(directory, prefix, fixedImaget1,
                                   fixedMaskt1, imgPath)
        else:
            regPath = registration(directory, prefix, fixedImaget2,
                                   fixedMaskt2, imgPath)
    else:
        regPath = imgPath
        print('Registered image found ...')

    # load the mri and the mask
    mri = loadImage(regPath)

    # extract feature from the mri
    # histName = os.path.join(directory, prefix + '-histogram' + '.npy')
    # H_test= slide_filter(mri*mask, histName)
    H_test = slide_filter(mri, '')

    dim = np.shape(mri)

    fid = open(os.path.join(directory, prefix + '-quality' + '.txt'), 'w')

    print("Checking quality ...")
    prediction = predictQuality(dim, H_test, modality, fid)

    return prediction
Exemplo n.º 8
0
def scan_id():
    id = [
        'AD:CG:3F:4B', 'EF:5F:95:60', '3D:51:B9:9A', '25:DB:C0:A4',
        '4D:D0:56:7D'
    ]
    num = randint(0, len(id) - 1)
    # params = {'card_id': id[num]}
    # url = 'http://127.0.0.1:8000/register/'
    generated_id = id[num]
    url = 'http://127.0.0.1:8000/chulseokcheck/'
    s = requests.Session()
    r1 = s.get(url=url)
    csrf_token = r1.cookies['csrftoken']
    # r2 = s.post(url=url, headers={'X-CSRFToken': csrf_token}, data=json.dumps(params))
    r2 = s.post(url=url,
                headers={'X-CSRFToken': csrf_token},
                data={'card_id': generated_id})
    print(r2.status_code, r2.reason)
    print(r2.text)
    filename = 'temp.mp3'

    # Get status code and register
    if json.loads(r2.text)['status'] == 2:
        encoded_card_id = base64.b64encode(generated_id.encode('utf-8'))
        text = "등록되지 않은 카드입니다. 등록이 필요합니다."
        tts = gTTS(text=text, lang='ko')
        f = open(filename, 'wb')
        tts.write_to_fp(f)
        f.close()
        playsound(filename)
        registration.registration(encoded_card_id)
    else:
        #return id[num]
        text = json.loads(r2.text)['name'] + "님 환영합니다."
        tts = gTTS(text=text, lang='ko')
        f = open(filename, 'wb')
        tts.write_to_fp(f)
        f.close()
        playsound(filename)
Exemplo n.º 9
0
def mainmenu():
    print("Welcome to the MAIN MENU \n \nPlease enter the number you wish to perform.")
    menuoption = input("1. View top customers for rewards program. \n2. Production Discontinuation & Break-even analysis based on discounts. \n3. View top subcategories to focus on. \n4. View charts for Sales \n5. Register a new user. \n6. Logout and return to login screen. \n0. Exit\nOPTION:").strip()
    if menuoption =="":
        print(blankerror)
        mainmenu()
    elif menuoption =="1":
        rewardprog()
    elif menuoption =="2":
        discontinuityprog()
    elif menuoption =="3":
        subcatmenu1()
    elif menuoption =="4":
        chartmenu1()
    elif menuoption =="5":
        registration.registration()
    elif menuoption =="6":
        Login.login()
    elif menuoption =="0":
        SystemExit(0)
    else:
        print(invalid)
        mainmenu()
def registration_module_test(inputDir):
    '''
    This function opens all images in a directory,
    converts them to the format for the module,
    passes in the images, and writes the returned
    images to the output directory.
    '''
    # Get all jpg files in directory
    imageFiles = glob.glob(os.path.join(inputDir, '*.jpg'))
    imageVolume = skimage.io.ImageCollection(imageFiles, as_grey=True).concatenate()

    # If we have ITK, use that algorithm
    if itkLoaded:
        # ITK algorithms use ITK to read/write
        registered_images = itk_affine_registration.itk_affine_registration(imageFiles)

    # Try the brainmix-register algorithm
    elif skimageloaded and brainmixloaded:
        registered_images = bm.registration(imageVolume)
        
    else:
        sys.exit("No libraries are loaded")
def registration_module_test(inputDir):
    '''
    This function opens all images in a directory,
    converts them to the format for the module,
    passes in the images, and writes the returned
    images to the output directory.
    '''
    # Get all jpg files in directory
    imageFiles = glob.glob(os.path.join(inputDir, '*.jpg'))
    imageVolume = skimage.io.ImageCollection(imageFiles,
                                             as_grey=True).concatenate()

    # If we have ITK, use that algorithm
    if itkLoaded:
        # ITK algorithms use ITK to read/write
        registered_images = itk_affine_registration.itk_affine_registration(
            imageFiles)

    # Try the brainmix-register algorithm
    elif skimageloaded and brainmixloaded:
        registered_images = bm.registration(imageVolume)

    else:
        sys.exit("No libraries are loaded")
Exemplo n.º 12
0

def display():
    pass


if __name__ == "__main__":
    # ------------------Create input ndarray------------------------
    inputDir = '../data/test/'
    imageFiles = glob.glob(os.path.join(inputDir, '*.jpg'))
    imageVolume = io.ImageCollection(imageFiles, as_grey=True).concatenate()
    stack = imageVolume

    # ------------------Check that single image registration works----

    src = stack[0]
    dst = stack[1]

    reg_dst = reg.reg(src, dst)

    # ------------- Check that stack registration works -----------

    reg_stack = reg.registration(stack)

    merged = [reg.overlay_pics(stack[0], img) for img in stack]
    merged_reg = [reg.overlay_pics(reg_stack[0], img) for img in reg_stack]
    image = data.coins()

    viewer = viewer.CollectionViewer(merged_reg)
    viewer.show()
Exemplo n.º 13
0
def run(server_class=http.server.HTTPServer,
        handler_class=HTTPServer_RequestHandler):
    print('Starting server...')

    # Server Configuration from file config.cfg
    config = {}
    cfg = configparser.ConfigParser()
    if not cfg.read(["config.cfg"]):
        print("File does not exist")
    if cfg.has_option("net", "ip"):  #ip
        config['ip'] = cfg.get("net", "ip")
    else:
        print("Config file need to have ip field")
    #if cfg.has_option("net", "name"): #host_name
    #    config['host_name'] = cfg.get("net", "name")
    #else:
    #    print ("Config file need to have name field")
    if cfg.has_option("net", "port"):  #port
        config['port'] = int(cfg.get("net", "port"))
    else:
        print("Config file need to have port field")
    if cfg.has_option("net", "file_key"):  #file_key
        config['file_key'] = cfg.get("net", "file_key")
    else:
        print("Config file need to have file_key field")
    if cfg.has_option("net", "file_cert"):  #file_key
        config['file_cert'] = cfg.get("net", "file_cert")
    else:
        print("Config file need to have file_cert field")
    #if cfg.has_option("net", "max_conect"): #max_conect
    #    max_conexiones = int(cfg.get("net", "max_conect"))
    #else:
    #    print ("Config file need to have max_conect field")

    # Create the kernel and learn AIML files for bot response
    bot.initialize()

    # Server settings
    server_address = (config['ip'], config['port'])
    httpd = server_class(server_address, handler_class)
    #httpd.socket.listen(max_conexiones) #Límite de clientes conectados

    # Seguridad https
    httpd.socket = ssl.wrap_socket(
        httpd.socket,
        keyfile=config['file_key'],  #keyfile = RUTA_KEY,
        certfile=config['file_cert'],  #certfile = RUTA_CERT,
        server_side=True,
    )

    # Authentication token
    tokens.server_token().get_token()

    # Registro en el dispatcher
    reg = registration.registration()
    reg.register()

    # Creación de recursos en la base FHIR si no existen
    fhir_client.DB_device_creation()
    fhir_client.DB_device_request_creation()
    fhir_client.DB_procedure_request_creation()

    # Cambio estado Device
    fhir_client.device_update_DB("active")

    # Run and Stop server
    #while True:
    try:
        #Ejecución del servidor
        httpd.serve_forever()
        #httpd.handle_request() #handle one request (while loop needed)
        print('Running server...')
        print('Server port:', port)

    except KeyboardInterrupt:
        print('Keyboard interrupt received: EXITING')

    finally:
        #Desregistro en el dispatcher
        dereg = deregistration.deregistration()
        dereg.deregister()

        #Cambio estado Device
        fhir_client.device_update_DB("inactive")

        #Apagado del servidor
        httpd.shutdown()
        httpd.server_close()
        print('Server stopped')
        return
Exemplo n.º 14
0
import registration as reg
import psswd_encr as encr

if __name__ == "__main__":

    try:
        while True:
            what_to_do = input(
                "Type auth to login or reg to create a new user:\n->")
            # Registration Part
            if what_to_do.lower() == "reg":
                My_user = False
                while not My_user:
                    ln = input("Type your login\n->")
                    pwd = input("Type your password\n->")
                    My_user = reg.registration(ln, pwd)
            # Authentification
            elif what_to_do.lower() == "auth":
                My_user = False
                while not My_user:
                    ln = input("Type your login\n->")
                    pwd = input("Type your password\n->")
                    My_user = reg.authentication(ln, pwd)
            what_to_do = input(f"{My_user.name}, what you want to do?\n->")
            # Password Generation
            if what_to_do.lower() == "gen":
                psswd_lst = gen.password_output()
                psswd = ''
                for ent in psswd_lst:
                    psswd += str(ent)
                print(f"Your password is:\n->{psswd}")
Exemplo n.º 15
0
import registration
import existance
import qr_reader
import delete
import show
import transaction

conn = sqlite3.connect('bookshelf.db')
c = conn.cursor()

x = input(
    "registration>>>r, show>>>s, delete>>>d, lend>>>l, return>>>ret, (init>>>i) "
)

if x == 'r':
    registration.registration(c)
elif x == 's':
    show.show(c)
elif x == 'd':
    delete.delete(c)
elif x == 'l':
    transaction.lend_book(c)
elif x == 'ret':
    transaction.return_book(c)
elif x == 'i':
    registration.initialize(c)
else:
    print("Sorry, that key is not available.")

conn.commit()
conn.close()
import unittest
from registration import registration
from log_cook import log_cook
from io import StringIO
import sys
from coding import coding
from fake_Connection_database import fake_Conection_database
R = registration()
LK = log_cook()


class TestStringMethods(unittest.TestCase):
    def test_regist_kuchar(self):
        sys.stdout = StringIO()
        meno, heslo = "Matej", "543210"
        sys.stdin = StringIO(meno + '\n' + heslo)
        R.connection = fake_Conection_database()
        R.connection.good_sql_exe_script = "\ninsert into xpkuchari( meno, heslo) VALUES (%s,%s)"
        R.regist_cook()
        self.assertEqual(
            sys.stdout.getvalue(),
            "registracia kuchara\nzadaj meno:\nzadaj heslo:\npodarilo sa\n")
        self.assertEqual(
            list(R.connection.values.keys())[0],
            tuple([meno, coding().hash_password(heslo)]))
        sys.stdin = sys.__stdin__
        sys.stdout = sys.__stdout__

    def test_regist_casnik(self):
        sys.stdout = StringIO()
        meno, heslo = "Matej", "543210"
Exemplo n.º 17
0
 def test_login(self):
     registration.registration(self.user)
     self.user["password"] = "******"
     query = r.db("TravTest").table("user").get("*****@*****.**").run()
     self.assertEqual(query["email"], self.user["email"])
     self.login_phase()
Exemplo n.º 18
0
def display():
    pass


if __name__ == "__main__":
    # ------------------Create input ndarray------------------------
    inputDir = '../data/test/'
    imageFiles = glob.glob(os.path.join(inputDir, '*.jpg'))
    imageVolume = io.ImageCollection(imageFiles, as_grey=True).concatenate()
    stack = imageVolume

    # ------------------Check that single image registration works----

    src = stack[0]
    dst = stack[1]

    reg_dst = reg.reg(src, dst)

    # ------------- Check that stack registration works -----------
    
    reg_stack = reg.registration(stack)

    merged = [reg.overlay_pics(stack[0], img) for img in stack]
    merged_reg = [reg.overlay_pics(reg_stack[0], img) for img in reg_stack]
    image = data.coins()

    viewer = viewer.CollectionViewer(merged_reg)
    viewer.show()

Exemplo n.º 19
0
 def test_list(self):
     obj = registration()
     obj.list()
Exemplo n.º 20
0
import pickle

import registration
import character

if character.load_game():
    print(character.character)
else:
    registration.registration()
    character.save_game()
    print(character.character)


Exemplo n.º 21
0
 def test_register(self):
     obj = registration()
     assert email == premchouhan @ gmail.com
     with pytest.raises(NameError):
         obj.register_user()
Exemplo n.º 22
0
    def parse_timers(self):
        """Parse timers from game and save them locally"""
        browser = RoboBrowser(history=True, cache=True, parser='lxml', user_agent=self.USERAGENT)
        try:
            browser.open('http://avatar.botva.ru/')

        except ConnectionError:
            print('ConnectionError')
            return False

        try:
            loginform = browser.get_form(action='login.php')
            loginform["email"] = botva_login
            loginform["password"] = botva_pass
            browser.session.headers['Referer'] = 'http://avatar.botva.ru/'
            browser.submit_form(loginform)

        except TypeError:
            if self.check_updateworks(browser):
                browser.session.close()
                return False

        except ConnectionError:
            browser.session.close()
            return False

        browser.open('http://avatar.botva.ru/conflict.php')

        if 'options.php' in browser.url:  # game freeze pers in options.php when it's blocked
            open("need_new_bot", "w").write("need")  # signal to tg bot

            # registration new bot
            from registration import registration
            from settings import name_id
            email = botva_login.replace(str(name_id), str(name_id+1))
            names = ["MrSmith-%s" % str(name_id+1),
                    ]
            with open(bot_dir_path + "settings.py", 'r') as f:
                st = f.read()
                start_login = st.find('\nbotva_login')
                end_login = st.find('\n', start_login+1)

                actual_login = st[start_login:end_login]

                st = st[
                     :start_login+1] + "# " + st[
                                    start_login+1:end_login] + "\n" + "botva_login = "******"'" + email + "'" + st[
                                                                                                            end_login:]
                st = st.replace(f"name_id = {name_id}", f"name_id = {name_id+1}")

            registration(names, email, botva_pass)

            with open(bot_dir_path + "settings.py", 'w') as f:  # write new credentials in settings
                f.write(st)

            return False

        for el in browser.find_all(class_='status1'):

            enemy_part = re.findall(r'data-enemy_id="(\d+)"', str(el))[0]
            our_part = re.findall(r'data-loc_id="(\d+)"', str(el))[0]
            _btl_time = re.findall(r'(\d+):(\d+):(\d+)', str(el))[0]
            
            try:
                dtimer = dt.now().replace(
                    hour=int(_btl_time[0]), 
                    minute=int(_btl_time[1]), 
                    second=int(_btl_time[2])
                    )
            except Exception as e:
                print(f'{dt.now().time()}, error: {e}\n {_btl_time}')
                break
                
            if int(_btl_time[0]) < dt.now().hour:
                dtimer = dtimer + timedelta(1)

            timer = dtimer.timestamp()
            btl_time = ':'.join(_btl_time)

            btl_text = '{} {}/{}'.format(
                    btl_time, 
                    self.part_resurs[int(our_part)-1], 
                    self.part_resurs[int(enemy_part)-1]
                    )

            if btl_text not in self.btl_timers.values() and timer > time.time()+100:
                self.btl_timers[timer] = btl_text

        browser.session.close()

        timers = self.btl_timers.copy()  # del old msgs from base
        for t in timers.keys():
            if time.time() > float(t):
                self.btl_timers.pop(t)
                self.write_btl_to_file()

        return True
Exemplo n.º 23
0
 def setUpClass(cls):
     registration.registration(user)
     user["password"] = "******"
 def signup(self):
     messagebox.showinfo('Success', 'Going To The Registration Form')
     self.window.destroy()
     iv = registration()
Exemplo n.º 25
0
            conn.settimeout(1)
            print('connected:', addr)

            data_res = ''
            while True:
                data1 = conn.recv(1024)
                if not data1.endswith('#'.encode('utf-8')):
                    data_res += data1.decode('utf-8')
                else:
                    data_res += data1.decode('utf-8')[0:-1:1]
                    break

            jsData = dict(js.loads(data_res))
            print(jsData)
            if jsData['type'] == 'RegistrationEvent':
                conn.send(reg.registration(jsData))
                conn.close()
                continue
                print("Finish")
            elif jsData['type'] == 'BuildEvent':
                conn.send(build.build(jsData))
                conn.close()
                print("Finish")
                continue
            elif jsData['type'] == 'AuthorizationEvent':
                conn.send(reg.authorization(jsData))
                conn.close()
                print("Finish")
                continue
            elif jsData['type'] == 'DestroyEvent':
                conn.send(build.destroy(jsData))
        j += 1
        if j == 1000:
            break
    return np.array(pointCloud)


if __name__ == '__main__':
    start = time.clock()
    threshold = 100
    cloud1 = readData("pointcloud1.fuse")
    cloud2 = readData("pointcloud2.fuse")
    pk = copy.copy(cloud1)

    # get the error of the first two iterations to use in the while loop condition
    yk = minDist(pk, cloud2)
    qr, qt = registration(cloud1, yk)
    dk1 = getDk(qr, qt, cloud1, yk)
    pk = np.dot(cloud1, createR(qr.transpose())) + qt

    yk = minDist(pk, cloud2)
    qr, qt = registration(cloud1, yk)
    dk2 = getDk(qr, qt, cloud1, yk)
    pk = np.dot(cloud1, createR(qr.transpose())) + qt

    print "DK: ", dk1, dk2
    while dk1 - dk2 > threshold:
        dk1 = dk2
        yk = minDist(pk, cloud2)
        qr, qt = registration(cloud1, yk)
        dk2 = getDk(qr, qt, cloud1, yk)
        # pk = np.subtract(np.dot(cloud1,createR(qr.transpose())), qt)
Exemplo n.º 27
0
				flag_excluded = True
			else:
				target_folder = "preproc/"
			print(filex)
			x = imgtonumpy(filex)  # .astype(numpy.float)
			datax = json.load(open(filex.replace("png", "json")))

			# fix some errors in the JSON exports
			if '00281054' in datax.keys():
				if datax['00281054']['vr'] != ['CS']:
					datax['00281054']['vr'] = ['CS']
			if '20500020' in datax.keys():
				if datax['20500020']['vr'] != ['CS']:
					datax['20500020']['vr'] = ['CS']

			ds1 = pydicom.dataset.Dataset.from_json(datax)
			lut = pydicom.pixel_data_handlers.util.apply_modality_lut(x, ds1).astype(numpy.uint16)
			# print(x.max(), lut.max(), lut.shape)
			lut = pydicom.pixel_data_handlers.util.apply_voi_lut(lut, ds1).astype(numpy.float)
			lut = normalization(lut)
			if ds1[0x0028,0x0004].value == "MONOCHROME1":
				lut = -1*(lut-255)
			lut = shape_as(lut)
			# x = cv2.GaussianBlur(x,(5,5),cv2.BORDER_DEFAULT)
			target_file_name = filex.replace(".png", "_preproc.png")
			# numpytoimg(lut, target_folder + target_file_name.split("/")[-1])
			if ((not flag_excluded) and (not path.exists("registered/"+target_file_name.split('/')[-1]))):
				# print("entro {}".format("registered/"+filex.split('/')[-1]))
				lut = registration(lut, ref_numpy)
				numpytoimg(lut, "registered/" + target_file_name.split("/")[-1])
Exemplo n.º 28
0
 def test_register(self):
     obj = registration()
     assert email == premchouhan @ gmail.com
     with pytest.raises(NameError):
         obj.register(email, password, confirm_password)