Пример #1
0
 def __init__(self, result, img=None):
     self.result = union_rbox(result, 0.2)
     self.img = img
     self.type = None
     self.N = len(self.result)
     self.res = {}
     self.address()
     self.time()
     self.price()
     self.customer_num()
     print(self.res)
Пример #2
0
 def __init__(self, result):
     self.result = union_rbox(result, 0.2)
     self.N = len(self.result)
     self.res = {}
     self.license_type()
     self.license_no()
     self.full_name()
     self.address()
     self.birthday()
     self.issue_date()
     self.be_class()
     self.valid_period()
Пример #3
0
 def __init__(self, result):
     self.result = union_rbox(result, 0.2)
     self.non_decimal = re.compile(r'[^\d.]+')
     self.non_valid_decimal = re.compile(r'[^\d./]+')
     self.only_letter = re.compile("[^a-z^A-Z^]")
     self.N = len(self.result)
     self.res = {}
     self.bank_name()
     self.card_number()
     self.card_type()
     self.expiry_date()
     self.card_name()
Пример #4
0
 def __init__(self, result):
     self.result = union_rbox(result, 0.2)
     self.N = len(self.result)
     self.res = {'name': '', 'gender': '', 'ethnicity': '', 'birthday': '', 'idNumber': '', 'address': '',
                 'authority': '', 'effectiveDate': '', 'expiryDate': '', 'picUrl': '', 'picName': ''}
     self.full_name()
     self.birthNo()
     self.gender()
     self.ethnicity()
     self.birthday()
     self.address()
     self.authority()
     self.effecttime()
Пример #5
0
 def __init__(self, result):
     # self.result = result
     self.result = union_rbox(result, 0.2)
     self.N = len(self.result)
     self.res = {'invoiceCode': '', 'invoiceNo': '', 'invoiceDate': '', 'invoiceAmount': '', 'buyerName': '', 'buyerTaxNo': '',
                 'sellerName': '', 'sellerTaxNo': '', 'picUrl': '', 'picName': ''}
     self.InvoiceCode()
     self.InvoiceNo()
     self.InvoiceDate()
     self.InvoiceAmount()
     self.BuyerName()
     self.BuyerTaxNo()
     self.SellerName()
     self.SellerTaxNo()
Пример #6
0
 def __init__(self, result):
     self.result = union_rbox(result, 0.2)
     self.N = len(self.result)
     self.res = {}
     self.license_type()
     self.business_id()
     self.business_name()
     self.business_type()
     self.address()
     self.operator()
     self.registered_capital()
     self.register_date()
     self.business_term()
     self.scope()
Пример #7
0
    def getTextList(self, img, angle, result):
        result = union_rbox(result,0.2)
        res = [{'text':x['text'],
                'name':str(i),
                'box':{'cx':x['cx'],
                        'cy':x['cy'],
                        'w':x['w'],
                        'h':x['h'],
                        'angle':x['degree']

                        }
                } for i,x in enumerate(result)]
        res = adjust_box_to_origin(np.copy(img), angle, res)##修正box
        textStrings = ''
        for each in res:
            textStrings += each["text"] + ' '
        return textStrings
Пример #8
0
 def __init__(self, result):
     self.is_vehiclelicense = False
     self.is_vehicleplate = False
     self.result = union_rbox(result, 0.2)
     self.N = len(self.result)
     self.res = {}
     self.license_type()
     self.plate_no()
     self.vehicle_type()
     self.owner()
     self.address()
     self.use_character()
     self.model()
     self.vin()
     self.engine_no()
     self.register_date()
     self.issue_date()
