如何在localhost和ibm云上的Flask中处理图像时设置路径

问题描述 投票:0回答:1

这个应用程序运行良好,直到昨天,但今天它不工作。后端或前端未进行任何更改。该网站Output is like this。我正在尝试使用open cv从已上传到../static/uploads文件夹中的图像中提取4个子图像。而提取的4个图像存储在../static/extracted文件夹中。现在我担心的是,昨天代码正在运行,但今天它无法运行。在部署到ibm云时,我找不到开放的简历。 “未找到cv2模块”。有人可以帮我改进这段代码。

app.py代码:

from cloudant import Cloudant
from flask import Flask, render_template, request, jsonify
import atexit
import os
import json
from ocr_core import ocr_core


UPLOAD_FOLDER = '/static/uploads/'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__,static_url_path='')

db_name = 'mydb'
client = None
db = None

if 'VCAP_SERVICES' in os.environ:
    vcap = json.loads(os.getenv('VCAP_SERVICES'))
    print('Found VCAP_SERVICES')
    if 'cloudantNoSQLDB' in vcap:
        creds = vcap['cloudantNoSQLDB'][0]['credentials']
        user = creds['username']
        password = creds['password']
        url = 'https://' + creds['host']
        client = Cloudant(user, password, url=url, connect=True)
        db = client.create_database(db_name, throw_on_exists=False)
elif "CLOUDANT_URL" in os.environ:
    client = Cloudant(os.environ['CLOUDANT_USERNAME'], os.environ['CLOUDANT_PASSWORD'], url=os.environ['CLOUDANT_URL'], connect=True)
    db = client.create_database(db_name, throw_on_exists=False)
elif os.path.isfile('vcap-local.json'):
    with open('vcap-local.json') as f:
        vcap = json.load(f)
        print('Found local VCAP_SERVICES')
        creds = vcap['services']['cloudantNoSQLDB'][0]['credentials']
        user = creds['username']
        password = creds['password']
        url = 'https://' + creds['host']
        client = Cloudant(user, password, url=url, connect=True)
        db = client.create_database(db_name, throw_on_exists=False)

# On IBM Cloud Cloud Foundry, get the port number from the environment variable PORT
# When running this app on the local machine, default the port to 8000
port = int(os.getenv('PORT', 5000))


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


@app.route('/')
def home_page():
    return render_template('index.html')


@app.route('/upload', methods=['GET', 'POST'])
def upload_page():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return render_template('upload.html', msg='No file selected')
        file = request.files['file']
        if file.filename == '':
            return render_template('upload.html', msg='No file selected')

        if file and allowed_file(file.filename):
            file.save(os.path.join(os.getcwd() + UPLOAD_FOLDER, file.filename))
            extracted_text = ocr_core(file)
            return render_template('upload.html',
                                   msg='Successfully processed',
                                   extracted_text=extracted_text,
                                   img_src=UPLOAD_FOLDER + file.filename)
    elif request.method == 'GET':
        return render_template('upload.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port, debug=True)

OCR_朋友.朋友:

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import cv2
from random import randint
import pandas as pd

#UPLOAD_FOLDER = '/static'
def ocr_core(filename):
    #text = pytesseract.image_to_string(Image.open(filename)) 
    val=str(filename)
    val=list(val)
    naam=""
    tt=0
    for i in range(15,len(val)):
            if(val[i]!="'"):
                naam+=val[i]
                if(val[i]=='g'):
                    tt=1
            if(tt==1):
                break
    image = cv2.imread("/home/sahil/CheckCheque-deploy/static/uploads/" +str(naam))
    k=randint(0, 999999) 
    cropped1 = image[290:500, 320:1540]
    cv2.imwrite("/home/sahil/CheckCheque-deploy/static/extracted/name"+str(k)+".png", cropped1)
    name=pytesseract.image_to_string(Image.open("/home/sahil/CheckCheque-deploy/static/extracted/name"+str(k)+".png"))
    cropped2 = image[470:700, 670:2640]
    cv2.imwrite("/home/sahil/CheckCheque-deploy/static/extracted/amount"+str(k)+".png", cropped2)
    amount=pytesseract.image_to_string(Image.open("/home/sahil/CheckCheque-deploy/static/extracted/amount"+str(k)+".png"))
    cropped3 = image[850:1000, 480:1040]
    cv2.imwrite("/home/sahil/CheckCheque-deploy/static/extracted/acc_no"+str(k)+".png", cropped3)
    acc_no=pytesseract.image_to_string(Image.open("/home/sahil/CheckCheque-deploy/static/extracted/acc_no"+str(k)+".png"))
    cropped5 = image[500:850, 2940:4500]
    cv2.imwrite("/home/sahil/CheckCheque-deploy/static/extracted/amt_num"+str(k)+".png", cropped5)
    amt_num=pytesseract.image_to_string(Image.open("/home/sahil/CheckCheque-deploy/static/extracted/amt_num"+str(k)+".png"))
    acc_no1=""
    lnum=["1","0","2","3","4","5","6","7","8","9"]
    for i in range(0,len(acc_no)):
        if(str(acc_no[i]) in lnum):
            acc_no1+=acc_no[i]
    l=[name,acc_no,amt_num]
    df = pd.read_csv("/home/sahil/CheckCheque-deploy/jobchahiye.csv")
    df.loc[df.Account== int(l[1]), 'Amount'] -=int(l[2])
    df.loc[df.Name== str(l[0]), 'Amount'] +=int(l[2])
    df.to_csv("/home/sahil/CheckCheque-deploy/jobchahiye.csv", index=False) 
    return l
python-3.x opencv flask ibm-cloud cloudant
1个回答
0
投票

看起来你依赖于opencv-pythonopencv-contrib-python。因此,它需要作为您要运行应用程序的任何计算机上的先决条件安装。

在localhost上你使用pip执行此操作,但是如果你没有运行像virtualenv这样的东西,那么所有安装都将进入全局空间,并且很容易出现冲突,导致你无法运行任何东西。

对于云部署,您可以在requirements.txt文件中指定pip先决条件

© www.soinside.com 2019 - 2024. All rights reserved.