提高视频帧率
This commit is contained in:
@@ -12,7 +12,7 @@ from app.models import Detection
|
||||
class PythonModelDetector:
|
||||
"""Object detector using native Python models"""
|
||||
|
||||
def __init__(self, model_name: str, model_path: str, input_width: int, input_height: int, color: int = 0x00FF00):
|
||||
def __init__(self, model_name: str, model_path: str, input_width: int, input_height: int, color: int = 0x00FF00, model_config: dict = None):
|
||||
"""
|
||||
Initialize detector with Python model
|
||||
|
||||
@@ -22,11 +22,13 @@ class PythonModelDetector:
|
||||
input_width: Input width for the model
|
||||
input_height: Input height for the model
|
||||
color: RGB color for detection boxes (default: green)
|
||||
model_config: Additional configuration to pass to the model
|
||||
"""
|
||||
self.model_name = model_name
|
||||
self.input_width = input_width
|
||||
self.input_height = input_height
|
||||
self.color = color
|
||||
self.model_config = model_config or {}
|
||||
|
||||
# Convert color from RGB to BGR (OpenCV uses BGR)
|
||||
self.color_bgr = ((color & 0xFF) << 16) | (color & 0xFF00) | ((color >> 16) & 0xFF)
|
||||
@@ -72,8 +74,18 @@ class PythonModelDetector:
|
||||
if not hasattr(model_module, "Model"):
|
||||
raise AttributeError(f"Model module must define a 'Model' class: {model_path}")
|
||||
|
||||
# Create model instance
|
||||
self.model = model_module.Model()
|
||||
# Create model instance with config
|
||||
# Try to pass config to model constructor if it accepts parameters
|
||||
import inspect
|
||||
model_class = model_module.Model
|
||||
sig = inspect.signature(model_class.__init__)
|
||||
|
||||
if len(sig.parameters) > 1: # Has parameters beyond 'self'
|
||||
# Pass all config as keyword arguments
|
||||
self.model = model_class(**self.model_config)
|
||||
else:
|
||||
# No parameters, create without arguments
|
||||
self.model = model_class()
|
||||
|
||||
# Check if model has the required methods
|
||||
if not hasattr(self.model, "predict"):
|
||||
@@ -113,18 +125,16 @@ class PythonModelDetector:
|
||||
# Original image dimensions
|
||||
img_height, img_width = img.shape[:2]
|
||||
|
||||
# Preprocess image
|
||||
processed_img = self.preprocess(img)
|
||||
|
||||
# Measure inference time
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
# Run inference using model's predict method
|
||||
# Note: Pass original image to model, let it handle preprocessing
|
||||
# Expected return format from model's predict:
|
||||
# List of dicts with keys: 'bbox', 'class_id', 'confidence'
|
||||
# bbox: (x, y, w, h) normalized [0-1]
|
||||
model_results = self.model.predict(processed_img)
|
||||
model_results = self.model.predict(img)
|
||||
|
||||
# Calculate inference time in milliseconds
|
||||
inference_time = (time.time() - start_time) * 1000
|
||||
@@ -279,13 +289,22 @@ class ModelManager:
|
||||
# Use color from palette
|
||||
color = palette[i % len(palette)]
|
||||
|
||||
# Extract model-specific config (model_file, model_name, etc.)
|
||||
# These will be passed to the Model class __init__
|
||||
model_init_config = {}
|
||||
if "model_file" in model_config:
|
||||
model_init_config["model_file"] = model_config["model_file"]
|
||||
if "display_name" in model_config:
|
||||
model_init_config["model_name"] = model_config["display_name"]
|
||||
|
||||
# Create detector for Python model
|
||||
detector = PythonModelDetector(
|
||||
model_name=name,
|
||||
model_path=path,
|
||||
input_width=size[0],
|
||||
input_height=size[1],
|
||||
color=color
|
||||
color=color,
|
||||
model_config=model_init_config
|
||||
)
|
||||
|
||||
self.models[name] = detector
|
||||
|
||||
@@ -129,17 +129,13 @@ async def detect_file(
|
||||
model_name: str,
|
||||
file: UploadFile = File(...)
|
||||
):
|
||||
# 1. 打印 model_name(直接打印字符串即可)
|
||||
print(f"接收到的 model_name: {model_name}")
|
||||
|
||||
# 2. 打印 file 的基本信息(文件名、内容类型等)
|
||||
print(f"文件名: {file.filename}")
|
||||
print(f"文件内容类型: {file.content_type}") # 例如 image/jpeg、text/plain 等
|
||||
"""Detect objects in an uploaded image file"""
|
||||
print(f"接收到的 model_name: {model_name}")
|
||||
print(f"文件名: {file.filename}")
|
||||
print(f"文件内容类型: {file.content_type}")
|
||||
|
||||
global model_manager
|
||||
|
||||
|
||||
|
||||
if not model_manager:
|
||||
raise HTTPException(status_code=500, detail="Model manager not initialized")
|
||||
|
||||
@@ -151,16 +147,39 @@ async def detect_file(
|
||||
# Read uploaded file
|
||||
try:
|
||||
contents = await file.read()
|
||||
print(f"文件大小: {len(contents)} 字节")
|
||||
|
||||
if len(contents) == 0:
|
||||
raise HTTPException(status_code=400, detail="Empty file")
|
||||
|
||||
nparr = np.frombuffer(contents, np.uint8)
|
||||
print(f"numpy数组形状: {nparr.shape}, dtype: {nparr.dtype}")
|
||||
|
||||
image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
||||
|
||||
if image is None:
|
||||
raise HTTPException(status_code=400, detail="Invalid image data")
|
||||
print("错误: cv2.imdecode 返回 None")
|
||||
raise HTTPException(status_code=400, detail="Invalid image data - failed to decode")
|
||||
|
||||
print(f"解码后图像形状: {image.shape}, dtype: {image.dtype}")
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"处理图像时出错: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise HTTPException(status_code=400, detail=f"Failed to process image: {str(e)}")
|
||||
|
||||
# Run detection
|
||||
detections, inference_time = detector.detect(image)
|
||||
try:
|
||||
detections, inference_time = detector.detect(image)
|
||||
print(f"检测完成: 找到 {len(detections)} 个目标, 耗时 {inference_time:.2f}ms")
|
||||
except Exception as e:
|
||||
print(f"推理过程中出错: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise HTTPException(status_code=500, detail=f"Detection failed: {str(e)}")
|
||||
|
||||
return DetectionResponse(
|
||||
model_name=model_name,
|
||||
|
||||
Reference in New Issue
Block a user