Пример #9
0
def main():
 	billModel = '通用OCR'
 	path = 'test/t3.jpg'
 	img = Image.open(path).convert("RGB")
 	W,H = img.size
 	timeTake = time.time()
 	_,result,angle= model.model(img,
                                    detectAngle=DETECTANGLE,##是否进行文字方向检测
                                    config=dict(MAX_HORIZONTAL_GAP=100,##字符之间的最大间隔,用于文本行的合并
                                    MIN_V_OVERLAPS=0.7,
                                    MIN_SIZE_SIM=0.7,
                                    TEXT_PROPOSALS_MIN_SCORE=0.1,
                                    TEXT_PROPOSALS_NMS_THRESH=0.3,
                                    TEXT_LINE_NMS_THRESH = 0.99,##文本行之间测iou值
                                    MIN_RATIO=1.0,
                                    LINE_MIN_SCORE=0.2,
                                    TEXT_PROPOSALS_WIDTH=0,
                                    MIN_NUM_PROPOSALS=0,                                               
                ),
                                    leftAdjust=True,##对检测的文本行进行向左延伸
                                    rightAdjust=True,##对检测的文本行进行向右延伸
                                    alph=0.2,##对检测的文本行进行向右、左延伸的倍数
                                    ifadjustDegree=False##是否先小角度调整文字倾斜角度
                                   )
    
 	if billModel=='' or billModel=='通用OCR':
            result = union_rbox(result,0.2)
            res = [{'text':x['text'],'name':str(i)} for i,x in enumerate(result)]
 	elif billModel=='火车票':
            res = trainTicket.trainTicket(result)
            res = res.res
            res =[ {'text':res[key],'name':key} for key in res]

 	elif billModel=='身份证':

            res = idcard.idcard(result)
            res = res.res
            res =[ {'text':res[key],'name':key} for key in res]
 	print(result)
Пример #10
0
def find_word(imgpath):
    time.sleep(0.5)
    img = cv2.imread(imgpath)
    _, result, angle = model.model(img,
                                   detectAngle=True,
                                   config=dict(MAX_HORIZONTAL_GAP=50,
                                               MIN_V_OVERLAPS=0.6,
                                               MIN_SIZE_SIM=0.6,
                                               TEXT_PROPOSALS_MIN_SCORE=0.1,
                                               TEXT_PROPOSALS_NMS_THRESH=0.3,
                                               TEXT_LINE_NMS_THRESH=0.7),
                                   leftAdjust=True,
                                   rightAdjust=True,
                                   alph=0.01)
    result = union_rbox(result, 0.2)
    res = [{
        'text': x['text'],
        'name': str(i),
        'box': {
            'cx': x['cx'],
            'cy': x['cy'],
            'w': x['w'],
            'h': x['h'],
            'angle': x['degree']
        }
    } for i, x in enumerate(result)]
    res = adjust_box_to_origin(img, angle, res)  ##修正box
    txtpath = os.path.join('result',
                           imgpath.split('/')[1].split('.')[0] + '.txt')

    print(res)
    with open(txtpath, 'w') as f:
        for n in res:
            str_temp = n['text']
            f.write(str_temp)
            f.write('\n')
        f.close()
    if os.path.exists(imgpath):
        os.remove(imgpath)
Пример #11
0
    def Recognition_invoice(path):
        '''
        识别发票类别
        :param none:
        :return: 发票类别
        '''
        remove_stamp(path, invoice_file_name)
        img1 = './{}/nostamp_{}'.format(temp_dir, invoice_file_name)
        img1 = cv2.imread(img1)
        result_type = OCR(img1)
        result_type = union_rbox(result_type, 0.2)

        print(result_type)

        if len(result_type) > 0:
            N = len(result_type)
            for i in range(N):
                txt = result_type[i]['text'].replace(' ', '')
                txt = txt.replace(' ', '')
                type_1 = re.findall('电子普通', txt)
                type_2 = re.findall('普通发票', txt)
                type_3 = re.findall('专用发票', txt)
                if type_1 is None:
                    type_1 = []
                if type_2 is None:
                    type_2 = []
                if type_3 is None:
                    type_3 = []
            print(type_1)
            print(type_2)
            print(type_3)
            if len(type_1) > 0:
                return 1
            else:
                return 2
        elif len(result_type) == 0:
            return 2
