简体   繁体   English

如何使用 python 请求将 OpenCV 图像发送到 Go 端点

[英]How to send OpenCV Image using python requests to Go Endpoint

Here is the code for my camera script这是我的相机脚本的代码

import cv2
import requests
from datetime import datetime
from time import sleep

def sendImage(frame):
    imencoded = cv2.imencode(".jpg", frame)[1]
    now = datetime.now()
    seq = now.strftime("%Y%m%d%H%M%S")
    file = {'file': (seq+'.jpg', imencoded.tobytes(), 'image/jpeg')}
    response = requests.post("https://noeldev.site/cam", files=file, timeout=5)
    return response

def takeImage():
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    print(sendImage(frame))
    cap.release()


while 1:
    takeImage()
    sleep(5)

and my Go Server和我的 Go 服务器

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func imgHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("recieved request!")

    r.ParseMultipartForm(10 << 20)

    file, handler, err := r.FormFile("myFile")

    if err != nil {
        fmt.Println("error!")
        return
    }

    defer file.Close()
    fmt.Println(handler.Filename)
}

func getHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello World API!")
}

func main() {
    r := mux.NewRouter()

    r.HandleFunc("/", imgHandler).Methods("POST")
    r.HandleFunc("/", getHandler).Methods("GET")

    http.Handle("/", r)

    log.Fatal(http.ListenAndServe(":3004", nil))
}

I have no idea why I keep on getting an error on my FormFile function.我不知道为什么我的 FormFile function 不断出现错误。 My end goal is to have a secure connection to an endpoint so that I can send images from my raspberry pi to my server and have it saved locally.我的最终目标是与端点建立安全连接,以便我可以将图像从我的树莓派发送到我的服务器并将其保存在本地。 How can I do this so I send files to my Go endpoint using the python requests library.我该怎么做才能使用 python 请求库将文件发送到我的 Go 端点。 I've already seen solutions that involve using elements on a html page that works.我已经看到涉及在有效的 html 页面上使用元素的解决方案。

In Python you call the field file where in Go you try to access myFile .在 Python 中,您调用字段file ,在 Go 中,您尝试访问myFile The change to the Go code was:对 Go 代码的更改是:

file, handler, err := r.FormFile("file")

To find this out, I've changed the debug line to print the error as well:为了解决这个问题,我也更改了调试行以打印错误:

if err != nil {
    fmt.Printf("error: %s\n", err)
    return
}

(In general, use log.Printf in servers:) (一般情况下,在服务器中使用log.Printf :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM