推理阶段不需要做图片预处理,直接扔到模型里面就好了。

This commit is contained in:
zhanghuan
2025-09-11 14:23:45 +08:00
parent d9280fd0a0
commit 4cfbfecf9d
+8 -28
View File
@@ -57,19 +57,15 @@ class FoodClassifierApp:
try: try:
model_path = settings.INFERENCE_BEST_MODEL_PATH model_path = settings.INFERENCE_BEST_MODEL_PATH
if os.path.exists(model_path): if os.path.exists(model_path):
# 创建模型实例 # 创建模型实例(不需要内部预处理,因为我们使用preprocess_image方法)
self.model = create_food_cnn() self.model = create_food_cnn(use_internal_preprocess=False)
# 加载模型权重 # 加载模型权重
self.model.load_state_dict(torch.load(model_path, map_location=self.device)) self.model.load_state_dict(torch.load(model_path, map_location=self.device))
self.model.to(self.device) self.model.to(self.device)
self.model.eval() # 设置为评估模式 self.model.eval() # 设置为评估模式
# 定义图像预处理(与训练时相同) # 不再需要定义transform,直接使用模型的preprocess_image方法
self.transform = transforms.Compose([ self.transform = None
transforms.Resize((32, 32),interpolation=transforms.InterpolationMode.BILINEAR),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
print("PyTorch模型加载成功") print("PyTorch模型加载成功")
else: else:
@@ -502,7 +498,7 @@ class FoodClassifierApp:
for i, img_info in enumerate(self.uploaded_images): for i, img_info in enumerate(self.uploaded_images):
# 预处理图片 # 预处理图片
if self.model is not None and self.transform is not None: if self.model is not None:
# 使用真实模型预测 # 使用真实模型预测
prediction, confidence = self.predict_with_model(img_info['image']) prediction, confidence = self.predict_with_model(img_info['image'])
predicted_class = self.food_classes[prediction] predicted_class = self.food_classes[prediction]
@@ -549,25 +545,9 @@ class FoodClassifierApp:
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(image_rgb) pil_image = Image.fromarray(image_rgb)
# 应用预处理 # 不再需要手动预处理,模型会自动处理
resize_transform = transforms.Resize((32,32),interpolation=transforms.InterpolationMode.BICUBIC) # 使用模型的预处理方法
resized_image = resize_transform(pil_image) input_tensor = self.model.preprocess_image(pil_image)
if isinstance(resized_image, Image.Image):
# 转换为tensor但不归一化
to_tensor = transforms.ToTensor()
resized_tensor = to_tensor(resized_image)
print(f"缩放后tensor形状: {resized_tensor.shape}")
# 打印前5个像素值(每个通道)
print("前5个像素值 (R, G, B):")
for i in range(min(5, resized_tensor.shape[1])):
r_val = resized_tensor[0, 0, i].item() * 255 # Red通道 (转换回0-255范围)
g_val = resized_tensor[1, 0, i].item() * 255 # Green通道
b_val = resized_tensor[2, 0, i].item() * 255 # Blue通道
print(f" 像素[0,{i}]: R={r_val:.2f}, G={g_val:.2f}, B={b_val:.2f}")
input_tensor = self.transform(pil_image).unsqueeze(0) # 添加batch维度
input_tensor = input_tensor.to(self.device) input_tensor = input_tensor.to(self.device)
# 进行预测 # 进行预测