Пример #12
0
    def POST(self):
        t = time.time()
        data = web.data()
        uidJob = uuid.uuid1().__str__()

        data = json.loads(data)
        billModel = data.get('billModel', '')
        textAngle = data.get('textAngle', False)  ##文字检测
        textLine = data.get('textLine', False)  ##只进行单行识别

        imgString = data['imgString'].encode().split(b';base64,')[-1]
        img = base64_to_PIL(imgString)
        if img is not None:
            img = np.array(img)

        H, W = img.shape[:2]

        while time.time() - t <= TIMEOUT:
            if os.path.exists(filelock):
                continue
            else:
                with open(filelock, 'w') as f:
                    f.write(uidJob)

                if textLine:
                    ##单行识别
                    partImg = Image.fromarray(img)
                    text = crnn.predict(partImg.convert('L'))
                    res = [{
                        'text': text,
                        'name': '0',
                        'box': [0, 0, W, 0, W, H, 0, H]
                    }]
                    os.remove(filelock)
                    break

                else:
                    detectAngle = textAngle
                    result, angle = model.model(
                        img,
                        scale=scale,
                        maxScale=maxScale,
                        detectAngle=detectAngle,  ##是否进行文字方向检测,通过web传参控制
                        MAX_HORIZONTAL_GAP=100,  ##字符之间的最大间隔,用于文本行的合并
                        MIN_V_OVERLAPS=0.6,
                        MIN_SIZE_SIM=0.6,
                        TEXT_PROPOSALS_MIN_SCORE=0.1,
                        TEXT_PROPOSALS_NMS_THRESH=0.3,
                        TEXT_LINE_NMS_THRESH=0.99,  ##文本行之间测iou值
                        LINE_MIN_SCORE=0.1,
                        leftAdjustAlph=0.01,  ##对检测的文本行进行向左延伸
                        rightAdjustAlph=0.01,  ##对检测的文本行进行向右延伸
                    )

                    if billModel == '' or billModel == '通用OCR':
                        result = union_rbox(result, 0.2)
                        res = [{
                            'text': x['text'],
                            'name': str(i),
                            'box': {
                                'cx': x['cx'],
                                'cy': x['cy'],
                                'w': x['w'],
                                'h': x['h'],
                                'angle': x['degree']
                            }
                        } for i, x in enumerate(result)]
                        res = adjust_box_to_origin(img, angle, res)  ##修正box

                    elif billModel == '火车票':
                        res = trainTicket.trainTicket(result)
                        res = res.res
                        res = [{
                            'text': res[key],
                            'name': key,
                            'box': {}
                        } for key in res]

                    elif billModel == '身份证':

                        res = idcard.idcard(result)
                        res = res.res
                        res = [{
                            'text': res[key],
                            'name': key,
                            'box': {}
                        } for key in res]

                    os.remove(filelock)
                    break

        timeTake = time.time() - t

        return json.dumps({
            'res': res,
            'timeTake': round(timeTake, 4)
        },
                          ensure_ascii=False)
Пример #13
0
    def POST(self):
        data = web.data()
        data = json.loads(data)
        billModel = data.get('billModel', '')
        textAngle = data.get('textAngle', False)  # 文字检测
        textLine = data.get('textLine', False)  # 只进行单行识别

        imgString = data['imgString'].encode().split(b';base64,')[-1]
        imgString = base64.b64decode(imgString)
        jobid = uuid.uuid1().__str__()
        path = 'test/{}.jpg'.format(jobid)
        with open(path, 'wb') as f:
            f.write(imgString)
        img = cv2.imread(path)  # GBR
        H, W = img.shape[:2]
        timeTake = time.time()

        if textLine:
            # 单行识别
            partImg = Image.fromarray(img)
            text = model.crnnOcr(partImg.convert('L'))
            res = [{
                'text': text,
                'name': '0',
                'box': [0, 0, W, 0, W, H, 0, H]
            }]
        else:
            detectAngle = textAngle  # 是否进行文字方向检测
            _, result, angle = model.model(
                img,
                file_name="test.jpg",
                detectAngle=detectAngle,  # 是否进行文字方向检测,通过web传参控制
                config=dict(
                    MAX_HORIZONTAL_GAP=50,  # 字符之间的最大间隔,用于文本行的合并
                    MIN_V_OVERLAPS=0.6,
                    MIN_SIZE_SIM=0.6,
                    TEXT_PROPOSALS_MIN_SCORE=0.1,
                    TEXT_PROPOSALS_NMS_THRESH=0.3,
                    TEXT_LINE_NMS_THRESH=0.7),  # 文本行之间测iou值
                leftAdjust=True,  # 对检测的文本行进行向左延伸
                rightAdjust=True,  # 对检测的文本行进行向右延伸
                alpha=0.01)  # 对检测的文本行进行向右、左延伸的倍数

            print('[POST] result', result)
            print('[POST] angle', angle)

            if billModel == '' or billModel == '通用OCR':
                result = union_rbox(result, 0.2)
                res = [{
                    'text': x['text'],
                    'name': str(i),
                    'box': {
                        'cx': x['cx'],
                        'cy': x['cy'],
                        'w': x['w'],
                        'h': x['h'],
                        'angle': x['degree']
                    }
                } for i, x in enumerate(result)]
                res = adjust_box_to_origin(img, angle, res)  # 修正box

            elif billModel == '火车票':
                res = trainTicket.trainTicket(result)
                res = res.res
                res = [{
                    'text': res[key],
                    'name': key,
                    'box': {}
                } for key in res]

            elif billModel == '身份证':
                res = idcard.idcard(result)
                res = res.res
                res = [{
                    'text': res[key],
                    'name': key,
                    'box': {}
                } for key in res]

        timeTake = time.time() - timeTake

        os.remove(path)
        return json.dumps({
            'res': res,
            'timeTake': round(timeTake, 4)
        },
                          ensure_ascii=False)
