Как получить имя файла изображения и отправить его в процесс извлечения объектов в колбе? - PullRequest
0 голосов
/ 06 октября 2019

У меня есть программа для поиска изображений на python, я хочу создать веб-программу с использованием колбы. Но я не понимаю, как получить входные изображения из колбы. Таким образом, я могу обработать входное изображение в моей программе поиска изображений, а затем показать результат на моей странице колбы.

здесь мой код колбы:

import os
from flask import Flask, flash, request, redirect, url_for, send_from_directory, Request, render_template
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'res/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024

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

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return render_template('home.html')

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

app.run(host='0.0.0.0', port= 81)

, и это является частью моей программы поиска изображенийМне нужно входное изображение из колбы, чтобы заполнить 'inputImage.jpg' на моем queryPath:

from PIL import Image

# Define path of testing data and indexing file
queryPath = root_path + 'inputImage.jpg'
index_file = root_path + 'mtcd.csv'

# define the bins for quantization
colorBins = 64
R_Bins = 4
G_Bins = 4
B_Bins = 4
edgeBins = 18

query = cv2.imread(queryPath)

# Color Quantization
colorQuant = combineColorQuantization(query, B_Bins, G_Bins, R_Bins)

# Edge Quantization
edgeQuant = edgeQuantization(query, edgeBins)

# Texton Search
features = textonSearch(colorQuant, colorBins, edgeQuant, edgeBins)

# GLCM
glcm, en = GLCM(query)

features.extend(glcm[0])
features.extend(glcm[1])
features.extend(glcm[2])
features.extend(en)

# perform the search
searcher = Searcher(index_file)
results = searcher.search(features)

# display the query
fig = figure(figsize=(5,5))
title('Query Image')
imshow(array(Image.open(queryPath)))
axis('off')

# loop over the results
fig = figure(num=None, figsize=(20,5))
title('Result Image')
result = []
i = 1
for (score, resultID) in results:
    # load the result image and display it
    a = fig.add_subplot(2, 6, i)
    image = imread(root_path + 'batik/'+resultID)
    i += 1
    imshow(image)
    axis('off')
print(result)

1 Ответ

0 голосов
/ 07 октября 2019

Вы можете определить код обработки изображения как отдельную функцию, подобную этой

def process_file(path)
    # Define path of testing data and indexing file
    queryPath = path
    index_file = root_path + 'mtcd.csv'

    # define the bins for quantization
    colorBins = 64
    R_Bins = 4
    G_Bins = 4
    B_Bins = 4
    edgeBins = 18

    query = cv2.imread(queryPath)

    # Color Quantization
    colorQuant = combineColorQuantization(query, B_Bins, G_Bins, R_Bins)

    # Edge Quantization
    edgeQuant = edgeQuantization(query, edgeBins)

    # Texton Search
    features = textonSearch(colorQuant, colorBins, edgeQuant, edgeBins)

    # GLCM
    glcm, en = GLCM(query)

    features.extend(glcm[0])
    features.extend(glcm[1])
    features.extend(glcm[2])
    features.extend(en)

    # perform the search
    searcher = Searcher(index_file)
    results = searcher.search(features)

    # display the query
    fig = figure(figsize=(5,5))
    title('Query Image')
    imshow(array(Image.open(queryPath)))
    axis('off')

    # loop over the results
    fig = figure(num=None, figsize=(20,5))
    title('Result Image')
    result = []
    i = 1
    for (score, resultID) in results:
        # load the result image and display it
        a = fig.add_subplot(2, 6, i)
        image = imread(root_path + 'batik/'+resultID)
        i += 1
        imshow(image)
        axis('off')
    print(result)

, вызвав метод process_file () из блока кода маршрута фляги

  def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return render_template('home.html')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...