I've just created a yolov5 model, and exported it in the onnx format so it is usable with opencv but I keep getting the error:
[ERROR:0] global D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\dnn.cpp (3554) cv::dnn::dnn4_v20211004::Net::Impl::getLayerShapesRecursively OPENCV/DNN: [Reshape]:(466): getMemoryShapes() throws exception. inputs=1 outputs=1/1 blobs=0 [ERROR:0] global D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\dnn.cpp (3557) cv::dnn::dnn4_v20211004::Net::Impl::getLayerShapesRecursively input[0] = [ 1 24 52 52 ] [ERROR:0] global D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\dnn.cpp (3561) cv::dnn::dnn4_v20211004::Net::Impl::getLayerShapesRecursively output[0] = [ ] [ERROR:0] global D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\dnn.cpp (3567) cv::dnn::dnn4_v20211004::Net::Impl::getLayerShapesRecursively Exception message: OpenCV(4.5.4) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\layers\reshape_layer.cpp:106: error: (-215:Assertion failed) total(srcShape, srcRange.start, srcRange.end) == maskTotal in function 'cv::dnn::computeShapeByReshapeMask'
here is the code:
onnx_model = onnx.load('best.onnx')
onnx.checker.check_model(onnx_model)
net = cv.dnn.readNetFromONNX('best.onnx')
classes = []
with open("coco-dataset.labels", "r") as f:
classes = [line.strip() for line in f.readlines()]
layerNames = net.getLayerNames()
outputLayers=[]
for i in net.getUnconnectedOutLayers():
outputLayers.append(layerNames[i-1])
bounding_box = {'top': 0, 'left': 0, 'width': 1920, 'height': 1080}
sct = mss()
while True:
screenShot = sct.grab(bounding_box)
img_np = np.array(screenShot)
frame = cv.cvtColor(img_np, cv.COLOR_RGBA2RGB)
frame_id += 1
height, width, channels= frame.shape
blob = cv.dnn.blobFromImage(frame, 0.0039216, (416, 416), (0, 0, 0), True, crop=False)
cv.imshow("Image", frame)
net.setInput(blob)
(THIS IS THE ERROR LINE)
outs = net.forward(outputLayers)
I'm not sure if it is just my understanding of onnx, or if there is a fix I haven't picked up on.
Any help is appreciated!
Until now latest version of OpenCV (4.5.4), OpenCV unable to load onnx file without simplification operation. You have exported yolov5 pt file to onnx file with below command.
python export.py --weights .\best.pt
Try to export pt file to onnx file with below commands.
For Ubuntu:
python export.py --weights .\yolov5s.pt --include onnx --simplify
For Windows
pip install onnx
pip install onnx-simplifier
python export.py --weights .\yolov5s.pt --include onnx --simplify
and then load created onnx file with OpenCV, OpenCV will read that onnx successfully.
Also change you model size to (640,640) in blobfromimage function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With