我嘗試運行示例infer-simple.py,但無法成功,因為執行命令列 (image = cv2.imdecode(image, cv2.IMREAD_COLOR)) 時代碼回傳 None 值。
- 代碼:
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 影像是陣列而不是 None 之前,下面顯示了一個除錯示例。
- 除錯
resp: <urllib3.response.HTTPResponse object at 0x0000015055DE7070>
image: array([ 11, 214, 13, ..., 170, 1, 3], dtype=uint8)
但是,當我運行 cv2.imdecode(image, cv2.IMREAD_COLOR)) 時,我得到了一個無影像值。
3.錯誤
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.roboflow.com/python-webcam一步一步完成的。
我應用了在 Internet 上找到的解決方案,還重新安裝了所有必要的軟體包,但沒有任何效果。
uj5u.com熱心網友回復:
問題不在于您從相機獲取影像,而在于您從服務器獲取影像。
您必須在 roboflow.com 上創建專案并獲取模型的名稱和 api 密鑰 - 并使用所有這些來創建正確的 url。
我創建了帶有名稱的專案和訓練模型chess-sample-cpuhx/1并獲得了 API KEY,tE7xxxxxxxxx所以我有完整的 url
https://detect.roboflow.com/chess-sample-cpuhx/1?format=image&stroke=5&api_key=tE7xxxxxxxxx
我的代碼改動很少。
我檢查
- 如果網路攝像頭提供影像
- 如果服務器發送回應狀態
200并且狀態不同,則顯示來自服務器的訊息 - 例如b'{"message":"Not Found"}'或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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490885.html
標籤:Python opencv 摄像头 约洛夫5 机器人流
