登录
首页 >  Golang >  Go问答

Python请求:将OpenCV图像发送到Go终端的使用指南

来源:stackoverflow

时间:2024-02-06 12:33:22 413浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《Python请求:将OpenCV图像发送到Go终端的使用指南》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

这是我的相机脚本的代码

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("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))
}

我不知道为什么我的 formfile 函数不断出现错误。我的最终目标是与端点建立安全连接,以便我可以将图像从树莓派发送到我的服务器并将其保存在本地。我该如何执行此操作,以便使用 python requests 库将文件发送到我的 go 端点。我已经看到了一些解决方案,涉及在有效的 html 页面上使用元素。


正确答案


在 python 中,您将字段称为 file,而在 go 中,您尝试访问 myfile。 go 代码的更改是:

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

为了找出这一点,我更改了调试行以打印错误:

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

(一般情况下,在服务器中使用 log.printf :)

今天关于《Python请求:将OpenCV图像发送到Go终端的使用指南》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>