Пример #14
0
def upload():
    t = time.time()
    parser = reqparse.RequestParser()
    parser.add_argument('file')
    args = parser.parse_args()
    # data = request.json
    uidJob = uuid.uuid1().__str__()
    file = args['file']
    # data = json.loads(data)
    billModel = '通用OCR'
    textAngle = True  # 文字检测
    imgString = file.encode().split(b';base64,')[-1]
    img = base64_to_PIL(imgString)
    if img is not None:
        img = np.array(img)
    else:
        return 0

    H, W = img.shape[:2]

    while time.time() - t <= TIMEOUT:
        if os.path.exists(filelock):
            continue
        else:
            with open(filelock, 'w') as f:
                f.write(uidJob)
            detectAngle = textAngle
            result, angle = model.model(img,
                                        scale=scale,
                                        maxScale=maxScale,
                                        detectAngle=detectAngle,  # 是否进行文字方向检测,通过web传参控制
                                        MAX_HORIZONTAL_GAP=100,  # 字符之间的最大间隔,用于文本行的合并
                                        MIN_V_OVERLAPS=0.6,
                                        MIN_SIZE_SIM=0.6,
                                        TEXT_PROPOSALS_MIN_SCORE=0.1,
                                        TEXT_PROPOSALS_NMS_THRESH=0.3,
                                        TEXT_LINE_NMS_THRESH=0.99,  # 文本行之间测iou值
                                        LINE_MIN_SCORE=0.1,
                                        leftAdjustAlph=0.01,  # 对检测的文本行进行向左延伸
                                        rightAdjustAlph=0.01,  # 对检测的文本行进行向右延伸
                                        )

            if billModel == '' or billModel == '通用OCR':
                result = union_rbox(result, 0.2)
                res = {'name': '', 'position': '', 'company': '', 'local': '', 'email': '', 'phone': '',
                       'other': ''}
                # 对公司进行提取
                companyKeyword = ['公司', 'company', '银行', 'Bank', '集团', 'Group', '商行', 'Factory', 'CO', 'LTD']
                for i, x in enumerate(result):
                    for ck in companyKeyword:
                        if ck in x['text']:
                            res['company'] = x['text']
                            result.pop(i)
                            break
                    if res['company']:
                        break
                name = ''
                name_height = 0
                pop_data = 0
                # 对姓名进行处理
                for i, x in enumerate(result):
                    if 'name' in x['text'] or '姓名' in x['text']:
                        res['name'] = x['text'].replace('name', '')
                        res['name'] = res['name'].replace('姓名', '')
                        res['name'] = res['name'].replace(':', '')
                        result.pop(i)
                        break
                    else:
                        # 正则取中文,进行分别进行中文名和英文名的判断
                        text_list = re.findall(r'[\u4e00-\u9fa5]', x['text'])
                        if text_list:
                            if name_height < x['h'] and 1 < len(text_list) < 5:
                                name_height = x['h']
                                name = x['text']
                                pop_data = i
                        else:
                            strUpper = x['text'].upper()
                            if name_height < x['h'] and strUpper != x['text']:
                                name_height = x['h']
                                name = x['text']
                                pop_data = i
                    res['name'] = name
                result.pop(pop_data)
                # 对职位进行提取
                pos = ['GM', 'VP', 'HRD', 'OD', 'MD', 'OM', 'PM', 'BM', 'DM', 'RM', 'AAD', 'ACD', 'AD', 'AE',
                       'AP', 'ASM', 'VC', 'CWO', 'COO', 'CXO', 'CYO', 'CZO', 'PS', 'Manager', 'Engineer']
                posNum = "".join(filter(str.isdigit, x['text']))
                for i, x in enumerate(result[pop_data:pop_data + 3]):
                    if '职位' in x['text'] or 'position' in x['text']:
                        res['position'] = x['text'].replace('职位', '')
                        res['position'] = res['position'].replace('position', '')
                        res['position'] = res['position'].replace(':', '')
                        result.pop(i)
                        break
                if not res['position']:
                    for i, x in enumerate(result[pop_data:pop_data + 3]):
                        for ch in x['text']:
                            if u'\u4e00' <= ch <= u'\u9fff' and len(posNum) == 0:
                                res['position'] = x['text']
                                result.pop(i)
                                break
                        if res['position']:
                            break
                        for p in pos:
                            if p in x['text']:
                                res['position'] = x['text']
                                result.pop(i)
                                break
                        if res['position']:
                            break
                # 对邮箱进行提取
                for i, x in enumerate(result):
                    if '@' in x['text'] or '邮箱' in x['text'] or 'email' in x['text']:
                        res['email'] = x['text'].replace('邮箱', '')
                        res['email'] = res['email'].replace('email', '')
                        res['email'] = res['email'].replace(':', '')
                        result.pop(i)
                        break
                # 对地址进行提取
                localKeyword = ['市', '省', '区', '号', '路', '岛', '地址', 'sheng', 'shi', 'qu', 'hao', 'lu']
                for i, x in enumerate(result):
                    for k in localKeyword:
                        if k in x['text'] or 'Add' in x['text'] or 'add' in x['text']:
                            res['local'] = x['text'].replace('地址', '')
                            res['local'] = res['local'].replace('Add', '')
                            res['local'] = res['local'].replace(':', '')
                            result.pop(i)
                            break
                    if res['local']:
                        break

                # 对手机号码进行提取
                for i, x in enumerate(result):
                    if '-' not in x['text'] and '-' not in x['text']:
                        telephone = "".join(filter(str.isdigit, x['text']))
                        if 11 <= len(telephone) <= 13:
                            res['phone'] += x['text'].replace('电话', '') + ';'
                            res['phone'] = res['phone'].replace('Tel', '')
                            res['phone'] = res['phone'].replace('手机', '')
                            res['phone'] = res['phone'].replace(':', '')
                            result.pop(i)
                # 其他文本提取
                for i, x in enumerate(result):
                    res['other'] += x['text'] + ';'

            elif billModel == '火车票':
                res = trainTicket.trainTicket(result)
                res = res.res
                res = [{'text': res[key], 'name': key, 'box': {}} for key in res]

            elif billModel == '身份证':

                res = idcard.idcard(result)
                res = res.res
                res = [{'text': res[key], 'name': key, 'box': {}} for key in res]

            os.remove(filelock)
            break

    timeTake = time.time() - t
    return jsonify({
        "code": "0000",
        "msg": "成功",
        "data": res
    })
