我不断收到此错误:
cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:971: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
我已经完成了所有其他修复,这些修复实际上工作了一天,然后没有(例如将版本更新为 name/version#)。但现在,即使没有更改代码,我又再次收到错误。
这是我的代码部分:
upload_url = "".join([
"https://detect.roboflow.com/",
"basketball-cv/3",
"?api_key=",
"*************",
"&format=image",
"&stroke=5"
])
async def infer(requests):
# 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 = await requests.post(upload_url, data=img_str, headers={
"Content-Type": "application/x-www-form-urlencoded"
})
# Parse result image
image = np.asarray(bytearray(resp.content), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
...
cv2.imshow('image', image)
问题是什么?
我尝试更改版本号、更新大小和 API 密钥
@ChristophRackwitz 和 @DanMašek 已经提供了一些提示:
您没有检查
video.read()
是否返回帧,假设video
是cv2.VideoCapture
的实例,您应该在假设方法返回帧之前检查ret
,正如OpenCV文档建议的那样
您没有检查
requests.post
返回的响应
我还要补充一点,很难推理您提供的示例代码,似乎
video
是一个全局变量,并且在脚本执行到达infer
之前,它可能会在代码中的其他位置关闭。
您可以考虑稍微重构一下您的代码,这样您就可以更轻松地推断出问题所在:
import cv2
import numpy as np
import requests
class ReadingFrameFailed(Exception):
pass
class RequestsPostFailed(Exception):
pass
class MalformedResponse(Exception):
pass
# (...)
async def infer(
video: cv2.VideoCapture,
model_id,
roboflowapi_key,
requests: ????,
upload_url_template: str = "https://detect.roboflow.com/{model_id}?api_key={roboflow_api_key}&format=image&stroke=5",
) -> np.array:
ret, img = video.read()
if not ret:
raise ReadingFrameFailed("Failed to grab frame")
# logic for resizing and serializing frame
# (...)
upload_url = upload_url_template.format(**{
"model_id": model_id,
"roboflow_api_key": roboflow_api_key,
})
try:
resp = await requests.post(upload_url, data=img_str,
headers={"Content-Type": "application/x-www-form-urlencoded"})
except Exception as exc:
# ugly but since we don't know what `requests` object is...
raise RequestsPostFailed(str(exc))
image = np.asarray(bytearray(resp.content), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
if not image:
raise MalformedResponse("Failed to parse image, API returned unexpected result")
return image