context.get拿不到值
时间: 2024-05-26 12:18:11 浏览: 8
context.get() 是用于获取对话上下文中的值的方法,如果返回 None,可能是因为上下文中没有设置该键或键的值为 None。您可以尝试检查一下在对话开始时是否设置了上下文,或者是否在上下文中正确地设置了该键和对应的值。另外,您也可以尝试使用 context.set() 方法来设置一个新的键值对。如果仍然无法解决问题,您可以提供更多的上下文信息以便我更好地帮助您解决问题。
相关问题
import json import base64 from PIL import Image import io import cv2 import numpy as np from ultralytics import YOLO import supervision as sv def init_context(context): context.logger.info("Init context... 0%") model_path = "yolov8m-seg.pt" # YOLOV8模型放在nuclio目录下构建 model = YOLO(model_path) # Read the DL model context.user_data.model = model context.logger.info("Init context...100%") def handler(context, event): context.logger.info("Run yolo-v8-seg model") data = event.body buf = io.BytesIO(base64.b64decode(data["image"])) threshold = float(data.get("threshold", 0.35)) context.user_data.model.conf = threshold image = Image.open(buf) yolo_results = context.user_data.model(image, conf=threshold)[0] labels = yolo_results.names detections = sv.Detections.from_yolov8(yolo_results) detections = detections[detections.confidence > threshold] masks = detections.xy conf = detections.confidence class_ids = detections.class_id results = [] if masks.shape[0] > 0: for label, score, mask in zip(class_ids, conf, masks): # 将mask转换为轮廓 contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: points = [] for point in contour: x = point[0][0] y = point[0][1] points.append([x, y]) results.append({ "confidence": str(score), "label": labels.get(label, "unknown"), "points": points, "type": "polygon",}) return context.Response(body=json.dumps(results), headers={}, content_type='application/json', status_code=200)不用supervision 包 用别的方式解析
如果你不想使用 `supervision` 包,可以使用其他方式解析 `masks`。
以下是修改后的代码示例,使用 OpenCV 库中的 `cv2.findContours()` 函数和 `cv2.drawContours 函数来解析 `masks` 并结果列表:
```python
import json
import base64
from PIL import Image
import io
import cv2
import numpy as np
from ultralytics import YOLO
def init_context(context):
context.logger.info("Init context... 0%")
model_path = "yolov8m-seg.pt" # YOLOV8模型放在nuclio目录下构建
model = YOLO(model_path)
# Read the DL model
context.user_data.model = model
context.logger.info("Init context...100%")
def handler(context, event):
context.logger.info("Run yolo-v8-seg model")
data = event.body
buf = io.BytesIO(base64.b64decode(data["image"]))
threshold = float(data.get("threshold", 0.35))
context.user_data.model.conf = threshold
image = Image.open(buf)
yolo_results = context.user_data.model(image, conf=threshold)[0]
labels = yolo_results.names
detections = yolo_results.pred
results = []
for detection in detections:
class_id = int(detection[5])
score = detection[4]
mask = detection[6]
# 将mask转换为轮廓
_, contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
points = []
for point in contour:
x = point[0][0]
y = point[0][1]
points.append([x, y])
results.append({
"confidence": str(score),
"label": labels[class_id],
"points": points,
"type": "polygon"
})
return context.Response(body=json.dumps(results), headers={},
content_type='application/json', status_code=200)
```
在这个修改后的代码中,我假设你已经正确导入了所需的库和模块,并且使用了 `YOLO` 类来获取预测结果。
我修改了 `handler` 函数中的代码,将 `detections` 对象中的每个检测结果进行遍历。对于每个检测结果,我提取了类别ID、置信度和掩码。然后,使用 `cv2.findContours()` 函数将掩码转换为轮廓,并使用 `cv2.drawContours()` 函数绘制轮廓。
最后,我将每个检测结果的类别、置信度和轮廓点添加到结果列表中。
请注意,这只是一个示例代码,可能需要根据你的实际需求进行调整和优化。
希望这能帮助到你!如果还有其他问题,请随时提问。
@Overridepublic void invoke(Map<Integer, String> data, AnalysisContext context) { if (context.readRowHolder().getRowIndex() < context.readSheetHolder().getSheet().getHeadLineMun()) { // 当前行是表头行,存储表头信息 for (Map.Entry<Integer, String> entry : data.entrySet()) { int columnIndex = entry.getKey(); String columnName = entry.getValue(); headMap.put(columnIndex, columnName); } } else { // 当前行是数据行,进行数据处理 for (Map.Entry<Integer, String> entry : data.entrySet()) { int columnIndex = entry.getKey(); String columnValue = entry.getValue(); String columnName = headMap.get(columnIndex); // 处理数据 } }}解释一下这些代码
这段代码是使用EasyExcel读取Excel文件并解析数据的核心逻辑,具体解释如下:
```java
@Override
public void invoke(Map<Integer, String> data, AnalysisContext context) {
if (context.readRowHolder().getRowIndex() < context.readSheetHolder().getSheet().getHeadLineMun()) {
// 当前行是表头行,存储表头信息
for (Map.Entry<Integer, String> entry : data.entrySet()) {
int columnIndex = entry.getKey();
String columnName = entry.getValue();
headMap.put(columnIndex, columnName);
}
} else {
// 当前行是数据行,进行数据处理
for (Map.Entry<Integer, String> entry : data.entrySet()) {
int columnIndex = entry.getKey();
String columnValue = entry.getValue();
String columnName = headMap.get(columnIndex);
// 处理数据
}
}
}
```
1. `public void invoke(Map<Integer, String> data, AnalysisContext context)`:该方法是实现`AnalysisEventListener`接口时必须实现的方法,用于处理Excel文件中的每一行数据。当读取到一行数据时,该方法会被调用一次。
2. `if (context.readRowHolder().getRowIndex() < context.readSheetHolder().getSheet().getHeadLineMun())`:判断当前行是否为表头行。通过`context.readRowHolder().getRowIndex()`获取当前行的索引,通过`context.readSheetHolder().getSheet().getHeadLineMun()`获取表头所在的开始行索引,如果当前行的索引小于表头开始行索引则说明当前行是表头行。
3. `for (Map.Entry<Integer, String> entry : data.entrySet())`:遍历当前行的所有列数据。`data`是当前行的数据Map,key为列索引,value为该列的数据值。通过`entry.getKey()`获取列索引,通过`entry.getValue()`获取列数据值。
4. `int columnIndex = entry.getKey();`:获取当前列的索引。
5. `String columnName = entry.getValue();`:获取当前列的数据值。
6. `headMap.put(columnIndex, columnName);`:将当前列的索引和数据值存储在`headMap`中。`headMap`是一个`TreeMap`,用于存储表头信息。在`invokeHeadMap()`方法中,会将所有的表头信息存储在`headMap`中。
7. `String columnValue = entry.getValue();`:获取当前列的数据值。
8. `String columnName = headMap.get(columnIndex);`:根据当前列的索引获取表头的名称。
9. `// 处理数据`:根据表头名称和列数据值,进行数据处理。
总的来说,这段代码的作用是:判断当前行是否为表头行,如果是则将表头信息存储在`headMap`中;如果不是则进行数据处理。在数据处理时,根据表头名称和列数据值进行处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)