コード例 #1
0
def detect(filePath, recT, type):
    # 调用接口
    # type:1 蓝火车票
    # type:2 红火车票
    # type:3 发票
    if os.access(filePath, os.F_OK):
        if type == 1:
            box = Detect.detect(cv2.imread(filePath), 1)
            jsR = DetectBlueTrainTicket(box, filePath)
            # print(jsR)
            return jsR

        if type == 2:
            box = Detect.detect(cv2.imread(filePath), 1)
            jsR = DetectRedTrainTicket(box, filePath)
            # print(jsR)
            return jsR

        if type == 3:
            box = Detect.detect(cv2.imread(filePath), 0.3)
            symbol = FindSymbol(filePath)
            jsR = DetectVATInvoice(box, symbol, filePath)
            # print(jsR)
            return jsR

    else:
        print("Can't open file " + filePath)
コード例 #2
0
def smallTalk():

    count = 0
    print "Tell me ssssomething."
    while count <= 5:
        statement = raw_input("> ").lower()

        if "stop" in statement or "bye" in statement:
            print "Letssss talk about ssssomething elsssssse."
            MainSelect.select()
        elif "ok" in statement:
            Detect.convoStarters()
        elif "how" in statement and "you" in statement:
            print "I'm doing good, how are you?"
            count += 1
        elif "good" in statement:
            print "I am glad."
            count += 1
        elif "bad" in statement:
            print "Aww. :( Why isssss that?"
            count += 1
        elif "what" in statement and "name" in statement:
            print "Can't you read!!! my name is Ssssssnakebot. \tWhat'ssss your name??"
            count += 1
        else:
            Detect.nonResponses()

    print "Do you want to keep talking?"
    if Detect.yesResponses(statement):
        count = 0
        smallTalk()
    else:
        "Okay. Letsssss try ssssomething elsssse."
        MainSelect.select()
コード例 #3
0
 def __set_file_type(self):
     try:
         self.file_type = Detect.get_type(self.host_filename)
         if self.file_type:
             self.__logging_queue.put((logging.INFO, "[instance=%d] Detected sample type: %s" % (self.instance, self.file_type), self.run_id))
         else:
             f_type = Detect.get_file_type(self.host_filename).lower()
             self.__logging_queue.put((logging.WARNING, "[instance=%d] Cannot process type: %s." % (self.instance, f_type), self.run_id))
             raise ProcessingFailed()
     except Exception as ex:
         raise ProcessingFailed(ex)
コード例 #4
0
 def __set_run_command(self):
     try:
         architecture = Detect.get_pefile_architecture(self.host_filename)
         if architecture == 0:
             architecture = None
         self.run_command = Detect.get_run_command(self.file_type, architecture, self.malware_execution_path + "\\" + self.agent_filename)
         if self.run_command:
             self.__logging_queue.put((logging.DEBUG, "[instance=%d] Run command: %s" % (self.instance, self.run_command), self.run_id))
         else:
             self.__logging_queue.put((logging.ERROR, "[instance=%d] Failed to get run command for: (%s,%s)" % (self.instance, self.file_type, architecture), self.run_id))
             raise ProcessingFailed()
     except Exception as ex:
         raise ProcessingFailed(ex)
コード例 #5
0
 def __init__(self):
     print "INITIALIZING..."
     self.detect = Detect.Detect(h_low_B, s_low_B, v_low_B, h_high_B,
                                 s_high_B, v_high_B, h_low_Gb, s_low_Gb,
                                 v_low_Gb, h_high_Gb, s_high_Gb, v_high_Gb,
                                 h_low_Gy, s_low_Gy, v_low_Gy, h_high_Gy,
                                 s_high_Gy, v_high_Gy)
     self.dribbler = Drib.Dribbler(port)
     self.motors = Motor.Motors_controller(port)
     self.coilgun = C.Coilgun(port)
     print "ALL INITIALIZED"
コード例 #6
0
def detection():
    global x, y, h, w
    res = None
    _file = max(glob.glob(PUBLIC_FOLDER_PATH + r'/*'), key=os.path.getctime)
    detection_model = Detect.Detector(_file)
    res = detection_model.detect()
    print(_file)
    if res[0] == -1:
        return json.dumps({'result': '-1'})
    else:
        x, y, w, h = [int(i) for i in res[2]]
        return redirect(CLASSIFICATION_ROUTE, code=307)
コード例 #7
0
def select():
    print "Would you like to talk about your family?"
    confirm = raw_input("> ")

    if Detect.yesResponses(confirm):
        Josie.family()
    print "Would you like to talk about the weather?"
    confirm = raw_input("> ")
    if Detect.yesResponses(confirm):
        Josie.weather()
    print "Would you like to talk about your hobbies?"
    confirm = raw_input("> ")
    if Detect.yesResponses(confirm):
        Nidhi.hobbies()
    print "Would you like to talk about animals?"
    confirm = raw_input("> ")
    if Detect.yesResponses(confirm):
        Nidhi.animals()
    print "Would you like to hear snake facts?"
    confirm = raw_input("> ")
    if Detect.yesResponses(confirm):
        Nidhi.snakefacts()
    print "Would you like to play Escape Room?"
    confirm = raw_input("> ")
    if Detect.yesResponses(confirm):
        Josie.escape_room_lobby()
    else:
        Ravisha.smallTalk()
