将网络摄像头与yolov5型号一起使用

发布于 2025-02-06 23:38:50 字数 2086 浏览 3 评论 0 原文

我试图举办示例,但是我无法成功,因为执行命令行(image = cv2.imdecode(image,cv2.imread_color))时,代码正在返回无值。

  1. 代码:
def infer():
    # Get the current image from the webcam
    ret, img = video.read()

    # Resize (while maintaining the aspect ratio) to improve speed and save bandwidth
    height, width, channels = img.shape
    scale = ROBOFLOW_SIZE / max(height, width)
    img = cv2.resize(img, (round(scale * width), round(scale * height)))

    # Encode image to base64 string
    retval, buffer = cv2.imencode('.jpg', img)
    img_str = base64.b64encode(buffer)

    # Get prediction from Roboflow Infer API
    resp = requests.post(upload_url, data=img_str, headers={
        "Content-Type": "application/x-www-form-urlencoded"
    }, stream=True).raw

    # Parse result image
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    
    return image

始终在IMDecode映像为数组之前,并非没有,Bellow显示了一个调试示例。

  1. 但是
resp: <urllib3.response.HTTPResponse object at 0x0000015055DE7070>

image: array([ 11, 214,  13, ..., 170,   1,   3], dtype=uint8)

,当我运行cv2.imdecode(image,cv2.imread_color)时),我会获得图像的无值。

3. error

Exception has occurred: error OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:816: 
error: (-215:Assertion failed) !buf.empty() in function 'cv::imdecode_'

  File "C:\Users\diego\codes\Webcam\infer-simple.py", line 48, in infer
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
  File "C:\Users\diego\codes\Webcam\infer-simple.py", line 63, in <module>
    image = infer()

我根据 https://blog.roboboflow.com/python---网络摄像头

我应用了在互联网上找到的解决方案,还重新安装了所有必要的软件包,但没有任何效果。

I tried to run the example infer-simple.py, but I can't succeed, because the code is returning a None value when the command line (image = cv2.imdecode(image, cv2.IMREAD_COLOR)) is executed.

  1. code:
def infer():
    # Get the current image from the webcam
    ret, img = video.read()

    # Resize (while maintaining the aspect ratio) to improve speed and save bandwidth
    height, width, channels = img.shape
    scale = ROBOFLOW_SIZE / max(height, width)
    img = cv2.resize(img, (round(scale * width), round(scale * height)))

    # Encode image to base64 string
    retval, buffer = cv2.imencode('.jpg', img)
    img_str = base64.b64encode(buffer)

    # Get prediction from Roboflow Infer API
    resp = requests.post(upload_url, data=img_str, headers={
        "Content-Type": "application/x-www-form-urlencoded"
    }, stream=True).raw

    # Parse result image
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    
    return image

Always before the imdecode image is array not None, bellow is displayed one debug example.

  1. Debug
resp: <urllib3.response.HTTPResponse object at 0x0000015055DE7070>

image: array([ 11, 214,  13, ..., 170,   1,   3], dtype=uint8)

However, when I run cv2.imdecode(image, cv2.IMREAD_COLOR)) I get a none value for image.

3.Error

Exception has occurred: error OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:816: 
error: (-215:Assertion failed) !buf.empty() in function 'cv::imdecode_'

  File "C:\Users\diego\codes\Webcam\infer-simple.py", line 48, in infer
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
  File "C:\Users\diego\codes\Webcam\infer-simple.py", line 63, in <module>
    image = infer()

I did it all step by step according to https://blog.roboflow.com/python-webcam.

I applied solutions found on the Internet and also reinstalled all necessary packages but nothing worked.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡的优雅 2025-02-13 23:38:51

问题不是从相机中获得图像,而是从服务器获得图像时。

您必须在Roboflow.com上创建项目,并获取Model的名称和API键 - 并使用所有这些来创建正确的URL。

我创建了带有名称国际样本cpuhx/1 的项目和受过训练的模型,并获得了API密钥,例如 TE7XXXXXXXXXXXX ,因此

https://detect.roboflow.com/chess-sample-cpuhx/1?format=image&stroke=5&api_key=tE7xxxxxxxxx

我的代码有几个更改。

我检查

  • 网络摄像头是否给出了映像
  • ,如果服务器发送响应状态 200 以及状态是否不同,请从服务器显示消息 - 例如 b'{“ message”:“ nt of condut”}'}' b'{“ message”:“ forbidden”}'
