API集成:索引错误:对标量变量的无效索引

huangapple go评论92阅读模式
英文:

API Integration: IndexError: invalid index to scalar variable

问题

以下是您提供的代码的中文翻译部分:

  1. 我正在尝试使用FastAPI集成我的Yolov4 darknet自定义训练模型但控制台上出现了IndexError: scalar变量的无效索引并且在FastAPI本地服务器上出现了内部服务器错误以下是我的用于运行API的代码
  2. ```python
  3. import cv2
  4. import numpy as np
  5. import tensorflow as tf
  6. # 加载 YOLO v4 模型
  7. model = cv2.dnn.readNetFromDarknet("yolov4_test.cfg", "yolov4_train_final.weights")
  8. from fastapi import FastAPI, File, UploadFile
  9. from typing import List, Tuple
  10. app = FastAPI()
  11. @app.post("/detect_objects")
  12. async def detect_objects(image: UploadFile = File(...)) -> List[Tuple[str, Tuple[int, int, int, int]]]:
  13. # 读取图像文件
  14. image_bytes = await image.read()
  15. nparr = np.frombuffer(image_bytes, np.uint8)
  16. img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  17. # 在图像上运行 YOLO v4 模型
  18. blob = cv2.dnn.blobFromImage(img, 1/255.0, (608, 608), swapRB=True, crop=False)
  19. model.setInput(blob)
  20. layer_names = model.getLayerNames()
  21. output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]
  22. outputs = model.forward(output_layers)
  23. # 提取边界框和类别标签
  24. boxes = []
  25. for output in outputs:
  26. for detection in output:
  27. scores = detection[5:]
  28. class_id = np.argmax(scores)
  29. confidence = scores[class_id]
  30. if confidence > 0.5:
  31. center_x = int(detection[0] * img.shape[1])
  32. center_y = int(detection[1] * img.shape[0])
  33. width = int(detection[2] * img.shape[1])
  34. height = int(detection[3] * img.shape[0])
  35. left = int(center_x - width / 2)
  36. top = int(center_y - height / 2)
  37. boxes.append((class_id, (left, top, width, height)))
  38. # 将类别ID映射到类别标签
  39. classes = ["枪支"]
  40. results = []
  41. for box in boxes:
  42. class_label = classes[box[0]]
  43. bbox = box[1]
  44. results.append((class_label, bbox))
  45. return results

控制台中的错误信息如下:

  1. Traceback (most recent call last):
  2. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 428, in run_asgi
  3. result = await app( # type: ignore[func-returns-value]
  4. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
  5. return await self.app(scope, receive, send)
  6. # 其他错误信息...
  7. IndexError: scalar变量的无效索引。

您正在尝试获得边界框和标签,并将它们作为服务器响应返回。

英文:

I am trying to integrate my Yolov4 darknet customed trained model using fast api but am getting an IndexError: invalid index to scalar variable on console and Internal Server Error on Fastapi local server. Following is my code to run the API:

  1. import cv2
  2. import numpy as np
  3. import tensorflow as tf
  4. # Load YOLO v4 model
  5. model = cv2.dnn.readNetFromDarknet("yolov4_test.cfg", "yolov4_train_final.weights")
  6. from fastapi import FastAPI, File, UploadFile
  7. from typing import List, Tuple
  8. app = FastAPI()
  9. @app.post("/detect_objects")
  10. async def detect_objects(image: UploadFile = File(...)) -> List[Tuple[str, Tuple[int, int, int, int]]]:
  11. # Read image file
  12. image_bytes = await image.read()
  13. nparr = np.frombuffer(image_bytes, np.uint8)
  14. img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  15. # Run YOLO v4 model on image
  16. blob = cv2.dnn.blobFromImage(img, 1/255.0, (608, 608), swapRB=True, crop=False)
  17. model.setInput(blob)
  18. layer_names = model.getLayerNames()
  19. output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]
  20. outputs = model.forward(output_layers)
  21. # Extract bounding boxes and class labels
  22. boxes = []
  23. for output in outputs:
  24. for detection in output:
  25. scores = detection[5:]
  26. class_id = np.argmax(scores)
  27. confidence = scores[class_id]
  28. if confidence > 0.5:
  29. center_x = int(detection[0] * img.shape[1])
  30. center_y = int(detection[1] * img.shape[0])
  31. width = int(detection[2] * img.shape[1])
  32. height = int(detection[3] * img.shape[0])
  33. left = int(center_x - width / 2)
  34. top = int(center_y - height / 2)
  35. boxes.append((class_id, (left, top, width, height)))
  36. # Map class IDs to class labels
  37. classes = ["Gun"]
  38. results = []
  39. for box in boxes:
  40. class_label = classes[box[0]]
  41. bbox = box[1]
  42. results.append((class_label, bbox))
  43. return results

Following is the error i am getting in console:

  1. Traceback (most recent call last):
  2. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 428, in run_asgi
  3. result = await app( # type: ignore[func-returns-value]
  4. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
  5. return await self.app(scope, receive, send)
  6. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\fastapi\applications.py", line 276, in __call__
  7. await super().__call__(scope, receive, send)
  8. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\applications.py", line 122, in __call__
  9. await self.middleware_stack(scope, receive, send)
  10. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
  11. raise exc
  12. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
  13. await self.app(scope, receive, _send)
  14. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
  15. raise exc
  16. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
  17. await self.app(scope, receive, sender)
  18. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
  19. raise e
  20. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
  21. await self.app(scope, receive, send)
  22. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\routing.py", line 718, in __call__
  23. await route.handle(scope, receive, send)
  24. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\routing.py", line 276, in handle
  25. await self.app(scope, receive, send)
  26. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\starlette\routing.py", line 66, in app
  27. response = await func(request)
  28. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\fastapi\routing.py", line 237, in app
  29. raw_response = await run_endpoint_function(
  30. File "c:\users\raafeh\desktop\fyp\envfast\lib\site-packages\fastapi\routing.py", line 163, in run_endpoint_function
  31. return await dependant.call(**values)
  32. File "C:\Users\Raafeh\Desktop\FYP\main.py", line 27, in detect_objects
  33. output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]
  34. File "C:\Users\Raafeh\Desktop\FYP\main.py", line 27, in <listcomp>
  35. output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]
  36. IndexError: invalid index to scalar variable.

I am trying get the bounding boxes and Label out as the server response

答案1

得分: 0

基于快速搜索结果,这与FastAPI无关,而是由于尝试索引NumPy标量,例如整数或浮点数所致。

快速查看代码会建议以下行中的 i 是一个整数,这导致了错误:

output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]

也许用 layer_names[i - 1] 替换 layer_names[i[0] - 1] 可能会解决这个问题。

英文:

Based on a quick search, this has nothing to do with FastAPI but rather is caused by trying to index a NumPy scalar, an integer or float for example.

A quick look at the code would suggest that the i on the following line is an integer, and that causes the error:

  1. output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]

Maybe replacing layer_names[i[0] - 1] with layer_names[i - 1] might solve this.

答案2

得分: 0

layer_names[i[0] - 1] 替换为 layer_names[i - 1],但接着我遇到了另一个错误:

> cv2.error: 来自OpenCV代码的未知C++异常

这是我使用的OpenCV版本(4.7)引起的问题,我将其更改为4.6,API代码就正常工作了。

英文:

So my problem was solved by replacing layer_names[i[0] - 1] with layer_names[i - 1] but then I faced another error of

> cv2.error: Unknown C++ exception from OpenCV code

This was an issue with the OpenCV version I used which was 4.7, I changed it to 4.6 and volaa! My api code was working .

huangapple
  • 本文由 发表于 2023年5月7日 04:02:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定