コード例 #8
0
def __init__():
    chooseMod = 1
    if len(sys.argv) > 1:
        filePath = sys.argv[1]
        print("识别文件filePath:" + filePath)

        if len(sys.argv) > 2:
            if sys.argv[2] == '1':
                chooseMod = 1
            # 默认蓝色火车票
            if sys.argv[2] == '2':
                chooseMod = 2
                print("mod:" + str(chooseMod))
                # 红色火车票
            if sys.argv[2] == '11':
                chooseMod = 3
                # 专用增值税发票1

    else:
        filePath = 'Image_00066.jpg'
        print("识别文件filePath:")
        print("默认文件:Image_00068.jpg")

    if os.access(filePath, os.F_OK):
        if chooseMod == 1:
            box = Detect.detect(cv2.imread(filePath), 1)
            print(DetectBlueTrainTicket(box, filePath))

        if chooseMod == 2:
            box = Detect.detect(cv2.imread(filePath), 1)
            print(DetectRedTrainTicket(box, filePath))
        if chooseMod == 3:
            box = Detect.detect(cv2.imread(filePath), 0.3)
            symbol = FindSymbol(filePath)
            print(DetectVATInvoice(box, symbol, filePath))
    else:
        print("Can't open file " + filePath)
コード例 #9
0
    def sample_produce(self, samples_directory, database_filename, db_lock, message_queue, logging_queue):
        if not samples_directory:
            logging_queue.put((logging.INFO, 'Producer not started, samples_directory was not provided.'))
            return

        logging_queue.put((logging.INFO, 'Producer started.'))

        for sample_filename in glob.iglob(os.path.join(samples_directory, "*")):
            try:
                message = message_queue.get(False)
            except Queue.Empty:
                message = None
            if message:
                if message[0] == 'PRODUCER':
                    if message[1] == 'STOP':
                        logging_queue.put((logging.INFO, 'Producer stopped.'))
                        return
                else:
                    # Message wasn't for us replace it.
                    message_queue.put(message)

            architecture = Detect.get_pefile_architecture(sample_filename)
            with db_lock:
                db = database.SQLiteDatabase(database_filename)
                sample_sha1 = self.__sha1_for_file(sample_filename)
                db.insert(sample_sha1, sample_filename, architecture)
                db.close()
                logging_queue.put((logging.DEBUG, 'Added to db: %s - %s - %s' % (sample_sha1, architecture, sample_filename)))

        logging_queue.put((logging.INFO, 'Producer done.'))

        while True:
            try:
                message = message_queue.get(False)
            except Queue.Empty:
                message = None
            if message:
                if message[0] == 'PRODUCER':
                    if message[1] == 'STOP':
                        logging_queue.put((logging.INFO, 'Producer stopped.'))
                        return
                else:
                    # Message wasn't for us replace it.
                    message_queue.put(message)
コード例 #10
0
ファイル: test_cv.py プロジェクト: Ivosama/roboFriend
import sys
import eyes
import SmileDetection
import PyGame
import cum_hist as ch
import histogram as hg
import FrownDetection
import SmileDetectionOLD
import SmileDetectionEVENOLDER

eyes = eyes.Eyes()

cap = cv2.VideoCapture(0)

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
blobDetector = Detect.BlobDetector()
sys.setrecursionlimit(5000)

while True:
    ret, frame = cap.read()
    #frame = cv2.imread("TestImages/Straight Outta CREATE 2.png", cv2.IMREAD_COLOR)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    #gray = cv2.imread("TestImages/Peter.png", cv2.IMREAD_GRAYSCALE)
    editedImage = np.zeros((gray.shape[0], gray.shape[1]), np.uint8)

    faces = face_cascade.detectMultiScale(gray, 1.1, 5)
    PyGame.screen.fill((0, 0, 0))

    for (x, y, w, h) in faces:
        #cv2.imwrite("TestImages/NightSmile.png", gray)
        cv2.rectangle(editedImage, (x, y), ((x + w), (y + h)), (255, 0, 0), 2)
コード例 #11
0
org = (50, 50)
fontScale = 1
color = (255, 0, 0)
thickness = 1
if capture.isOpened() is False:
    print("Error opening camera")
while True:
    ret, frame = capture.read()
    if ret is True:
        detected = YOLO.humanDetect(frame)

        if detected is not None:

            #cv2.imshow("human detected",detected)
            #cv2.waitKey()
            print("Human Detected")
            face = Detect.detect_face(detected)
            mask = Detect.detect_mask(face)
            print(mask)

        else:
            print('Human Not detected')
        frame = cv2.putText(frame, mask, org, font, fontScale, color,
                            thickness, cv2.LINE_AA)
        cv2.imshow("Video", frame)
        if cv2.waitKey(2) & 0xFF == ord('q'):
            break

