From 4cfbfecf9dc1b2c456e5e744cc6455427945d063 Mon Sep 17 00:00:00 2001 From: zhanghuan <1262329256@qq.com> Date: Thu, 11 Sep 2025 14:23:45 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A8=E7=90=86=E9=98=B6=E6=AE=B5=E4=B8=8D?= =?UTF-8?q?=E9=9C=80=E8=A6=81=E5=81=9A=E5=9B=BE=E7=89=87=E9=A2=84=E5=A4=84?= =?UTF-8?q?=E7=90=86=EF=BC=8C=E7=9B=B4=E6=8E=A5=E6=89=94=E5=88=B0=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E9=87=8C=E9=9D=A2=E5=B0=B1=E5=A5=BD=E4=BA=86=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- classifier/food_classifier_app.py | 36 +++++++------------------------ 1 file changed, 8 insertions(+), 28 deletions(-) diff --git a/classifier/food_classifier_app.py b/classifier/food_classifier_app.py index 16f99f4..ac26116 100644 --- a/classifier/food_classifier_app.py +++ b/classifier/food_classifier_app.py @@ -57,19 +57,15 @@ class FoodClassifierApp: try: model_path = settings.INFERENCE_BEST_MODEL_PATH if os.path.exists(model_path): - # 创建模型实例 - self.model = create_food_cnn() + # 创建模型实例(不需要内部预处理,因为我们使用preprocess_image方法) + self.model = create_food_cnn(use_internal_preprocess=False) # 加载模型权重 self.model.load_state_dict(torch.load(model_path, map_location=self.device)) self.model.to(self.device) self.model.eval() # 设置为评估模式 - # 定义图像预处理(与训练时相同) - self.transform = transforms.Compose([ - transforms.Resize((32, 32),interpolation=transforms.InterpolationMode.BILINEAR), - transforms.ToTensor(), - transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) - ]) + # 不再需要定义transform,直接使用模型的preprocess_image方法 + self.transform = None print("PyTorch模型加载成功") else: @@ -502,7 +498,7 @@ class FoodClassifierApp: 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']) predicted_class = self.food_classes[prediction] @@ -549,25 +545,9 @@ class FoodClassifierApp: image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) pil_image = Image.fromarray(image_rgb) - # 应用预处理 - resize_transform = transforms.Resize((32,32),interpolation=transforms.InterpolationMode.BICUBIC) - resized_image = resize_transform(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 = self.model.preprocess_image(pil_image) input_tensor = input_tensor.to(self.device) # 进行预测