Пример #15
0
    def getWordRecognition(self, img_file, bill_model):
        billModel = bill_model
        textAngle = True  ##文字检测
        textLine = False  ##只进行单行识别

        img = cv2.imread(img_file)  ##GBR
        H, W = img.shape[:2]
        timeTake = time.time()
        if textLine:
            ##单行识别
            partImg = Image.fromarray(img)
            text = model.crnnOcr(partImg.convert('L'))
            res = [{
                'text': text,
                'name': '0',
                'box': [0, 0, W, 0, W, H, 0, H]
            }]
        else:
            detectAngle = textAngle
            _, result, angle = model(
                img,
                detectAngle=detectAngle,  ##是否进行文字方向检测,通过web传参控制
                config=dict(
                    MAX_HORIZONTAL_GAP=50,  ##字符之间的最大间隔,用于文本行的合并
                    MIN_V_OVERLAPS=0.6,
                    MIN_SIZE_SIM=0.6,
                    TEXT_PROPOSALS_MIN_SCORE=0.1,
                    TEXT_PROPOSALS_NMS_THRESH=0.3,
                    TEXT_LINE_NMS_THRESH=0.7,  ##文本行之间测iou值
                ),
                leftAdjust=True,  ##对检测的文本行进行向左延伸
                rightAdjust=True,  ##对检测的文本行进行向右延伸
                alph=0.01,  ##对检测的文本行进行向右、左延伸的倍数
            )

            if billModel == '' or billModel == '通用OCR':
                result = union_rbox(result, 0.2)
                res = [{
                    'text': x['text'],
                    'name': str(i),
                    'box': {
                        'cx': x['cx'],
                        'cy': x['cy'],
                        'w': x['w'],
                        'h': x['h'],
                        'angle': x['degree']
                    }
                } for i, x in enumerate(result)]
                res = adjust_box_to_origin(img, angle, res)  ##修正box

            elif billModel == '身份证':

                res = idcard.idcard(result)
                res = res.res
                res = [{
                    'text': res[key],
                    'name': key,
                    'box': {}
                } for key in res]

            elif billModel == '驾驶证':

                res = drivinglicense.drivinglicense(result)
                res = res.res
                res = [{
                    'text': res[key],
                    'name': key,
                    'box': {}
                } for key in res]

            elif billModel == '行驶证':

                res = vehiclelicense.vehiclelicense(result)
                res = res.res
                res = [{
                    'text': res[key],
                    'name': key,
                    'box': {}
                } for key in res]

            elif billModel == '银行卡':
                res = bankcard.bankcard(result)
                res = res.res
                res = [{
                    'text': res[key],
                    'name': key,
                    'box': {}
                } for key in res]

            elif billModel == '手写体':
                result = union_rbox(result, 0.2)
                res = [{
                    'text': x['text'],
                    'name': str(i),
                    'box': {
                        'cx': x['cx'],
                        'cy': x['cy'],
                        'w': x['w'],
                        'h': x['h'],
                        'angle': x['degree']
                    }
                } for i, x in enumerate(result)]
                res = adjust_box_to_origin(img, angle, res)  ##修正box

            elif billModel == '车牌':
                res = vehicleplate.vehicleplate(result)
                res = res.res
                res = [{
                    'text': res[key],
                    'name': key,
                    'box': {}
                } for key in res]

        timeTake = time.time() - timeTake

        return {'res': res, 'timeTake': round(timeTake, 4)}
