2016-12-07 16 views
2

Итак, я пытаюсь запустить скрипт python в своем Laravel 5.3.Запуск сценария python в Laravel

Эта функция находится внутри моего контроллера. Это просто передает данные в мой питон скрипт

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; 
} 

Мой питон скрипт представляет собой алгоритм ORB, где он возвращает наименьшее расстояние и его идентификатор после сравнения поезда изображения к изображению запроса. Итак, это мой питон скрипт:

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.

EDIT: Проблема решена. В 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"; 

ответ

7

Использование 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

Я отредактировал мой вопрос выше. Я больше не мог использовать Symfony Process, который вы предложили. Спасибо, в любом случае! –

 Смежные вопросы

  • Нет связанных вопросов^_^