我创建了一个允许用户上传图片的电子商务网站。我希望通过 python 代码分析上传的图像,以便为图像中的对象生成关键字。该网站是使用 PHP 构建的,但我无法将分析图像的 Python 代码集成到 PHP 代码中并且 PHP 代码在本地主机 8080 上运行,而 Python 代码在端口 127.0.0.1.5000 上运行。
为了运行 PHP 代码,我安装了一些包,它们是 -
1。 pip 安装烧瓶
2。 pip 安装 numpy
3。 pip 安装 tensorflow
4。 pip 安装 keras
5。 pip 安装枕头
Python代码-
import os
from flask import Flask, render_template, request
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from keras.applications.resnet_v2 import preprocess_input as resnet152v2_preprocess_input
from keras.applications.resnet_v2 import ResNet152V2
from keras.applications.imagenet_utils import decode_predictions
model = ResNet152V2(weights='imagenet')
class_dict = {
'notebook': 'laptop',
'cellular_telephone': 'Smartphone',
'hand-held_computer': 'Smartphone',
'remote_control': 'Smartphone',
'iPod': 'Smartphone',
'microphone': 'Headphone',
'espresso_maker': 'Headphone',
'washer': 'Washing Machine',
'analog_clock': 'Watch',
'digital_watch': 'Watch',
'reflex_camera': 'Camera',
'vending_machine': 'Fridge',
'pill_bottle': 'Water Bottle',
'water_bottle': 'Water Bottle',
'ashcan': 'Fridge'
}
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS
def allowed_file(filename):
"""Function to check if the file extension is allowed"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == "POST":
if 'file' not in request.files:
return render_template('search_page.php', message='No file selected')
file = request.files['file']
if not allowed_file(file.filename):
return render_template('search_page.php', message='File type not allowed')
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
img = load_img(img_path, target_size=(224, 224))
img = img_to_array(img)
img = np.expand_dims(img, axis=0)
img = resnet152v2_preprocess_input(img)
preds = model.predict(img)
decoded_preds = decode_predictions(preds, top=1)[0]
for pred in decoded_preds:
pred = (pred[0], class_dict.get(pred[1], pred[1]), pred[2])
message = 'Predicted: {} with probability {}'.format(pred[1], pred[2])
return render_template('search_page.php', message=message, filename=filename)
return render_template('search_page.php')
@app.route('/view/<filename>')
def view_image(filename):
"""Function to display an uploaded image"""
return '<img src="/uploads/{}">'.format(filename)
if __name__ == '__main__':
app.run(debug=True, port=8080)
Php Code -
<?php
include 'components/connect.php';
session_start();
if(isset($_SESSION['user_id'])){
$user_id = $_SESSION['user_id'];
}else{
$user_id = '';
};
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>search page</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php include 'components/user_header.php'; ?>
<section class="search-form">
<form action="" method="post">
<input type="text" name="search_box" placeholder="search here..." maxlength="100" class="box" required>
<button type="submit" class="fas fa-search" name="search_btn"></button>
</form>
</section>
<section class="search-form">
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<br><br>
<button type="button" onclick="previewImage()">View</button>
<br><br>
<img src="" id="imgPreview" style="display:none;max-width:300px;max-height:300px;">
<br><br>
</form>
<input type="submit" value="Upload">
<script type="text/javascript">
function previewImage() {
var preview = document.getElementById("imgPreview");
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
preview.style.display = "block";
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
preview.style.display = "none";
}
}
</script>
</section>
</section>
<section class="products" style="padding-top: 0; min-height:100vh;">
<div class="box-container">
<?php
if(isset($_POST['search_box']) OR isset($_POST['search_btn'])){
$search_box = $_POST['search_box'];
$select_products = $conn->prepare("SELECT * FROM `products` WHERE name LIKE '%{$search_box}%'");
$select_products->execute();
if($select_products->rowCount() > 0){
while($fetch_product = $select_products->fetch(PDO::FETCH_ASSOC)){
?>
<form action="" method="post" class="box">
<input type="hidden" name="pid" value="<?= $fetch_product['id']; ?>">
<input type="hidden" name="name" value="<?= $fetch_product['name']; ?>">
<input type="hidden" name="price" value="<?= $fetch_product['price']; ?>">
<input type="hidden" name="image" value="<?= $fetch_product['image_01']; ?>">
<a href="quick_view.php?pid=<?= $fetch_product['id']; ?>" class="fas fa-eye"></a>
<img src="uploaded_img/<?= $fetch_product['image_01']; ?>" alt="">
<div class="name"><?= $fetch_product['name']; ?></div>
<div class="flex">
<div class="price"><span>Rs. </span><?= $fetch_product['price']; ?><span>/-</span></div>
<input type="number" name="qty" class="qty" min="1" max="99" onkeypress="if(this.value.length == 2) return false;" value="1">
</div>
<input type="submit" value="add to cart" class="btn" name="add_to_cart">
</form>
<?php
}
}else{
echo '<p class="empty">no products found!</p>';
}
}
?>
</div>
</section>
<?php include 'components/footer.php'; ?>
<script src="js/script.js"></script>
</body>
</html>
虽然可以在 PHP 中运行 Python,但由于潜在的安全风险和性能问题,不建议这样做。相反,最好使用简单的队列系统在两种语言之间进行通信,尤其是在处理用户上传的文件(如图像)时。
假设你有一个数据库,比如 SQLite 或 PostgreSQL,你可以创建一个表来存储有关需要处理的图像的信息。该表可能包含以下列:
id, imagePath, status, isProcessed, createdAt, updatedAt
1,/home/user/project/storage/img/sample.jpg,pending,false,2023-04-01,2023-04-01
接下来,使用您的 Python 脚本,您可以每 5 分钟运行一次,以检查表中是否有处于“待处理”状态的新条目。然后,该脚本可以使用 Python 库执行必要的图像分析。处理图像后,脚本应更新表,根据结果将状态设置为“已完成”或“出错”,并将 isProcessed 标志设置为“真”。
与此同时,您的 PHP 应用程序可以定期检查表格以查看图像的状态是否已更新为“已完成”。如果是这样,它可以检索图像分析的结果并将它们显示给用户或根据需要执行任何进一步的操作。这需要你改变你的用户的工作流程 需要向他们展示“您的文件已上传,我们会在处理完您的图片后通知您”
有了这个,您可以在您的应用程序中有效地集成 Python 和 PHP。