capture.release()
cv2.destroyAllWindows()
コード例 #12
0
def surface(filename, type='blue'):
    filepath = os.path.join('allstatic', filename)

    # 原方法
    if type == None:
        midProcessResult = detectType.detectType('allstatic', filename)  # tangpeng 预处理
        # 未分类
    else:
        if type == 'blue' or type == 'excess':
            # return out_filename, 1, pipe.textlines, cdic
            midProcessResult = PipeInvoice.getPipe('allstatic', filename, type, False)
        else:
            ##type == 'red'
            midProcessResult = [None, None, None]
            out_filename = filename.replace('upload', 'out')
            out_filename = os.path.join('allstatic', out_filename)

            # 拷贝到out
            shutil.copy(filepath, out_filename)

            midProcessResult[0] = out_filename
            midProcessResult[1] = 2  # 专票
            # 暂时用原图,不用校正后的图
            midProcessResult[2] = textline(midProcessResult[0])
    # 行提取
    blueTemplet = {
        'departCity': [48, 62, 222, 56],
        'arriveCity': [412, 61, 228, 55],
        'trainNumber': [264, 62, 170, 57],
        'invoiceDate': [24, 139, 369, 42],
        'seatNum': [408, 138, 160, 40],
        'idNum': [22, 276, 306, 38],
        'passenger': [328, 276, 150, 38],
        'totalAmount': [33, 177, 151, 39],
        'ticketsNum': [21, 10, 195, 66]
    }

    '''        'departCity': [29, 74, 218, 54],
            'arriveCity': [425, 68, 224, 64],
            'trainNumber': [230, 65, 203, 62],
            'invoiceDate': [0, 163, 357, 41],
            'seatNum': [392, 164, 203, 46],
            'idNum': [0, 343, 350, 45],
            'totalAmount': [3, 206, 212, 52],
            'ticketsNum': [34, 40, 202, 47]
        }'''
    redTemplet = {
        'idNum': [66, 242, 357, 38],
        'departCity': [66, 66, 222, 45],
        'arriveCity': [388, 66, 225, 47],
        'trainNumber': [288, 53, 103, 41],
        'invoiceDate': [66, 114, 237, 43],
        'seatNum': [400, 115, 210, 46],
        'totalAmount': [66, 163, 188, 34],
        'ticketsNum': [21, 23, 218, 47]
    }
    ''''''
    excessTemplet = {
        'departCity': [26, 40, 151, 33],
        'arriveCity': [271, 40, 169, 33],
        'trainNumber': [178, 35, 92, 32],
        'invoiceDate': [12, 82, 203, 29],
        'seatNum': [315, 79, 136, 33],
        'totalAmount': [12, 118, 167, 28],
        'ticketsNum': [23, 12, 147, 37]
    }

    # vatinvoice
    VATInvoiceTemplet = {
    }


    if midProcessResult[1] == 1:
        TemType = blueTemplet

    if midProcessResult[1] == 2:
        TemType = redTemplet

    if midProcessResult[1] == 3:
        TemType = excessTemplet

    if midProcessResult[1] == 11:  # 增值税专用             预留
        dic = xmlToDict.XmlTodict('VATInvoiceMuban.xml')

        tplt = [dic['QRCode'][0], dic['QRCode'][1], dic['figureX'][0] + dic['figureX'][2] / 2,
                dic['figureX'][1] + dic['figureX'][3] / 2]
        # print(tplt)
        for c in tplt:
            if c == None:
                print('Templet VATInvoice error')

        for item in dic:
            if item != 'QRCode' and item != 'figureX':
                # print(item)
                # tmp = MakeFileInV([[int(dic.get(item)[0]), int(dic.get(item)[1])], [int(dic.get(item)[2]), int(dic.get(item)[3])]], box, symbol, filePath, item, tplt)
                VATInvoiceTemplet[item] = [int(dic.get(item)[0]), int(dic.get(item)[1]), int(dic.get(item)[2]),
                                           int(dic.get(item)[3])]
        TemType = VATInvoiceTemplet

    rate = 1
    fcv = cv2.imread(filepath, 1)
    w1 = fcv.shape
    if w1[0] + w1[1] > 1500:
        rate = 0.5
        # print("rate : 0.5")

    if midProcessResult[1] == 1:
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        Templet = adjustToTextLine(TemType, box, midProcessResult[1], None)  # 蓝火车票
    if midProcessResult[1] == 2:
        rate = 2.0
        print("rate : 2.0")
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        # print( box.tolist())
        Templet = adjustToTextLine(TemType, box, midProcessResult[1], None)  # 红火车票
    if midProcessResult[1] == 3:
        rate = 1.0
        print("rate : 1.0")
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        # print( box.tolist())
        Templet = adjustToTextLine(TemType, box, midProcessResult[1], None)  # 红(补票)车票
    if midProcessResult[1] == 11:
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        figureP = FindCircle.findSymbol(filepath)
        StBox = sortBox(box)
        Templet = adjustToTextLine(TemType, [StBox[0], StBox[1], figureP[0], figureP[1]], midProcessResult[1],
                                   tplt)  # 增值税专票

    attributeLine = lineToAttribute.getAtbt.compute(midProcessResult[2], Templet)

    # 生成行提取的图片
    plt_rects = []
    for x in attributeLine:
        plt_rects.append(attributeLine[x])
    # 显示
    vis_textline0 = fp.util.visualize.rects(cv2.imread(midProcessResult[0], 0), plt_rects)
    pl.imshow(vis_textline0)
    # 保存到line目录
    pltpath = midProcessResult[0].replace("out", "line")
    try:
        pl.savefig(pltpath)
    except Exception as e:
        print("绘制行提取图片不支持bmp格式:{}".format(e))
        pass

    return midProcessResult[0], midProcessResult[1], attributeLine
コード例 #13
0
ファイル: main.py プロジェクト: liaohhhhhh/denoisy
import loaddata
import Method
import Detect

if __name__ == '__main__':
    input_dir = input('--input_dir:')
    output_dir = input('--output_dir:')
    datas = loaddata.Dataset(input_dir)
    datas.creat_outdir(output_dir)

    SIZE = 5
    for i in range(datas.getlen()):
        print(datas.getname(i))
        img = datas.getitem(i)
        r = Detect.search(img)
        img1 = img.copy()
        img2 = img.copy()
        for row in range(5, img.shape[0] - 5):
            for col in range(5, img.shape[1] - 5):
                if r[row][col] == 255:
                    img1[row][col] = Method.canny1(img, r, row, col)
                    img1[row][col] = Method.equalize(img, img1[row][col], row,
                                                     col)
                else:
                    img1[row][col] = img[row][col]

        for row in range(5, img.shape[0] - 5):
            for col in range(5, img.shape[1] - 5):
                if r[row][col] == 255:
                    #img2[row][col] = Method.canny(img1, r, row, col)
                    img2[row][col] = Method.c_mean(img1, row, col, SIZE)
