在Laravel中运行python脚本

问题描述 投票:9回答:3

所以,我试图在我的Laravel 5.3中运行一个python脚本。

这个功能在我的Controller里面。这只是将数据传递给我的python脚本

public function imageSearch(Request $request) {
    $queryImage = 'c:\\\xampp\\\htdocs\\\identificare_api\\\public\\\gallery\\\herbs\\\query.png'; //queryImage
    $trainImage = 'c:\\\xampp\\\htdocs\\\identificare_api\\\public\\\gallery\\\herbs\\\2nd.png'; //trainImage
    $trainImage1 = 'c:\\\xampp\\\htdocs\\\identificare_api\\\public\\\gallery\\\herbs\\\3rd.png';
    $trainImage2 = 'c:\\\xampp\\\htdocs\\\identificare_api\\\public\\\gallery\\\herbs\\\4th.jpg';
    $trainImage3 = 'c:\\\xampp\\\htdocs\\\identificare_api\\\public\\\gallery\\\herbs\\\1st.jpg';

    $data = array
        (
            array(0, $queryImage),
            array(1, $trainImage),
            array(3, $trainImage1),
            array(5, $trainImage2),
            array(7, $trainImage3),
        );

    $count= count($data);
    $a = 1;
    $string = "";

    foreach( $data as $d){
        $string .= $d[0] . '-' . $d[1];

        if($a < $count){
            $string .= ","; 
        }
        $a++;

    }

    $result = shell_exec("C:\Python27\python c:\xampp\htdocs\identificare_api\app\http\controllers\ORB\orb.py " . escapeshellarg($string));

    echo $result;
}

我的python脚本是一个ORB算法,它在将火车图像与查询图像进行比较后返回最小距离及其id。所以,这是我的python脚本:

import cv2
import sys
import json
from matplotlib import pyplot as plt

arrayString = sys.argv[1].split(",")

final = []

for i in range(len(arrayString)):
    final.append(arrayString[i].split("-"))

img1 = cv2.imread(final[0][1], 0)

for i in range(1, len(arrayString)):

    img2 = cv2.imread(final[i][1], 0)

    # Initiate STAR detector
    orb = cv2.ORB_create()

    # find the keypoints and descriptors with SIFT
    kp1, des1 = orb.detectAndCompute(img1,None)
    kp2, des2 = orb.detectAndCompute(img2,None)

    # create BFMatcher object
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

    # Match descriptors.
    matches = bf.match(des1,des2)

    # Sort them in the order of their distance.
    matches = sorted(matches, key = lambda x:x.distance)

    # Draw first 10 matches.
    img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10], None, flags=2)

    if i == 1:
       distance = matches[0].distance
    else:
       if distance > matches[0].distance:
           distance = matches[0].distance
           smallestID = final[i][0]

print str(smallestID) + "-" + json.dumps(distance)

我已经尝试在不使用Laravel的情况下运行这两个文件,但它运行良好。但是当我试图将PHP代码集成到我的Laravel时,它什么都没显示。状态代码是200 OK。

编辑:解决了问题。在PHP代码中,只需更改

$result = shell_exec("C:\Python27\python c:\xampp\htdocs\identificare_api\app\http\controllers\ORB\orb.py " . escapeshellarg($string));

$result = shell_exec("python " . app_path(). "\http\controllers\ORB\orb.py " . escapeshellarg($string));

那么,你也可以这样做

$queryImage = public_path() . "\gallery\herbs\query.png";
php python exec shell-exec orb
3个回答
16
投票

使用Symfony进程。 https://symfony.com/doc/current/components/process.html

安装:

composer require symfony/process

码:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('python /path/to/your_script.py');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

0
投票

对我有用的解决方案是在结尾添加2>&1。

shell_exec("python path/to/script.py 2>&1");

我遇到的问题是没有错误,没有回应,我有错误的路径,但没有办法知道。 2>&1将调试信息重定向为结果。

In the shell, what does " 2>&1 " mean?


0
投票

使用Symfony Process会很方便。 https://symfony.com/doc/current/components/process.html

确保可以在项目中使用交响乐

composer show symphony/process

如果没有安装,请执行composer require symfony/process

然后做一些事情

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

//$process = new Process('python /path/to/your_script.py'); //This won't be handy when going to pass argument
$process = new Process(['python','/path/to/your_script.py',$arg(optional)]);
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
© www.soinside.com 2019 - 2024. All rights reserved.