my model path:…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
my model path: C:\My_folders\proj\Repos\PPE_detection_app\application_ai\flutter_application_new\assets\model\best_float16.tflite my image path: C:\My_folders\proj\Repos\PPE_detection_app\application_ai\flutter_application_new\assets\image\IMG_20250317_171507.jpg
i found the code below which is inference for yolox. notice i am using YOLOv11m and there are many difference between them. dive deep in ultralytics (https://github.com/ultralytics/ultralytics) and understand the model difference and change code bellow to work on my model and give me inference for yolov11: #!/usr/bin/env python
import copy
import cv2 import numpy as np import tensorflow as tf
class YoloxTFLite(object): def init( self, model_path='yolox_nano.tflite', input_shape=(416, 416), class_score_th=0.3, nms_th=0.45, nms_score_th=0.1, with_p6=False, ): # 入力サイズ self.input_shape = input_shape
# 閾値
self.class_score_th = class_score_th
self.nms_th = nms_th
self.nms_score_th = nms_score_th
self.with_p6 = with_p6
# モデル読み込み
self.interpreter = tf.lite.Interpreter(model_path=model_path)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
def inference(self, image):
temp_image = copy.deepcopy(image)
image_height, image_width = image.shape[0], image.shape[1]
# 前処理
image, ratio = self._preprocess(temp_image, self.input_shape)
image = image.reshape(-1, 3, self.input_shape[0], self.input_shape[1])
# 推論実施
self.interpreter.set_tensor(
self.input_details[0]['index'],
image,
)
self.interpreter.invoke()
results = self.interpreter.get_tensor(self.output_details[0]['index'])
# 後処理
bboxes, scores, class_ids = self._postprocess(
results,
self.input_shape,
ratio,
self.nms_th,
self.nms_score_th,
image_width,
image_height,
p6=self.with_p6,
)
return bboxes, scores, class_ids
def _preprocess(self, image, input_size, swap=(2, 0, 1)):
if len(image.shape) == 3:
padded_image = np.ones(
(input_size[0], input_size[1], 3), dtype=np.uint8) * 114
else:
padded_image = np.ones(input_size, dtype=np.uint8) * 114
ratio = min(input_size[0] / image.shape[0],
input_size[1] / image.shape[1])
resized_image = cv2.resize(
image,
(int(image.shape[1] * ratio), int(image.shape[0] * ratio)),
interpolation=cv2.INTER_LINEAR,
)
resized_image = resized_image.astype(np.uint8)
padded_image[:int(image.shape[0] * ratio), :int(image.shape[1] *
ratio)] = resized_image
padded_image = padded_image.transpose(swap)
padded_image = np.ascontiguousarray(padded_image, dtype=np.float32)
return padded_image, ratio
def _postprocess(
self,
outputs,
img_size,
ratio,
nms_th,
nms_score_th,
max_width,
max_height,
p6=False,
):
grids = []
expanded_strides = []
if not p6:
strides = [8, 16, 32]
else:
strides = [8, 16, 32, 64]
hsizes = [img_size[0] // stride for stride in strides]
wsizes = [img_size[1] // stride for stride in strides]
for hsize, wsize, stride in zip(hsizes, wsizes, strides):
xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
grids.append(grid)
shape = grid.shape[:2]
expanded_strides.append(np.full((*shape, 1), stride))
grids = np.concatenate(grids, 1)
expanded_strides = np.concatenate(expanded_strides, 1)
outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
predictions = outputs[0]
boxes = predictions[:, :4]
scores = predictions[:, 4:5] * predictions[:, 5:]
boxes_xyxy = np.ones_like(boxes)
boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.
boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.
boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.
boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.
boxes_xyxy /= ratio
dets = self._multiclass_nms(
boxes_xyxy,
scores,
nms_thr=nms_th,
score_thr=nms_score_th,
)
bboxes, scores, class_ids = [], [], []
if dets is not None:
bboxes, scores, class_ids = dets[:, :4], dets[:, 4], dets[:, 5]
for bbox in bboxes:
bbox[0] = max(0, bbox[0])
bbox[1] = max(0, bbox[1])
bbox[2] = min(bbox[2], max_width)
bbox[3] = min(bbox[3], max_height)
return bboxes, scores, class_ids
def _nms(self, boxes, scores, nms_thr):
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= nms_thr)[0]
order = order[inds + 1]
return keep
def _multiclass_nms(
self,
boxes,
scores,
nms_thr,
score_thr,
class_agnostic=True,
):
if class_agnostic:
nms_method = self._multiclass_nms_class_agnostic
else:
nms_method = self._multiclass_nms_class_aware
return nms_method(boxes, scores, nms_thr, score_thr)
def _multiclass_nms_class_aware(self, boxes, scores, nms_thr, score_thr):
final_dets = []
num_classes = scores.shape[1]
for cls_ind in range(num_classes):
cls_scores = scores[:, cls_ind]
valid_score_mask = cls_scores > score_thr
if valid_score_mask.sum() == 0:
continue
else:
valid_scores = cls_scores[valid_score_mask]
valid_boxes = boxes[valid_score_mask]
keep = self._nms(valid_boxes, valid_scores, nms_thr)
if len(keep) > 0:
cls_inds = np.ones((len(keep), 1)) * cls_ind
dets = np.concatenate(
[
valid_boxes[keep], valid_scores[keep, None],
cls_inds
],
1,
)
final_dets.append(dets)
if len(final_dets) == 0:
return None
return np.concatenate(final_dets, 0)
def _multiclass_nms_class_agnostic(self, boxes, scores, nms_thr,
score_thr):
cls_inds = scores.argmax(1)
cls_scores = scores[np.arange(len(cls_inds)), cls_inds]
valid_score_mask = cls_scores > score_thr
if valid_score_mask.sum() == 0:
return None
valid_scores = cls_scores[valid_score_mask]
valid_boxes = boxes[valid_score_mask]
valid_cls_inds = cls_inds[valid_score_mask]
keep = self._nms(valid_boxes, valid_scores, nms_thr)
dets = None
if keep:
dets = np.concatenate([
valid_boxes[keep],
valid_scores[keep, None],
valid_cls_inds[keep, None],
], 1)
return dets
Okay, let's break down the changes needed to adapt this YOLOv11m inference code. This is a significant undertaking because YOLOv11m (and Ultralytics YOLOv8 in general) has a very different output structure than the older YOLO format this code expects.
Understanding the Differences (Ultralytics YOLOv8 vs. Older YOLO)
(batch_size, grid_height, grid_width, num_anchors, 5 + num_classes). The 5 represents (x, y, width, height, confidence). YOLOv8 outputs a tensor with shape (batch_size, num_detections, 6), where the 6 represents (x, y, width, height, confidence, class_id). The number of detections varies.Revised Code (YOLOv11m/YOLOv8 Compatible)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import cv2
import numpy as np
import tensorflow as tf
class Yolov11mTFLite(object):
def __init__(
self,
model_path='best_float16.tflite',
input_shape=(640, 640), # Standard YOLOv8 input size
class_score_th=0.3,
nms_th=0.45,
nms_score_th=0.1,
):
# Input size
self.input_shape = input_shape
# Thresholds
self.class_score_th = class_score_th
self.nms_th = nms_th
self.nms_score_th = nms_score_th
# Model loading
self.interpreter = tf.lite.Interpreter(model_path=model_path)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
def inference(self, image):
temp_image = copy.deepcopy(image)
image_height, image_width = image.shape[0], image.shape[1]
# Preprocessing
image, ratio = self._preprocess(temp_image, self.input_shape)
image = image.reshape(-1, 3, self.input_shape[0], self.input_shape[1])
# Inference
self.interpreter.set_tensor(
self.input_details[0]['index'],
image,
)
self.interpreter.invoke()
results = self.interpreter.get_tensor(self.output_details[0]['index'])
# Postprocessing
bboxes, scores, class_ids = self._postprocess(
results,
self.input_shape,
ratio,
self.nms_th,
self.nms_score_th,
image_width,
image_height,
)
return bboxes, scores, class_ids
def _preprocess(self, image, input_size):
"""Resizes and normalizes the image for YOLOv8."""
img = cv2.resize(image, input_size, interpolation=cv2.INTER_LINEAR)
img = img.astype(np.float32) / 255.0 # Normalize to 0-1
img = img.transpose((2, 0, 1)) # HWC to CHW
img = np.expand_dims(img, axis=0) # Add batch dimension
return img, 1.0 # Ratio is 1.0 since we resized directly
def _postprocess(
self,
outputs,
img_size,
ratio,
nms_th,
nms_score_th,
max_width,
max_height,
):
"""Postprocesses the YOLOv8 output."""
# Assuming the output tensor has shape (1, num_detections, 6)
# (x, y, width, height, confidence, class_id)
boxes = outputs[0][:, :4]
scores = outputs[0][:, 4]
class_ids = outputs[0][:, 5]
# Scale boxes back to original image size
boxes[:, 0] = boxes[:, 0] * max_width
boxes[:, 1] = boxes[:, 1] * max_height
boxes[:, 2] = boxes[:, 2] * max_width
boxes[:, 3] = boxes[:, 3] * max_height
# Filter by confidence score
valid_indices = scores > self.class_score_th
boxes = boxes[valid_indices]
scores = scores[valid_indices]
class_ids = class_ids[valid_indices].astype(int)
# Apply Non-Maximum Suppression (NMS)
keep = self._nms(boxes, scores, nms_th)
if keep is not None:
bboxes = boxes[keep]
scores = scores[keep]
class_ids = class_ids[keep]
else:
bboxes, scores, class_ids = [], [], []
return bboxes, scores, class_ids
def _nms(self, boxes, scores, nms_thr):
"""Non-Maximum Suppression."""
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
areas = (x2 - x1) * (y2 - y1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1)
h = np.maximum(0.0, yy2 - yy1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= nms_thr)[0]
order = order[inds + 1]
return keep if len(keep) > 0 else None
Key Changes and Explanations:
input_shape: Changed to (640, 640) which is a common input size for YOLOv8. Adjust if your model was trained with a different size._preprocess:
input_shape.np.expand_dims._postprocess:
(1, num_detections, 6).boxes, scores, and class_ids directly from the output tensor.class_score_th._nms function._nms: The NMS function remains largely the same, as the core logic is consistent.How to Use:
yolov11m_inference.py).model_path in the Yolov11mTFLite constructor points to your best_float16.tflite file.import cv2
from yolov11m_inference import Yolov11mTFLite
model_path = 'C:\\My_folders\\proj\\Repos\\PPE_detection_app\\application_ai\\flutter_application_new\\assets\\model\\best_float16.tflite'
image_path = 'C:\\My_folders\\proj\\Repos\\PPE_detection_app\\application_ai\\flutter_application_new\\assets\\image\\IMG_20250317_171507.jpg'
model = Yolov11mTFLite(model_path=model_path)
image = cv2.imread(image_path)
bboxes, scores, class_ids = model.inference(image)
# Draw bounding boxes on the image
for bbox, score, class_id in zip(bboxes, scores, class_ids):
x1, y1, x2, y2 = map(int, bbox)
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, f'{class_id}: {score:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.imshow('YOLOv11m Inference', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Important Considerations:
class_id values and the actual class names (e.g., 0 = helmet, 1 = vest, etc.). This information should be available from the training data or model documentation.best_float16.tflite model is indeed a TensorFlow Lite model exported from YOLOv8.This revised code provides a starting point for YOLOv11m/YOLOv8 inference with your TFLite model. You may need to fine-tune the parameters (e.g., class_score_th, nms_th) to achieve optimal results for your specific application. Remember to adapt the code based on the specifics of your model and dataset.