python - 如何使用用户提供的图像将 python 脚本作为 Web 服务运行?

标签 python flask

<分区>

我有一个 Python(2.7) 脚本,可以检测图像中的人脸,效果很好。

from PIL import Image
import face_recognition


# Load the jpg file into a numpy array
image = face_recognition.load_image_file("/PATH_TO_IMAGE/IMAGE.jpg")

# Find all the faces in the image
face_locations = face_recognition.face_locations(image)

# a = print("Found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:

    # Print the location of each face in this image
  top, right, bottom, left = face_location
  print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

    # You can access the actual face itself like this:
  face_image = image[top:bottom, left:right]
  pil_image = Image.fromarray(face_image)
  pil_image.show()

现在,我想把它变成一个 http://localhost:8080/detect这样用户就可以提供图像并单击提交按钮将显示输出。我认为有几种方法可以做到这一点,使用 Flask、Django 或 Web 服务器。但不确定哪种是最简单的方法以及如何去做。如何获取此代码并将其转换为网络服务?需要更改哪些代码?任何代码示例都会有很大帮助。

最佳答案

我相信您是在问什么是适合 Python 的优秀 Web 框架。在我能胜任之前,我写了一个Django 网络服务器,我觉得有点令人生畏。但那时一切都令人生畏。自从成为 OK 程序员以来,我在几个项目中使用过 Flask。它相当简单,易于设置,并且有详细的文档记录,Django 也是如此。我用了this tutorial在我学习 Flask 的时候。据我了解,这确实是一个意见问题,所以恕我直言,我会像教程中那样使用 FlaskuWSGINginx .不过,我鼓励您自己进行研究,看看其他选择是否更适合您和您的项目。

编辑:要使用此代码Flask,您可以将代码直接放在route's 中。函数,甚至更好地将其放入函数或类中并导入它。甚至更好地创建一个 model, view, and controller(MVC) .粗略地看一下,您似乎必须 upload the file and save it ,然后用face_recognition打开它。 face_recognition module似乎无法从内存中读取数据,因此保存文件并使用 face_recognition.load_image_file("/PATH_TO_IMAGE/IMAGE.jpg") 似乎是必要的。只是为了确保在加载文件以清理空间后将其删除。然后一旦你有了你的 PIL.Image 对象,你将从你的代码中返回它,然后用 flask.send_file 函数发送它作为 demonstrated here .有很多链接但没有代码,但是这些链接以及我最初链接到的教程应该可以帮助您到达需要的位置。

注意:如果不清楚,您的代码应该返回 Image.fromarray(face_image) 而不是使用 show 函数.

关于python - 如何使用用户提供的图像将 python 脚本作为 Web 服务运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43104600/

相关文章:

python - 直接前一个兄弟的 xpath

python - 我想在 flask route 返回 html

python - __del__ 的用例

python - 在 Python Flask 中将 Pandas 数据框作为 JSONP 响应返回

Python Shell 不工作,不运行解释器 (Flask)

flask - 在没有 https 的情况下在本地测试flask-oauthlib

javascript - 使用 AJAX 在 Flask 和 JS 之间发送数据以进行 chrome 扩展

python - 无法从 python os.path.abspath 获取有效路径名

Python BeautifulSoup - find 和 findAll 的不同结果

python - 如何暂停或删除 manim 中的声音?