hungdang1610 commited on
Commit
3df4fe3
·
verified ·
1 Parent(s): aad7781

infer file

Browse files
Files changed (1) hide show
  1. models/inference.py +126 -0
models/inference.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mivolo_model import MiVOLOModel
2
+ import torch
3
+ import torchvision.transforms as transforms
4
+ from ultralytics import YOLO
5
+ from PIL import Image
6
+ import numpy as np
7
+ import os
8
+ import requests
9
+
10
+ def download_files_to_cache(urls, file_names, cache_dir_name="age_estimation"):
11
+ def download_file(url, save_path):
12
+ response = requests.get(url, stream=True)
13
+ response.raise_for_status() # Check if the download was successful
14
+
15
+ with open(save_path, 'wb') as file:
16
+ for chunk in response.iter_content(chunk_size=8192):
17
+ file.write(chunk)
18
+ print(f"File downloaded and saved to {save_path}")
19
+
20
+ # Định nghĩa đường dẫn tới thư mục cache
21
+ cache_dir = os.path.join(os.path.expanduser("~"), ".cache", cache_dir_name)
22
+
23
+ # Tạo thư mục cache nếu chưa tồn tại
24
+ os.makedirs(cache_dir, exist_ok=True)
25
+
26
+ # Tải các file nếu chưa tồn tại
27
+ for url, file_name in zip(urls, file_names):
28
+ save_path = os.path.join(cache_dir, file_name)
29
+ if not os.path.exists(save_path):
30
+ print(f"File {file_name} does not exist. Downloading...")
31
+ download_file(url, save_path)
32
+ else:
33
+ print(f"File {file_name} already exists at {save_path}")
34
+
35
+ # URL của các file cần tải
36
+ urls = [
37
+ "https://huggingface.co/hungdang1610/estimate_age/resolve/main/models/best_model_weights_10.pth?download=true",
38
+ "https://huggingface.co/hungdang1610/estimate_age/resolve/main/models/yolov8x_person_face.pt?download=true"
39
+ ]
40
+
41
+ # Định nghĩa tên file tương ứng để lưu
42
+ file_names = [
43
+ "best_model_weights_10.pth",
44
+ "yolov8x_person_face.pt"
45
+ ]
46
+ model_path = os.path.join(os.path.expanduser("~"), ".cache/age_estimation/best_model_weights_10.pth")
47
+ detection_path = os.path.join(os.path.expanduser("~"), ".cache/age_estimation/yolov8x_person_face.pt")
48
+ # Gọi hàm để tải file
49
+ download_files_to_cache(urls, file_names)
50
+
51
+ IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
52
+ IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
53
+ MEAN_TRAIN = 36.64
54
+ STD_TRAIN = 21.74
55
+ model = MiVOLOModel(
56
+ layers=(4, 4, 8, 2),
57
+ img_size=224,
58
+ in_chans=6,
59
+ num_classes=3,
60
+ patch_size=8,
61
+ stem_hidden_dim=64,
62
+ embed_dims=(192, 384, 384, 384),
63
+ num_heads=(6, 12, 12, 12),
64
+ ).to('cpu')
65
+ state = torch.load(model_path, map_location="cpu")
66
+ model.load_state_dict(state, strict=True)
67
+ # model = torch.load("models/model.pth")
68
+ transform_infer = transforms.Compose([
69
+ transforms.Resize((224, 224), interpolation=transforms.InterpolationMode.BICUBIC),
70
+ transforms.ToTensor(),
71
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
72
+ ])
73
+ detector = YOLO(detection_path)
74
+ def chunk_then_stack(image):
75
+ # image = Image.open(image_path).convert("RGB")
76
+ image_np = np.array(image)
77
+ results = detector.predict(image_np, conf=0.35)
78
+ for result in results:
79
+ boxes = result.boxes
80
+
81
+ # Khởi tạo các giá trị ban đầu
82
+ face_coords = [None, None, None, None]
83
+ person_coords = [None, None, None, None]
84
+
85
+ # Lấy tọa độ của bounding boxes
86
+ for i, box in enumerate(boxes.xyxy):
87
+ cls = int(boxes.cls[i].item())
88
+ x_min, y_min, x_max, y_max = map(int, box.tolist()) # Chuyển tọa độ sang int
89
+
90
+ # Lưu tọa độ vào đúng trường tương ứng
91
+ if cls == 1: # Face
92
+ face_coords = [x_min, y_min, x_max, y_max]
93
+ elif cls == 0: # Person
94
+ person_coords = [x_min, y_min, x_max, y_max]
95
+
96
+ return face_coords, person_coords
97
+
98
+
99
+
100
+ def tranfer_image(image):
101
+ # image = Image.open(img_path).convert('RGB')
102
+ face_coords, person_coords = chunk_then_stack(image)
103
+ face_image = image.crop((int(face_coords[0]), int(face_coords[1]), int(face_coords[2]), int(face_coords[3])))
104
+
105
+ person_image = image.crop((int(person_coords[0]), int(person_coords[1]), int(person_coords[2]), int(person_coords[3])))
106
+
107
+ # Resize ảnh về (224, 224)
108
+ face_image = face_image.resize((224, 224))
109
+ person_image = person_image.resize((224, 224))
110
+ face_image = transform_infer(face_image)
111
+ person_image = transform_infer(person_image)
112
+
113
+
114
+ image_ = torch.cat((face_image, person_image), dim=0)
115
+ return image_.unsqueeze(0)
116
+
117
+ image = Image.open("1.jpg").convert('RGB')
118
+ image_ = tranfer_image(image)
119
+ print(image_.shape)
120
+ import time
121
+ start_time = time.time()
122
+ output = model(image_)
123
+ output_mse = output[:, 2]
124
+ predicted_age = output_mse.item() *STD_TRAIN + MEAN_TRAIN
125
+ print("inference time: ", time.time() - start_time)
126
+ print("predicted_age: ", predicted_age)