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",})不用这个包了 解析mask掩码
时间: 2024-02-14 09:29:51 浏览: 35
如果你不再使用 `sv.Detections` 包,而是希望解析 `mask` 掩码,可以使用 OpenCV 库来完成。以下是修改后的代码示例,用于解析 `mask` 掩码并生成结果列表:
```python
import io
import base64
import json
import cv2
import numpy as np
from PIL import Image
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.mask.astype(np.uint8)
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, 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)
```
在这个修改后的代码中,我假设你已经正确导入了所需的库和模块,并且 `sv.Detections` 包已被移除。我将 `mask` 数组转换为了 `np.uint8` 类型,并使用 OpenCV 的 `findContours()` 函数来找到轮廓。然后,通过遍历轮廓并保存每个轮廓的点,生成了结果列表。
请注意,这只是一个示例代码,可能需要根据你的实际需求进行调整和优化。
希望这能帮助到你!如果还有其他问题,请随时提问。