コード例 #14
0
ファイル: submit.py プロジェクト: jimmythegreat/panda-malrec
def sha1_for_file(filename, block_size=2**20):
        f = open(filename, 'rb')
        sha1 = hashlib.sha1()
        while True:
            data = f.read(block_size)
            if not data:
                break
            sha1.update(data)
        digest = sha1.hexdigest()
        f.close()
        return digest


if __name__ == '__main__':
    args = get_arguments()
    db = database.SQLiteDatabase(args.database_filename)
    added = 1
    target = os.path.join(args.samples_directory, "*") if os.path.isdir(args.samples_directory) else args.samples_directory
    for sample_filename in glob.iglob(target):
        try:
            architecture = Detect.get_pefile_architecture(sample_filename)
            sample_sha1 = sha1_for_file(sample_filename)
            db.insert(sample_sha1, sample_filename, architecture)
            if not args.quiet or (added % 1000) == 0:
                print '[%d] Added to db: %s - %s - %s' % (added, sample_sha1, architecture, sample_filename)
            added += 1
        except Exception as ex:
            if not args.quiet:
                print 'Failed: %s : %s' % (sample_filename, ex.message)
    print 'Added %d samples to the database: %s' % (added, args.database_filename)
    db.close()
コード例 #15
0
ファイル: Demo.py プロジェクト: Chunshan-Theta/SEX_Detect
for i in range(300):
    data = Image.open('./Test/0/W_'+str(i)+'.jpeg') 
    a,c = Detect.DetectAPic(data)
    #print a,c
    if a == 1:count+=1
'''

count =0
NumPic = 0.0

for dirPath, dirNames, fileNames in os.walk('./Test/1/'):
    NumPic = len(fileNames)
    for f in fileNames:#os.path.join(dirPath, f)
        data = Image.open(os.path.join(dirPath, f)) 
        a,c = Detect.DetectAPic(data)
        print 'pic src:',dirPath,f,'prediction:',a,'confident:',c,'%'
        if a == 1:
            count+=1

for dirPath, dirNames, fileNames in os.walk('./Test/0/'):
    NumPic += len(fileNames)
    for f in fileNames:#os.path.join(dirPath, f)
        data = Image.open(os.path.join(dirPath, f)) 
        a,c = Detect.DetectAPic(data)
        print 'pic src:',dirPath,f,'prediction:',a,'confident:',c,'%'
        if a == 0:
            count+=1

print 'successful:',float(count)/float(NumPic),'%'
'''
コード例 #16
0
ファイル: main.py プロジェクト: Slugskickass/NDR_detection
import Detect as dt
import numpy as np
import matplotlib.pyplot as plt
import ruptures as rpt

file_name = 'Example_data.tif'

data = dt.loadtiffs(file_name)
#empty_events = dt.collect_non_event(data, 80)
#lines = dt.fit_line(empty_events)
#slopes, intercepts, breakpoints = dt.change_point(data[71, 98, :], sigma=5, diff=1)

data = data[110:140, 160:190, :]
XS, YS, yy = np.shape(data)
holdall = np.zeros((XS, YS))
for indexx, X in enumerate(range(np.shape(holdall)[0])):
    for indexy, Y in enumerate(range(np.shape(holdall)[0])):
        data_point = [X, Y]
        my_data = np.diff(data[data_point[0], data_point[1], :])
        out = np.asarray(dt.ck_filter(my_data, 3))
        slopes, intercepts, breakpoints = dt.change_point(out, sigma=5)
        holdall[indexx, indexy] = len(breakpoints)


plt.imshow(holdall)
plt.show()

[x, y] = np.where(holdall == np.max(holdall))
for I in range(-4, 5):
    line_data = data[x[0]+I, y[0], :]
    out = np.asarray(dt.ck_filter(np.diff(line_data), 3))