# all `import` at the beginning
import json
import base64
import cv2
import numpy as np
import requests
import time

# --- constants ---  

ROBOFLOW_API_KEY = 'tE7xxxxxxxxx'
ROBOFLOW_MODEL = 'chess-sample-cpuhx/1'
ROBOFLOW_SIZE = 400

# --- functions ---

params = {
    "api_key": ROBOFLOW_API_KEY,
    "format": "image",
    "stroke": "5"
}

headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

url = f"https://detect.roboflow.com/{ROBOFLOW_MODEL}"


def infer(img):
    # Resize (while maintaining the aspect ratio) to improve speed and save bandwidth
    height, width, channels = img.shape
    scale = ROBOFLOW_SIZE / max(height, width)
    img = cv2.resize(img, (round(scale * width), round(scale * height)))

    # Encode image to base64 string
    retval, buffer = cv2.imencode('.jpg', img)
    img_str = base64.b64encode(buffer)

    # Get prediction from Roboflow Infer API
    response = requests.post(url, params=params, data=img_str, headers=headers, stream=True)
    data = response.raw.read()
    
    #print(response.request.url)
    
    if not response.ok:
        print('status:', response.status_code)
        print('data:', data)
        return
    
    # Parse result image
    image = np.asarray(bytearray(data), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)

    return image

# --- main ---

video = cv2.VideoCapture(0)

while True:

    start = time.time()

    ret, img = video.read()
    
    if ret:
        
        image = infer(img)
        
        if image is not None:
            cv2.imshow('image', image)
        
            if cv2.waitKey(1) == ord('q'):  # `waitKey` should be after `imshow()` - to update image in window and to get key from window
                break
        
            end = time.time()
            print( 1/(end-start), "fps")  # print() automatically add space between elements - you don't need space in "fps"
        
# - end -

video.release()
cv2.destroyAllWindows()

Problem is not when you get image from camera but when you get image from server.

You have to create project on roboflow.com and gets model's name and api key - and use all this to create correct url.

I created project and trained model with name chess-sample-cpuhx/1 and got API KEY like tE7xxxxxxxxx so I have full url

https://detect.roboflow.com/chess-sample-cpuhx/1?format=image&stroke=5&api_key=tE7xxxxxxxxx

My code with few changes.

I check

  • if webcam gives image
  • if server send response status 200 and if status is different then display message from server - like b'{"message":"Not Found"}' or b'{"message":"Forbidden"}'
# all `import` at the beginning
import json
import base64
import cv2
import numpy as np
import requests
import time

# --- constants ---  

ROBOFLOW_API_KEY = 'tE7xxxxxxxxx'
ROBOFLOW_MODEL = 'chess-sample-cpuhx/1'
ROBOFLOW_SIZE = 400

# --- functions ---

params = {
    "api_key": ROBOFLOW_API_KEY,
    "format": "image",
    "stroke": "5"
}

headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

url = f"https://detect.roboflow.com/{ROBOFLOW_MODEL}"


def infer(img):
    # Resize (while maintaining the aspect ratio) to improve speed and save bandwidth
    height, width, channels = img.shape
    scale = ROBOFLOW_SIZE / max(height, width)
    img = cv2.resize(img, (round(scale * width), round(scale * height)))

    # Encode image to base64 string
    retval, buffer = cv2.imencode('.jpg', img)
    img_str = base64.b64encode(buffer)

    # Get prediction from Roboflow Infer API
    response = requests.post(url, params=params, data=img_str, headers=headers, stream=True)
    data = response.raw.read()
    
    #print(response.request.url)
    
    if not response.ok:
        print('status:', response.status_code)
        print('data:', data)
        return
    
    # Parse result image
    image = np.asarray(bytearray(data), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)

    return image

# --- main ---

video = cv2.VideoCapture(0)

while True:

    start = time.time()

    ret, img = video.read()
    
    if ret:
        
        image = infer(img)
        
        if image is not None:
            cv2.imshow('image', image)
        
            if cv2.waitKey(1) == ord('q'):  # `waitKey` should be after `imshow()` - to update image in window and to get key from window
                break
        
            end = time.time()
            print( 1/(end-start), "fps")  # print() automatically add space between elements - you don't need space in "fps"
        
# - end -

video.release()
cv2.destroyAllWindows()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文