doulan7166 2017-01-05 08:31
浏览 61
已采纳

来自PHP的Python脚本

I am running a Python script from a PHP file. For a very a simple example, it works perfectly. Here is the Python script:

#!/usr/bin/env python

def test():
    x = 2 + 1
    print x + 4
    return x

print test()

And PHP script:

<?php
    $command = escapeshellcmd('/usr/bin/python2.7 /home/super/PycharmProjects/img_plus_text/helloworld.py');
    $output = shell_exec($command);
    echo $output;
    echo "Finishing....!";
?> 

Unfortunately, for more complicated script, It does not work. Here is the Python script

#!/usr/bin/env python

import numpy as np
import os
import random

import caffe
import cv2
from sklearn.externals import joblib

import create_dataset_final_mlp
import text_2_bow




def create_class_mapping():
    with open("text_processing/encoded-classes.txt") as class_file:
        lines = class_file.readlines()
        dictionary = {}
        for item in lines:
            item = item.split(" ")
            dictionary[item[0]] = item[1].replace("
", "").replace("@", "")
        return dictionary


def get_top5(probability_list):
    result = []
    probabilities = []
    for i in range(0, 5):
        top = probability_list.index(max(probability_list))
        probabilities.insert(i, probability_list[top])
        probability_list[top] = -1
        result.insert(i, top)
    return result, probabilities


def select_random_file(base_dir):
    # Select random category
    file_chosen = random.choice(os.listdir(base_dir))
    # Select random file in that category
    file_chosen = random.choice(os.listdir(base_dir + "/" + file_chosen))
    return file_chosen


def get_top5_class_name(mapping, top5_list):
    class_name_list = []
    for i in range(0, 5):
        index = top5_list[i]
        class_name = mapping[str(index)]
        class_name_list.insert(i, class_name)
    return class_name_list


def main(image_to_classify):
    dataset_path = "/images-test1"
    image_file_chosen = create_dataset_final_mlp.find(image_to_classify, dataset_path)

    if image_file_chosen is None:
        image_file_chosen = select_random_file("%s" % dataset_path)

    identifier = image_file_chosen.split(".")[0]
    print "Identifier: " + identifier

    dictionary = text_2_bow.create_dictionary("text_processing/dictionary-1000-words.csv")

    #   load CNN model from disk
    classifier = create_dataset_final_mlp.load_model_from_disk("test/deploy.prototxt",
                                                               "test/snapshot_iter_1020.caffemodel", '256,256',
                                                               "test/converted_mean.npy")

    #   load the final MLP to classify patterns
    print "loading model from disk..."
    mlp = joblib.load("trained_model_9097_5000_3000_iter_100.model")

    with open("export-ferramenta.csv") as export_file:
        for line in export_file:
            if identifier in line:
                pattern = line
                print "Pattern: " + pattern
                break

    # Show selected image
    full_img_path = create_dataset_final_mlp.find(image_file_chosen, dataset_path)
    # img = cv2.imread(full_img_path, cv2.IMREAD_COLOR)
    # cv2.imshow("Image selected", img)
    # cv2.waitKey(0)

    #   get the CNN features
    inputs = [caffe.io.load_image(full_img_path)]
    # the second parameter is used to switch for prediction from center crop alone instead of averaging predictions across crops (default).
    classifier.predict(inputs, False)
    features = classifier.blobs['fc6'].data[0]
    extracted_cnn_features = create_dataset_final_mlp.get_cnn_features_as_vector(features)
    extracted_cnn_features = extracted_cnn_features[:-1]
    extracted_cnn_features = extracted_cnn_features.split(",")

    #   transform the text using text_2_bow functions
    pattern = pattern.split(",")
    text_pattern = pattern[1] + pattern[2]
    matrix = text_2_bow.get_matrix(text_pattern, dictionary)
    reshaped_matrix = np.reshape(matrix, 5000).tolist()

    full_features_vector = extracted_cnn_features + reshaped_matrix
    full_features_vector = np.asarray(full_features_vector, np.float64)

    #   use the MLP to classify
    prediction = mlp.predict_proba([full_features_vector])
    tolist = prediction[0].tolist()

    mapping = create_class_mapping()
    top5, probabilities = get_top5(tolist)
    top_class_name = get_top5_class_name(mapping, top5)

    print "Top 5 classes: ", top_class_name
    print "Top 5 probs ", probabilities
    return top_class_name, probabilities


if __name__ == "__main__":
    main("")

PHP Script

<?php

echo exec('sudo /home/super/bin/caffe-nv/python /home/super/PycharmProjects/img_plus_text/demo_website.py 2>&1'); 

?>

ERROR

sh: 1: /home/super/bin/caffe-nv/python: Permission denied

I have read majority of the questions on the issue however I am stuck here. Please point out the mistake. Thank you.

  • 写回答

1条回答 默认 最新

  • dtwncxs3547 2017-01-11 08:04
    关注

    The problem was with environment variables, I made a shell script as shown below

    export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/:$LD_LIBRARY_PATH
    export PYTHONPATH=$PYTHONPATH:/home/super/bin/caffe-nv/python/
    python /demo_website2.py $1
    

    Then I run the shell script from PHP using exec

    exec("/opt/lampp/htdocs/test/run.sh ". $param, $output);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错