コード例 #17
0
def init(filepath, type):
    # filepath = 'Image_065.jpg'
    '''if len(sys.argv) > 1:
        filePathg = sys.argv[1]
        filepath = filePathg
    '''
    # print(sys.argv)
    # print(filepath)
    if type == None:
        midProcessResult = detectType.detectType(filepath)  # tangpeng 预处理
        # 未分类
    else:
        if type == 'blue' or type == 'excess':
            midProcessResult = PipeInvoice.getPipe(filepath, type, False)
        else:
            ##type == 'red'
            midProcessResult = [None, None, None]
            midProcessResult[0] = filepath
            midProcessResult[1] = 2  # 专票
            midProcessResult[2] = textline(midProcessResult[0])
    # midProcessResult = [None, None]
    # midProcessResult[0] = midPR[0]
    # midProcessResult[1] = midPR[1]
    # midProcessResult[0] = filepath
    # 行提取
    blueTemplet = {
        'departCity': [48, 62, 222, 56],
        'arriveCity': [412, 61, 228, 55],
        'trainNumber': [264, 62, 170, 57],
        'invoiceDate': [24, 139, 369, 42],
        'seatNum': [408, 138, 160, 40],
        'idNum': [22, 276, 306, 38],
        'passenger': [328, 276, 150, 38],
        'totalAmount': [33, 177, 151, 39],
        'ticketsNum': [21, 10, 195, 66]
    }
    '''        'departCity': [29, 74, 218, 54],
            'arriveCity': [425, 68, 224, 64],
            'trainNumber': [230, 65, 203, 62],
            'invoiceDate': [0, 163, 357, 41],
            'seatNum': [392, 164, 203, 46],
            'idNum': [0, 343, 350, 45],
            'totalAmount': [3, 206, 212, 52],
            'ticketsNum': [34, 40, 202, 47]
        }'''
    redTemplet = {
        'idNum': [66, 242, 357, 38],
        'departCity': [66, 66, 222, 45],
        'arriveCity': [388, 66, 225, 47],
        'trainNumber': [288, 53, 103, 41],
        'invoiceDate': [66, 114, 237, 43],
        'seatNum': [400, 115, 210, 46],
        'totalAmount': [66, 163, 188, 34],
        'ticketsNum': [21, 23, 218, 47]
    }
    ''''''
    excessTemplet = {
        'departCity': [26, 40, 151, 33],
        'arriveCity': [271, 40, 169, 33],
        'trainNumber': [178, 35, 92, 32],
        'invoiceDate': [12, 82, 203, 29],
        'seatNum': [315, 79, 136, 33],
        'totalAmount': [12, 118, 167, 28],
        'ticketsNum': [23, 12, 147, 37]
    }

    # vatinvoice
    VATInvoiceTemplet = {}

    dic = xmlToDict.XmlTodict('VATInvoiceMuban.xml')

    tplt = [
        dic['QRCode'][0], dic['QRCode'][1],
        dic['figureX'][0] + dic['figureX'][2] / 2,
        dic['figureX'][1] + dic['figureX'][3] / 2
    ]
    # print(tplt)
    for c in tplt:
        if c == None:
            print('Templet VATInvoice error')

    # print(VATInvoiceTemplet)
    # midProcessResult[1] = 2#专票 for test
    # TemType = redTemplet #默认蓝票
    if midProcessResult[1] == 1:
        TemType = blueTemplet

    if midProcessResult[1] == 2:
        TemType = redTemplet

    if midProcessResult[1] == 3:
        TemType = excessTemplet

    if midProcessResult[1] == 11:  # 增值税专用             预留
        for item in dic:
            if item != 'QRCode' and item != 'figureX':
                # print(item)
                # tmp = MakeFileInV([[int(dic.get(item)[0]), int(dic.get(item)[1])], [int(dic.get(item)[2]), int(dic.get(item)[3])]], box, symbol, filePath, item, tplt)
                VATInvoiceTemplet[item] = [
                    int(dic.get(item)[0]),
                    int(dic.get(item)[1]),
                    int(dic.get(item)[2]),
                    int(dic.get(item)[3])
                ]
        TemType = VATInvoiceTemplet

    rate = 1
    # print(filepath)
    fcv = cv2.imread(filepath, 1)
    # print(fcv)
    w1 = fcv.shape
    if w1[0] + w1[1] > 1500:
        rate = 0.5
        print("rate : 0.5")

    if midProcessResult[1] == 1:
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        Templet = adjustToTextLine(TemType, box, midProcessResult[1],
                                   None)  # 蓝火车票
    if midProcessResult[1] == 2:
        rate = 2.0
        print("rate : 2.0")
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        # print( box.tolist())
        Templet = adjustToTextLine(TemType, box, midProcessResult[1],
                                   None)  # 红火车票
    if midProcessResult[1] == 3:
        rate = 1.0
        print("rate : 1.0")
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        # print( box.tolist())
        Templet = adjustToTextLine(TemType, box, midProcessResult[1],
                                   None)  # 红(补票)车票
    if midProcessResult[1] == 11:
        box = Detect.detect(cv2.imread(midProcessResult[0]), rate)
        figureP = FindCircle.findSymbol(filepath)
        StBox = sortBox(box)
        # print(box)
        # print(figureP)
        # print(StBox)
        Templet = adjustToTextLine(
            TemType, [StBox[0], StBox[1], figureP[0], figureP[1]],
            midProcessResult[1], tplt)  # 增值税专票

    im = cv2.imread(filepath, 0)
    rec = []
    for c in TemType:
        rec.append(TemType[c])
    vis_textline0 = fp.util.visualize.rects(im, rec)
    # vis_textline1 = fp.util.visualize.rects(im, rects, types)
    # 显示
    pl.figure(figsize=(15, 10))
    pl.subplot(2, 2, 1)
    pl.imshow(im, 'gray')

    pl.subplot(2, 2, 2)
    pl.imshow(vis_textline0)
    pl.show()

    # print(textline(midProcessResult[0]))
    attributeLine = lineToAttribute.getAtbt.compute(midProcessResult[2],
                                                    Templet)

    # print(attributeLine)
    # print(type(attributeLine))
    # print(attributeLine['departCity'])
    jsonResult = flow.cropToOcr(midProcessResult[0], attributeLine,
                                midProcessResult[1])  # ocr和分词
    print(jsonResult)
    return jsonResult
