macOS下PHP调用Python 3.9脚本返回Null结果的问题排查
PHP调用带人脸识别的Python脚本返回Null的解决建议
问题场景
在VSCode中编写PHP代码,通过Safari浏览器调用Python 3.9脚本时,仅含print语句的脚本可正常返回结果,但包含人脸识别逻辑的脚本始终返回Null。
相关代码
PHP代码
<?php $result = shell_exec("/usr/bin/python3 fr/fr_load.py"); var_dump($result); ?>
Python代码
#!/usr/bin/python3 #import the required libraries import cv2 import joblib from sys import exit from sklearn.feature_extraction.text import CountVectorizer import pandas as pd # function to detect face from image def face_detection(image_to_detect): #converting the image to grayscale since its required for eigen and fisher faces image_to_detect_gray = cv2.cvtColor(image_to_detect, cv2.COLOR_BGR2GRAY) # load the pretrained model for face detection # haarcascade is recommended for Eigenface face_detection_classifier = cv2.CascadeClassifier('php/fr/models/haarcascade_frontalface_default.xml') # detect all face locations in the image using classifier all_face_locations = face_detection_classifier.detectMultiScale(image_to_detect_gray) # if no faces are detected if (len(all_face_locations) == 0): return None, None #splitting the tuple to get four face positions x,y,width,height = all_face_locations[0] #[0] cuz we assume we have only one face on our data set #calculating face coordinates face_coordinates = image_to_detect_gray[y:y+width, x:x+height] #for traning and testting all images should be at same size (for egien) face_coordinates = cv2.resize(face_coordinates,(500,500)) #we can use any number fit for us #return the face detected and face location return face_coordinates, all_face_locations[0] #all_face_locations[0] beacuse there is only one face in each image names =[] names.append("steve jobs") names.append("ali alramadan") names.append("hillary clinton") #########load recognition model for later use ########### face_classifier = cv2.face.EigenFaceRecognizer_create() face_classifier.read("php/fr/models/our model.yml") ######## prediction ############## #path of the image we want to test and predict image_to_classify = cv2.imread("php/fr/dataset/testing/load.jpg") #make a copy of the image cuz we dont want to ruin the actual image by writing on it image_to_classify_copy = image_to_classify.copy() #get the face from the image face_coordinates_classify, box_locations = face_detection(image_to_classify_copy) #if no faces are returned if face_coordinates_classify is None: print("There are no faces in the image to classify") exit() #if face is returned then predict the face name_index, distance = face_classifier.predict(face_coordinates_classify) #if distance is big then there is big different between the train image and test image name = names[name_index] distance = abs(distance) print(name) #draw bounding box and text for the face detected (x,y,w,h) = box_locations cv2.rectangle(image_to_classify,(x,y),(x+w, y+h),(0,255,0),2) cv2.putText(image_to_classify,name,(x,y-5),cv2.FONT_HERSHEY_PLAIN,2.5,(0,255,0),2) #show the image in window cv2.imshow("Prediction "+name, cv2.resize(image_to_classify, (500,500))) cv2.waitKey(0) cv2.destroyAllWindows()
解决建议
1. 移除GUI阻塞代码
Python脚本中的cv2.waitKey(0)会让脚本一直等待键盘输入,导致shell_exec无法获取输出。直接注释或删除以下代码块:
#show the image in window cv2.imshow("Prediction "+name, cv2.resize(image_to_classify, (500,500))) cv2.waitKey(0) cv2.destroyAllWindows()
若需本地可视化测试,仅在直接运行Python脚本时保留这段代码。
2. 替换为绝对路径
PHP执行时的工作目录可能与脚本预期不符,导致相对路径无法找到依赖文件。将所有文件路径改为绝对路径,例如:
face_detection_classifier = cv2.CascadeClassifier('/Users/yourname/project/php/fr/models/haarcascade_frontalface_default.xml') face_classifier.read("/Users/yourname/project/php/fr/models/our model.yml") image_to_classify = cv2.imread("/Users/yourname/project/php/fr/dataset/testing/load.jpg")
需替换为你项目的真实根路径。
3. 捕获错误输出
shell_exec仅捕获标准输出,修改PHP代码将错误输出重定向到标准输出,以便排查脚本报错:
<?php $result = shell_exec("/usr/bin/python3 fr/fr_load.py 2>&1"); var_dump($result); ?>
4. 检查权限
Web服务器(如Apache/Nginx)的执行用户可能没有访问模型、图片等文件的权限:
- 执行
chmod -R 755 /path/to/your/project/php/fr设置文件夹权限 - 确保Web用户属于文件所在用户组
5. 验证脚本独立执行性
在终端直接运行Python脚本,确认脚本本身可正常输出:
/usr/bin/python3 /path/to/fr/fr_load.py
若终端运行报错,先修复脚本本身问题(如依赖缺失、模型损坏),再通过PHP调用。
内容的提问来源于stack exchange,提问作者ammr mmar
相关产品推荐
相关产品推荐