Пример #16
0
    def getWordRecognition(self, img_file, bill_model):
        billModel = bill_model
        textAngle = True ##文字检测
        textLine = False ##只进行单行识别
        text = ''

        file_name = os.path.basename(img_file)
        file_path = os.path.dirname(img_file)

        # img = cv2.imread(img_file)##GBR
        img,is_exif,H,W = self.setExif(img_file)
        if is_exif is True:
            textAngle = False

        # H,W = img.shape[:2]
        timeTake = time.time()
        if textLine:
            ##单行识别
            partImg = Image.fromarray(img)
            text = model.crnnOcr(partImg.convert('L'))
            res =[ {'text':text,'name':'0','box':[0,0,W,0,W,H,0,H]} ]
        else:
            detectAngle = textAngle
            _,result,angle= model(img,
                                        detectAngle=detectAngle,##是否进行文字方向检测,通过web传参控制
                                        config=dict(MAX_HORIZONTAL_GAP=50,##字符之间的最大间隔,用于文本行的合并
                                        MIN_V_OVERLAPS=0.6,
                                        MIN_SIZE_SIM=0.6,
                                        TEXT_PROPOSALS_MIN_SCORE=0.1,
                                        TEXT_PROPOSALS_NMS_THRESH=0.3,
                                        TEXT_LINE_NMS_THRESH = 0.7,##文本行之间测iou值
                                                ),
                                        leftAdjust=True,##对检测的文本行进行向左延伸
                                        rightAdjust=True,##对检测的文本行进行向右延伸
                                        alph=0.01,##对检测的文本行进行向右、左延伸的倍数
                                       )



            if billModel=='' or billModel=='通用OCR' :
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']

                              }
                       } for i,x in enumerate(result)]
                res = adjust_box_to_origin(np.copy(img),angle, res)##修正box
                com_res = res

            elif billModel=='身份证':

                res = idcard.idcard(result)
                res = res.res
                res =[ {'text':res[key],'name':key,'box':{}} for key in res]
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                com_res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']
                              }
                       } for i,x in enumerate(result)]
                com_res = adjust_box_to_origin(np.copy(img),angle, com_res)##修正box
            
            elif billModel=='驾驶证':

                res = drivinglicense.drivinglicense(result)
                res = res.res
                res =[ {'text':res[key],'name':key,'box':{}} for key in res]
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                com_res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']
                              }
                       } for i,x in enumerate(result)]
                com_res = adjust_box_to_origin(np.copy(img),angle, com_res)##修正box

            elif billModel=='行驶证':

                res = vehiclelicense.vehiclelicense(result)
                res = res.res
                res =[ {'text':res[key],'name':key,'box':{}} for key in res]
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                com_res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']
                              }
                       } for i,x in enumerate(result)]
                com_res = adjust_box_to_origin(np.copy(img),angle, com_res)##修正box

            elif billModel=='营业执照':

                res = businesslicense.businesslicense(result)
                res = res.res
                res =[ {'text':res[key],'name':key,'box':{}} for key in res]
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                com_res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']
                              }
                       } for i,x in enumerate(result)]
                com_res = adjust_box_to_origin(np.copy(img),angle, com_res)##修正box
        
            elif billModel=='银行卡':
                res = bankcard.bankcard(result)
                res = res.res
                res =[ {'text':res[key],'name':key,'box':{}} for key in res]
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                com_res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']
                              }
                       } for i,x in enumerate(result)]
                com_res = adjust_box_to_origin(np.copy(img),angle, com_res)##修正box

            elif billModel=='手写体':
                result = union_rbox(result,0.2)
                res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']

                              }
                       } for i,x in enumerate(result)]
                res = adjust_box_to_origin(np.copy(img),angle, res)##修正box
                text = self.getTextList(img,angle, result)

            elif billModel=='车牌':
                res = vehicleplate.vehicleplate(result)
                res = res.res
                res =[ {'text':res[key],'name':key,'box':{}} for key in res]
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                com_res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']
                              }
                       } for i,x in enumerate(result)]
                com_res = adjust_box_to_origin(np.copy(img),angle, com_res)##修正box
            
            elif billModel=='名片':
                res = businesscard.businesscard(result)
                res = res.res
                res =[ {'text':res[key],'name':key,'box':{}} for key in res]
                text = self.getTextList(img,angle, result)
                result = union_rbox(result,0.2)
                com_res = [{'text':x['text'],
                        'name':str(i),
                        'box':{'cx':x['cx'],
                               'cy':x['cy'],
                               'w':x['w'],
                               'h':x['h'],
                               'angle':x['degree']
                              }
                       } for i,x in enumerate(result)]
                com_res = adjust_box_to_origin(np.copy(img),angle, com_res)##修正box
            
        
        timeTake = time.time()-timeTake

        #draw box in to original image
        drawBoxes = []
        draw_filename = file_name.split('.')[0] + '_drawed.' + file_name.split('.')[1]
        drawPath = os.path.join(file_path,draw_filename)
        drawUrl = settings.FILE_URL +  settings.MEDIA_URL + 'photos' + '/' + draw_filename
        # img =  cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        if len(com_res) > 0:
            for arr in com_res:
               drawBoxes.append(arr["box"])
            drawImg = draw_boxes(np.array(img),drawBoxes)
            cv2.imwrite(drawPath, drawImg)

        return {'res':res,'timeTake':round(timeTake,4), 'text':text, 'com_res': com_res, 'drawUrl': drawUrl}
Пример #17
0
 def __init__(self, result):
     self.result = union_rbox(result, 0.2)
     self.N = len(self.result)
     self.res = {}
     self.plate_no()