【问题标题】:Python requests - post method - send image from CV2 - ndarray not workingPython 请求 - 发布方法 - 从 CV2 发送图像 - ndarray 不起作用
【发布时间】:2020-12-06 10:35:21
【问题描述】:

我有以下 Flask API 服务器端代码:

    def post(self):
        data = parser.parse_args()
        if not data['file']:
            abort(404, message="No images found")
        imagestr = data['file'].read()
        if imagestr:
            #convert string data to numpy array
            npimg = np.frombuffer(imagestr, np.uint8)
            # convert numpy array to image
            img = cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED)

客户端代码:

def detect(image):
    endpoint = "http://127.0.0.1/getimage"
    # imstring = base64.b64encode(cv2.imencode('.jpg', image)[1]).decode()
    # img_str = cv2.imencode('.jpg', image)
    # im = img_str.tostring()
    # jpg_as_text = base64.b64encode(buffer)
    # print(jpg_as_text)
    data = cv2.imencode('.jpg', image)[1].tobytes()
    files = {'file':data}
    headers={"content-type":"image/jpg"}
    response = requests.post(endpoint, files=files, headers=headers)
    return response

对于 API,我能够通过 CURL 成功发送图像并获得响应。

curl -X POST -F file=@input.jpg http://127.0.0.1/getimage

但是,当我尝试使用客户端代码时,我无法发送图像。我看到服务器端没有收到文件:

{'file': None}
192.168.101.57 - - [17/Aug/2020 14:56:39] "POST /getimage HTTP/1.1" 404 -

我不确定我错过了什么。有人可以帮忙吗?

【问题讨论】:

  • 在您的 curl 中将其发送到端点 /getimage 但服务器日志显示 /detect - 检查您实际上使用的是正确的端点
  • 已更正。谢谢。

标签: python-3.x file-upload python-requests http-post flask-restful


【解决方案1】:

根据request docs,您应该使用以下方法发布文件:

files = {'file': ('image.jpg', open('image.jpg', 'rb'), 'image/jpg', {'Expires': '0'})}
response = requests.post(endpoint, files=files)

【讨论】:

    【解决方案2】:

    我个人使用这种方法,因为它不仅可以发送图像,还可以发送 任何 numpy 数组,并进行一些压缩以减小大小。 (假设您要发送一个 4d numpy 数组的图像数组时很有用)

    客户端代码:

    import io,zlib
    def encode_ndarray(np_array):    #utility function
        bytestream = io.BytesIO()
        np.save(bytestream, np_array)
        uncompressed = bytestream.getvalue()
        compressed = zlib.compress(uncompressed,level=1)   #level can be 0-9, 0 means no compression
        return compressed
    
    any_numpy_array = np.zeros((4,150,150,3))
    encoded_array = encode_ndarray(any_numpy_array)
    headers = {'Content-Type': 'application/octet-stream'}
    resp = requests.post(endpoint, data=encoded_array,headers=headers)
    

    服务器端代码:

    def decode_ndarray(bytestream):    #utility function
        return np.load(io.BytesIO(zlib.decompress(bytestream)))
    
    @app.route("/getimage", methods=['POST'])
    def function():
        r = request
        any_numpy_array = decode_ndarray(r.data)
    
    

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多