コード例 #18
0
    def __init__(self, configuration_filename, vm_section_name, sample_name, sample_sha1, instance, logging_queue):
        self.handles = []

        Detect.set_paths(configuration_filename)

        self.__logging_queue = logging_queue
        if not os.path.isfile(configuration_filename):
            raise ConfigFailed("[instance=%d] configuration_filename is not a file" % instance)

        if instance < 1:
            raise ConfigFailed("[instance=%d] instance must be greater than 0" % instance)

        self.config = ConfigParser.ConfigParser()
        self.config.read(configuration_filename)

        self.vm_section_name = vm_section_name

        self.sample_name = sample_name
        self.sample_sha1 = sample_sha1
        self.instance = int(instance)
        self.monitor_port = 1234 + self.instance

        self.working_directory = None

        self.execution_time = None
        self.panda_directory = None
        self.panda_exe = None
        self.results_directory = None
        self.sample_results_directory = None
        self.pcap_filename = None
        self.malware_execution_path = None
        self.replay_base = None
        self.qcow_location = None
        self.revert_instead_of_copy = None
        self.refresh_network = None
        self.snapshot_name = None
        self.cmd_open = None
        self.auto_play_disabled = None
        self.compress_replay = None
        self.vm_memory = None
        self.delete_original = None
        self.work_in_working = None

        self.host_filename = None
        self.file_type = None
        self.agent_filename = None
        self.run_command = None
        self.iso_file = None
        self.new_qcow = None
        self.panda_process = None

        self.monitor_tries = 10
        self.__monitor = None

        self.run_id = None

        self.__keymap = {'-': 'minus',
                         '=': 'equal',
                         '[': 'bracket_left',
                         ']': 'bracket_right',
                         ';': 'semicolon',
                         '\'': 'apostrophe',
                         '\\': 'backslash',
                         ',': 'comma',
                         '.': 'dot',
                         '/': 'slash',
                         '*': 'asterisk',
                         ' ': 'spc',
                         '_': 'shift-minus',
                         '+': 'shift-equal',
                         '{': 'shift-bracket_left',
                         '}': 'shift-bracket_right',
                         ':': 'shift-semicolon',
                         '"': 'shift-apostrophe',
                         '|': 'shift-backslash',
                         '<': 'shift-comma',
                         '>': 'shift-dot',
                         '?': 'shift-slash',
                         '\n': 'ret',
                         '%': 'shift-5',
                         }
コード例 #19
0
ファイル: lantester.py プロジェクト: strunz983/Lantester
def main():

    global interface, sniff, protocol, flags, target_ip, port_range, reverse, scanType, detection

    if len(sys.argv[1:]):
        try:
            opts, args = getopt.getopt(sys.argv[1:], "sS:P:f:t:p:rd:h:", [
                "sniff", "scan=", "proto=", "flags=", "target=", "port=",
                "reverse", "detect=", "help"
            ])
        except:
            usage()
            sys.exit()
    try:

        for o, a in opts:
            if o in ("-h", "--help"):
                usage()
                sys.exit()
            elif o in ("-s", "--sniff"):
                sniff = True
            elif o in ("-S", "--scan"):
                scanType = a
            elif o in ("-P", "--proto"):
                protocol = a
            elif o in ("-f", "--flags"):
                flags = a
            elif o in ("-t", "--target"):
                if outils.is_valid_ip(a):
                    target_ip = a
                else:
                    try:
                        target_ip = socket.gethostbyname(a)
                    except:
                        print "Impossible de trouver l'adresse IP correspondante ."
                        usage()
                        sys.exit()

            elif o in ("-p", "--port"):
                list = a.split(",")
                if len(list) == 2:
                    p, q = map(int, list)
                    port_range = range(p, q + 1)
                elif len(list) == 1:
                    port_range = [int(a)]
            elif o in ("-r", "--reverse"):
                reverse = True
            elif o in ("-i", "--interface"):
                interface = a
            elif o in ("-d", "--detect"):
                detection = a
            elif o in ("-h", "--help"):
                usage()
                sys.exit()
    except:

        sys.exit()

    if scanType:
        if sniff or reverse or protocol or (scanType == "udp" and flags) or (
                scanType == "icmp-echo" and (flags or port_range)):
            usage()
            sys.exit()

        import scanner
        queue = Queue.Queue()
        cidr = outils.cidr(target_ip)
        if len(cidr) == 2:
            ip_list = outils.get_addresses(cidr[0], cidr[1])
        else:
            ip_list = cidr

        startTime = time.time()
        if scanType != "icmp-echo":
            for ip in ip_list:
                scanner.target_ip = ip
                for j in range(15):
                    if scanType == "tcp":
                        scan = scanner.TCPScanner(queue, flags)
                        scan.setDaemon(True)
                        scan.start()
                    elif scanType == "udp":
                        scan = scanner.UDPScanner(queue)
                        scan.setDaemon(True)
                        scan.start()
                if port_range:
                    for port in port_range:
                        queue.put(port)
                else:
                    for port in range(1, 1025):
                        queue.put(port)
                queue.join()

                scanner.scan_report(startTime, scanType, port_range)

        else:
            for j in range(15):
                scan = scanner.pingScan(queue)
                scan.setDaemon(True)
                scan.start()
            for ip in ip_list:
                queue.put(ip)

            queue.join()

            scanner.scan_report(startTime, scanType, None)

    elif detection:
        import Detect
        if detection == "dhcpserver":
            Detect.detect_DHCP_servers(interface)
        elif detection == "arppoison":
            Detect.detect_arp_poison(target_ip, interface)

    elif protocol:
        if sniff or scanType or flags or target_ip or reverse:
            usage()
            sys.exit()
        if protocol == "dhcp":
            import DHCPtester
            DHCPtester.DHCPtester()
        elif protocol == "dns":
            import DNS
            DNS.DNStester()
        elif protocol == "arp":
            import ARP_attaque
            ARP_attaque.menu()
    elif reverse:
        if sniff or scanType or flags or target_ip or port_range or protocol:
            usage()
            sys.exit()
        import Reverse
        Reverse.reverse()
    elif sniff:
        if scanType or flags or not (target_ip) or port_range or not (
                interface) or reverse or protocol:
            import Sniffer
            sniffer = Sniffer.Sniffer(interface, "tcp", 80, target_ip)
            sniffer.sniff()
