python-3.x - 如何在 localhost 和 ibm cloud 上的 Flask 中处理图像时设置路径
问题描述
该应用程序运行良好,直到昨天,但今天它不工作。后端或前端未进行任何更改。站点输出是这样的。我正在尝试使用 open cv 从已上传到 ../static/uploads 文件夹的图像中提取 4 个子图像。提取的 4 张图像存储在 ../static/extracted 文件夹中。现在我担心的是,昨天代码正在运行,但今天它不起作用。在部署到 ibm 云时,我找不到打开的 cv。“找不到 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_py.py:
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
解决方案
看起来您依赖于opencv-python
或opencv-contrib-python
。因此,它需要作为先决条件安装在要运行应用程序的任何机器上。
在 localhost 上pip
,您virtualenv
可以使用 .
对于云部署,您在requirements.txt
文件中指定 pip 先决条件
推荐阅读
- rest - Showing data from REST API
- sprite-kit - SpriteKit 中的液体飞溅
- python - 比较列中相同值的行并生成矩阵
- php - $_SERVER["REQUEST_URI"] htaccess 重定向后随机为空
- ruby-on-rails - Rails 5 使用 :id 向 REST 路由添加自定义操作
- javascript - HTML5
- javascript - nodejs和Chrome中setTimeout的不同行为
- c - 将二进制数据解释为浮点数
- analytics - Weka - loading an arff file, keep getting error @relation expected, but the format is correct
- bash - How to write Vault LDAP Auth Configuration from a json config file?