How to send OpenCV Image using python requests to Go Endpoint

huangapple go评论88阅读模式
英文:

How to send OpenCV Image using python requests to Go Endpoint

问题

这是我的相机脚本的代码:

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("http://localhost:3004/", 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)

这是我的Go服务器的代码:

package main

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

	"github.com/gorilla/mux"
)

func imgHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("收到请求!")

	r.ParseMultipartForm(10 << 20)

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

	if err != nil {
		fmt.Println("错误!")
		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))
}

我不知道为什么在FormFile函数上一直出错。我的最终目标是建立一个安全的连接到一个端点,这样我就可以从我的树莓派发送图像到我的服务器并将其保存在本地。我该如何使用Python的requests库将文件发送到我的Go端点?我已经看到了一些解决方案,涉及在HTML页面上使用<form>元素,这种方法是可行的。

英文:

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(&quot;.jpg&quot;, frame)[1]
    now = datetime.now()
    seq = now.strftime(&quot;%Y%m%d%H%M%S&quot;)
    file = {&#39;file&#39;: (seq+&#39;.jpg&#39;, imencoded.tobytes(), &#39;image/jpeg&#39;)}
    response = requests.post(&quot;http://localhost:3004/&quot;, 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

package main

import (
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;net/http&quot;

	&quot;github.com/gorilla/mux&quot;
)

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

	r.ParseMultipartForm(10 &lt;&lt; 20)

	file, handler, err := r.FormFile(&quot;myFile&quot;)

	if err != nil {
		fmt.Println(&quot;error!&quot;)
		return
	}

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

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

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

	r.HandleFunc(&quot;/&quot;, imgHandler).Methods(&quot;POST&quot;)
	r.HandleFunc(&quot;/&quot;, getHandler).Methods(&quot;GET&quot;)

	http.Handle(&quot;/&quot;, r)

	log.Fatal(http.ListenAndServe(&quot;:3004&quot;, nil))
}

I have no idea why I keep on getting an error on my 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. I've already seen solutions that involve using <form> elements on a html page that works.

答案1

得分: 1

在Python中,你调用的字段是file,而在Go中,你尝试访问的是myFile。对Go代码的更改如下:

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

为了找出问题,我将调试行更改为打印错误信息:

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

(通常在服务器中使用log.Printf How to send OpenCV Image using python requests to Go Endpoint

英文:

In Python you call the field file where in Go you try to access myFile. The change to the Go code was:

file, handler, err := r.FormFile(&quot;file&quot;)

To find this out, I've changed the debug line to print the error as well:

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

(In general, use log.Printf in servers How to send OpenCV Image using python requests to Go Endpoint

huangapple
  • 本文由 发表于 2022年8月8日 10:19:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/73272374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定