sys.path.append(os.path.join(os.path.dirname(__file__), 'Monolith'))
import Classify
import Detect
import recommendationengine

DIRPATH = os.path.dirname(os.path.realpath(__file__))
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
UPLOAD_FOLDER = DIRPATH + '/static/uploads'

app = Flask(__name__, root_path=DIRPATH)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

# Load Models
print('Loading Object Detection Model')
detection_model = Detect.Detector()
print('Loading Classification Model')
classification_model = Classify.Classifier()


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def detection(file):
    res = detection_model.detect(file)
    if res[0] == -1:
        return -1
    else:
        return 1
コード例 #21
0
import MainSelect
import Detect
import Ravisha

print "I am Sssssnake bot, I like to chat with humanssss."
print "Hello!"
question = raw_input("> ")
question = question.lower()

while "bye" not in question:

    if "hello" in question or "hi" in question or "hey" in question:
        print "How are you?"
        statement = raw_input("> ").lower()

        if Detect.yesResponses(statement):
            print "That issss good, I'm glad I could be here for it."
            print "Do you want to talk about ssssomething?"
            statement = raw_input("> ").lower()
            if Detect.yesResponses(statement):
                MainSelect.select()
            else:
                print "Okay, we'll talk later then. Sssssee ya."

        elif "bad" in statement.lower() or "not" in statement.lower(
        ) or "meh" in statement.lower():
            print "Oh no, can I make your day better?"
            confirm = raw_input("> ")
            if Detect.yesResponses(confirm):
                MainSelect.select()
            else:
コード例 #22
0
def animals(): #gives responses about different animals that the user talks about
    count = 0
    print "What are your favorite animals?"
    while count < 5:
        statement = raw_input("> ").lower()
        if "stop" in statement:
            print "Alright, let'sssss try a different topic."
            MainSelect.select()
        elif "snake" in statement:
            print "The besssst animal!"
            count += 1
        elif "dog" in statement:
            print "Dog is man'ssss besssst friend."
            count += 1
        elif "cat" in statement:
            print "What greater gift than the love of a cat."
            count += 1
        elif "rabbit" in statement or "bunny" in statement:
            print "What'sss up, doc?"
            count += 1
        elif "hamster" in statement or "guinea pig" in statement:
            print "Mmmmmm dinner."
            count += 1
        elif "fish" in statement:
            print "'I know the human being and fisssssh can co-exist peacefully.' - George W. Busssssh"
            count += 1
        elif "bird" in statement:
            print "Polly want a cracker?"
            count += 1
        elif "turtles" in statement:
            print "Sssslow and sssssteady winssss the race."
            count += 1
        elif "whale" in statement:
            print "The giantsssss of the water."
            count += 1
        elif "shark" in statement:
            print "Sssssharks aren't the monstersssss we make them out to be."
            count += 1
        elif "monkey" in statement or "chimp" in statement or "orangutan" in statement or "baboon" in statement or "gorrillas" in statement or "howler" in statement or "gibbons" in statement or "capuchin" in statement:
            print "People go to the zoo and they like the lion because it's ssscary," \
            " and the bear becausssse it's intensssse, but the monkey makessss people laugh."
            count += 1
        elif "elephant" in statement:
            print "The wisssessst of animalssss."
            count += 1
        elif "dolphin" in statement:
            print "If I had to come back in life, I'd come back assss a dolphin... " \
                  "they're alwayssss smiling; they're alwaysssss playing."
            count += 1
        elif "tiger" in statement or "panther" in statement or "lion" in statement or "jaguar" in statement or "leopard" in statement or "cheetah" in statement or "cougar" in statement or "puma" in statement:
            print "Big catsssss are just small catsssss with bigger teeth and clawsssss."
            count += 1
        elif "horse" in statement:
            print "The wind of heaven is that which blowsssss between a horsssse's earssss."
            count += 1
        else:
            print "Fasssssscinating. Beautiful creaturessss everywhere on thissss earth!"
            count += 1
        if count < 5:
            print "What other animalssss do you like?"

    print "Do you want to talk about animals more? (yes/no)" #asks if user wants to continue talking about animals after 5 sentences
    statement2 = raw_input("> ").lower()
    if Detect.yesResponses(statement2):
        pets()
    else:
        print "Okay, let'ssss talk about something elsssse."
        MainSelect.select()
コード例 #23
0
def hobbies(): #gives responses to different hobby types, including sports and the arts
    count = 0
    print "What are your hobbiesssss? Sportsss? Perhapssss the artsss?"
    while count <= 5:
        statement = raw_input("> ").lower()
        if "stop" in statement:
            print "Alright, let'sssss try a different topic."
            MainSelect.select()
        elif "soccer" in statement:
            print "Goooooooooooooaaaaaaalllll!!!"
            count += 1
        elif "football" in statement:
            print "The grind never sssstopsssss."
            count += 1
        elif "volleyball" in statement:
            print "Ssssssspike it."
            count += 1
        elif "baseball" in statement:
            print "Keep your eyesssss on the ball."
            count += 1
        elif "tennis" in statement:
            print "Game, ssssset, match!"
            count += 1
        elif "basketball" in statement:
            print "KOBE."
            count += 1
        elif "cricket" in statement:
            print "The key will be early wicketsssss."
            count += 1
        elif "golf" in statement:
            print "Hole in one."
            count += 1
        elif "swimming" in statement:
            print "Jussssst like a fissssssh."
            count += 1
        elif "draw" in statement or "drawing" in statement:
            print "The firsssst writing of the human being wasssss drawing, not writing."
            count += 1
        elif "dance" in statement or "dancing" in statement:
            print "Dance isssss the hidden language of the sssssoul."
            count += 1
        elif "read" in statement or "reading" in statement:
            print "A reader livesssss a thousand livesssss before he diessss. The man who never readsssss livesssss only one."
            count += 1
        elif "game" in statement:
            print "Life isssss a game."
            count += 1
        elif "music" in statement:
            print "That'sssss groovy. Musssssic is the key to the ssssoul."
            count += 1
        elif "sleep" in statement or "sleeping" in statement:
            print "Have fun exploring the cavernsssss of your pillowsssss."
            count += 1
        elif "writing" in statement or "write" in statement:
            print "There isssss no greater agony than bearing an untold sssssstory inside you."
            count += 1
        elif "photography" in statement or "photo" in statement:
            print "A picture issss worth a thoussssand wordssss."
        else:
            print "That'ssssss interesting... Sssoundssss fun!"
            count += 1
        if count < 5:
            print "What other hobbiessss do you enjoy?"
    print "Do you want to talk about your hobbiessss more? (yes/no)" #asks if user wants to continue talking about hobbies after 5 sentences
    statement2 = raw_input("> ").lower()
    if Detect.yesResponses(statement2):
        hobbies()
    else:
        print "Okay, let'ssss talk about something elsssse."
コード例 #24
0
def snakefacts(): #user puts in a number from 1-20 and Snakebot gives out a snake fact
    count = 0
    print "Give me an integer from 1 - 20 and I'll give you a sssssnake fact."
    while count < 5:
        statement = raw_input("> ").lower()
        if "stop" in statement:
            print "Alright, let'sssss try a different topic."
            MainSelect.select()
        statement = int(statement)
        if statement == 20:
            print "Ssssnakes range in ssssize from the tiny, 10 cm-long thread ssssnake, " \
            "to the reticulated python of up to 6.95 meterssss (22.8 ft) in length."
            count += 1
        elif 19 == statement:
            print "There's an isssland in Brazil where civilianssss are forbidden to go: " \
                  "it hassss up to 5 snakessss per ssssquare meter."
            count += 1
        elif 18 == statement:
            print "Sssssnakessss can have two headssss and fight each other for food."
            count += 1
        elif 17 == statement:
            print "The top ten deadliesssst ssssnakessss can be found in Australia."
            count += 1
        elif 16 == statement:
            print "Ssssnakessss can open their mouth up to 150 degreessss."
            count += 1
        elif 15 == statement:
            print "The Titanoboa lived 60 million yearssss ago and issss the largessst, " \
            "longesssst, and heaviesssst ssssnake ever discovered."
            count += 1
        elif 14 == statement:
            print "Ssssnakessss don't have eyelidssss."
            count += 1
        elif 13 == statement:
            print "Ssssnakessss usssse their tonguessss to ssssmell."
            count += 1
        elif 12 == statement:
            print "51% of Americanssss fear snakessss, most than any other thing in the world."
            count += 1
        elif 11 == statement:
            print "There has never been sssssnakessss in Ireland becausssse being cold-blooded, " \
                  "sssssnake couldn't ssssurvive the frozen ground during the ice age in the passsst."
            count += 1
        elif 10 == statement:
            print "More than 20 ssssnake familiessss are currently recognized, " \
                  "comprissssing about 500 genera and about 3,400 ssssspeciessss."
            count += 1
        elif 9 == statement:
            print "Military commandossss in Lebanon eat live ssssnakessss, " \
                  "a tradition to dissssplay their sssstrength and daring."
            count += 1
        elif 8 == statement:
            print "Ssssnakessss can ssssensssse other animalssss approaching by detecting faint vibrationssss " \
                  "in the air and on the ground."
            count += 1
        elif 7 == statement:
            print "Ssssome ssssnakessss ssssurvive for up to two yearssss without a meal."
            count += 1
        elif 6 == statement:
            print "The vertebral column of ssssnakessss consistssss of anywhere between 200 to 400 vertebrae."
            count += 1
        elif 5 == statement:
            print "Ophidiophobia issss the abnormal fear of ssssnakessss."
            count += 1
        elif 4 == statement:
            print "'King' in a ssssnake'sss name sssssignifiessss that it preys on other ssssnakessss."
            count += 1
        elif 3 == statement:
            print "The decapitated head of a dead ssssnake can still bite, even hourssss after death." \
                  " These typessss of bitessss usually contain huge amountssss of venom."
            count += 1
        elif 2 == statement:
            print "The top 5 mosssst venomous ssssnakessss in the world are the inland taipan, the eassstern brown ssssnake, " \
                  "the coasssstal taipan, the tiger ssssnake, and the black tiger ssssnake."
            count += 1
        elif 1 == statement:
            print "Ssssome ssssnakessss have over 200 teeth."
            count += 1
        else:
            print "Thosssse who do not read instructionssss do not receive sssssnake facts."
        if count < 5:
            print "Put in another integer from 1 - 20 for another ssssplendid sssssnake fact."
    print "Do you want to talk about ssssnakes more? (yes/no)" #asks if user wants to continue talking about snake facts after 5 sentences
    statement2 = raw_input("> ").lower()
    if Detect.yesResponses(statement2):
        snakefacts()
    else:
        print "Okay, let'ssss talk about something elsssse."
        MainSelect.select()