【问题标题】:encoding an image as binary and uploading it using POST multipart/form-data将图像编码为二进制并使用 POST multipart/form-data 上传
【发布时间】:2018-07-11 09:15:28
【问题描述】:

我正在尝试使用在线 API 检测人脸,该 API 需要使用 multipart/form-data 以二进制格式上传图像文件。我找到了一种将图像转换为二进制的方法。现在,对于上传部分,我是否有必要将此二进制数据写入文件?另外,我编写了以下代码并收到错误-

ValueError: 无法编码不是 2 元组的对象

我写的代码如下-

import requests
import pprint
from toBinary import conv

img='sample.jpg'

img=conv(img)
params={
    'api_key':<api key>,
    'api_secret':<api secret>,
}
print("1.-")
r = requests.post(url='https://api-
us.faceplusplus.com/facepp/v3/detect',data=params,files=img)

for face in range(0,len(r.json()['faces'])):
    pprint.pprint(r.json()['faces'][face]['face_token'])

img='01.jpg'
img=conv(img)
print("2-")
s = requests.post(url='https://api-
us.faceplusplus.com/facepp/v3/detect',data=params,files=img)

for face in range(0,len(s.json()['faces'])):
    pprint.pprint(s.json()['faces'][face]['face_token'])

toBinary 类如下-

import binascii
def conv(image_file):
    try:
        fin = open(image_file, "rb")
        data = fin.read()
        fin.close()
    except IOError:
        print("Image file %s not found" % image_file)
        raise SystemExit
    hex_str = str(binascii.hexlify(data))
    hex_list = []
    bin_list = []
    for ix in range(2, len(hex_str)-1, 2):
        hex = hex_str[ix]+hex_str[ix+1]
        hex_list.append(hex)
        bin_list.append(bin(int(hex, 16))[2:])
    bin_str = "".join(bin_list)
    return(bin_str)

edit- 添加 toBinary 类的代码,更改图像的来源。

【问题讨论】:

  • 请也附上 toBinary 类
  • toBinary 类的代码已根据您的要求添加。
  • 您是否将 url 传递给 conv 函数?然后尝试打开它?我认为open(image_file, "rb") 应该抛出一个错误
  • 一个错误,即找不到图像,与 url 一起引发。但是,当替换为本地图像的目录时,会抛出同样的错误(我上面提到的错误)

标签: python python-3.x python-requests multipartform-data face-detection


【解决方案1】:

我没有检查过这个解决方案

但是你可以试试这个https://github.com/FacePlusPlus/facepp-python-sdk

将此文件复制到您的项目https://github.com/FacePlusPlus/facepp-python-sdk/blob/master/facepp.py

然后像这样使用它:

from facepp import API
api = API(key, secret)
api.detection.detect(url=url)

【讨论】:

  • 我在你的代码中哪里引用了我试图检测人脸的图像?
  • api.detection.detect(url='https://pmcdeadline2.files.wordpress.com/2015/08/kevin-spacey-house-of- cards-s4.jpg?w=446&amp;h=299&amp;crop=1')
  • 我最终会尝试获取本地保存的图像。 api参考说明需要将本地保存的图像转换为二进制,然后按照我之前所说的方式上传。如果我之前没有说明,我很抱歉。我只是在尝试转换本地保存的图像之前尝试转换 url 图像。
  • 你可以试试这个api.detection.detect(img = File('/tmp/test.jpg'))
  • api 文档指出,如果必须上传本地保存的图像,则必须将其转换为二进制或 base64 编码的二进制形式。不过,我会尝试您建议的方法并报告,感谢您的帮助。 api 的文档,如果你需要的话,是here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2022-07-29
  • 2015-10-11
相关资源
最近更新 更多