- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个flask应用程序,该应用程序用于将用户输入作为图像并运行模型并将其保存在文件夹中,它最初会获取单个图像并运行该应用程序。但是我希望我的应用程序拍摄多个图像,在这些图像上运行模型,然后将其保存到文件夹中。
在这个StackOverflow问题上找到了所有答案:Uploading multiple files with Flask,没有一个适合我的用例。
请帮助我阐明我要去哪里。
这是我的 flask 文件
from flask import Flask, render_template, url_for, session, redirect, request
from image_initial import Image_tensorflow
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mykeyhere'
@app.route('/', methods =['GET', 'POST'])
def test():
if "file_urls" not in session:
session['file_urls'] = []
file_urls = session['file_urls']
if(request.method == 'POST'):
file_obj = request.form['username']
session['file_urls'] = file_obj
return redirect(url_for('results'))
return render_template("test.html")
@app.route('/results')
def results():
if "file_urls" not in session or session['file_urls'] == []:
print('session is not created')
return redirect(url_for('test'))
file_urls = session['file_urls']
Image_tensorflow(file_urls,file_urls)
session.pop('file_urls', None)
#print(request.form)
return render_template('results.html', file_urls=file_urls)
if __name__ == "__main__":
app.run(host='0.0.0.0')
<form action = "" method = "POST">
<p>Upload your file here.</p>
<p>
<input type='file' name='username' multiple='multiple' class="btn btn-primary"/>
</p>
<p>
<input type='submit' value='Upload' class="btn btn-secondary"/>
</p>
import numpy as np
import os
import sys
import tensorflow as tf
import json
from PIL import Image
sys.path.append("..")
from object_detection.utils import ops as utils_ops
from utils import label_map_util
from utils import visualization_utils as vis_util
def Image_tensorflow(xa,ya):
PATH_TO_FROZEN_GRAPH = 'frozen_inference_graph.pb'
PATH_TO_LABELS = 'object-detection.pbtxt'
NUM_CLASSES = 4
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
use_display_name=True)
category_index = label_map_util.create_category_index(categories)
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
def image_url(xa, ya):
file_path = 'images/'
file_name = ya
image = xa
f = open((file_path + str(file_name) + ".json"), "w")
f.close
return_dict = {'image': image, 'file': f};
return return_dict
get_image_data = image_url(xa,ya)
image_path= get_image_data['image']
IMAGE_SIZE = (12, 8)
def run_inference_for_single_image(image, graph):
with graph.as_default():
with tf.Session() as sess:
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in [
'num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks'
]:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
tensor_name)
if 'detection_masks' in tensor_dict:
# The following processing is only for single image
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
tensor_dict['detection_masks'] = tf.expand_dims(
detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
output_dict = sess.run(tensor_dict,
feed_dict={image_tensor: np.expand_dims(image, 0)})
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict[
'detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
return output_dict
for img in xa:
image = Image.open(img)
image_np = load_image_into_numpy_array(image)
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
output_dict = run_inference_for_single_image(image_np, detection_graph)
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True,
line_thickness=8)
# get_image_data = image_url(sys.argv[1],sys.argv[2])
# image_file = get_image_data['image']
# pass values
import cv2 as cv
image_file = image_path
img = cv.imread('image_file')
i = 0
j = 0
limiter = 0.3
while (i < 100):
if (output_dict['detection_scores'][i] > limiter):
j = j + 1
i = i + 1
# In[17]:
# store the pass values in lists
i = 0
detection_classes = []
detection_boxes = [[]] * j
detection_scores = []
while (i < j):
detection_classes.append(output_dict['detection_classes'][i])
detection_scores.append(output_dict['detection_scores'][i])
detection_boxes[i].append(output_dict['detection_boxes'][i])
i = i + 1
list1 = []
for items in detection_classes:
if items == 1:
list1.append("Angry")
elif items == 2:
list1.append("Sad")
elif items == 3:
list1.append("Neutral")
elif items == 4:
list1.append("Happy")
final_dict = {'DETECTION': list1}
file_to_write_to = get_image_data['file'].name
file_to_write_to = str(file_to_write_to)
text_file = open(file_to_write_to, "w")
text_file.write(json.dumps(final_dict))
text_file.close()
final_path = "images/" + str(ya) + "_annotated" + ".jpg"
# draw bounding boxes
img = cv.imread('xa')
i = 0
for item in detection_classes:
width, height = image.size
ymin = int(detection_boxes[0][i][0] * height)
xmin = int(detection_boxes[0][i][1] * width)
ymax = int(detection_boxes[0][i][2] * height)
xmax = int(detection_boxes[0][i][3] * width)
font = cv.FONT_HERSHEY_SIMPLEX
panel_colour = (182, 182, 42)
bumper_colour = (241, 239, 236)
damage_colour = (0, 255, 0)
text_colour = (255, 255, 255)
bumper_text = (0, 0, 0)
buffer = int(5 * width / 1000)
if (detection_classes[i] == 1):
img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
cv.putText(img, 'angry', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
int(2 * (height / 400)), cv.LINE_AA)
elif (detection_classes[i] == 2):
img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
cv.putText(img, 'sad', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
int(2 * (height / 400)), cv.LINE_AA)
elif (detection_classes[i] == 3):
img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), bumper_colour, int(2 * (height / 600)))
cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), bumper_colour, -1)
cv.putText(img, 'neutral', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), bumper_text,
int(2 * (height / 400)), cv.LINE_AA)
elif (detection_classes[i] == 4):
img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
cv.putText(img, 'happy', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
int(2 * (height / 400)), cv.LINE_AA)
i = i + 1
final_path = "/home/mayureshk/PycharmProjects/ImageDetection/venv/models/research/object_detection/images/" + str(ya) + "_annotated" + ".jpg"
cv.imwrite(final_path, img)
Traceback (most recent call last):
File "/home/mayureshk/PycharmProjects/ImageDetection/venv/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/home/mayureshk/PycharmProjects/ImageDetection/venv/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/mayureshk/PycharmProjects/ImageDetection/venv/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/mayureshk/PycharmProjects/ImageDetection/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/mayureshk/PycharmProjects/ImageDetection/venv/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/mayureshk/PycharmProjects/ImageDetection/venv/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "mayuresh.py", line 25, in results
Image_tensorflow(file_urls,file_urls)
File "/home/mayureshk/PycharmProjects/ImageDetection/venv/models/research/object_detection/image_initial.py", line 209, in Image_tensorflow
cv.imwrite(final_path, img)
cv2.error: OpenCV(4.2.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'
最佳答案
您没有得到文件列表,这就是为什么您没有得到多个文件的原因。您需要使用来自用户名输入的表单访问文件列表。
from flask import Flask, render_template, url_for, session, redirect, request
from image_initial import Image_tensorflow
app = Flask(__name__, template_folder='templates')
app.config['SECRET_KEY'] = 'mykeyhere'
@app.route('/', methods=['GET', 'POST'])
def test():
if "file_urls" not in session:
session['file_urls'] = []
file_urls = session['file_urls']
if request.method == 'POST':
file_obj = request.form.getlist("username")
session['file_urls'] = file_obj
return redirect(url_for('results'))
return render_template("test.html")
@app.route('/results')
def results():
if "file_urls" not in session or session['file_urls'] == []:
print('session is not created')
return redirect(url_for('test'))
file_urls = session['file_urls']
Image_tensorflow(file_urls, file_urls)
session.pop('file_urls', None)
return render_template('results.html', file_urls=file_urls)
if __name__ == "__main__":
app.run(host='0.0.0.0')
Image.open(xa)
这里的xa是图像列表,而
Image.open()
并不希望有一个列表,您可以遍历每个图像并将其打开。
for img in xa:
Image.open(img)
关于python - 如何在Flask中上传多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60182030/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!