File size: 11,049 Bytes
f61762b
 
 
 
 
 
2a9fe1b
f61762b
 
 
 
 
 
 
 
2a9fe1b
 
f61762b
2a9fe1b
f61762b
2a9fe1b
f61762b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9fe1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f61762b
2a9fe1b
f61762b
2a9fe1b
 
 
f61762b
 
 
2a9fe1b
f61762b
 
 
2a9fe1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f61762b
2a9fe1b
f61762b
8756727
2a9fe1b
 
f61762b
 
 
 
 
 
 
 
 
 
 
 
 
2a9fe1b
f61762b
2a9fe1b
 
 
 
 
 
 
 
 
 
 
f61762b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9fe1b
f61762b
 
2a9fe1b
f61762b
 
 
 
 
 
 
 
 
 
 
 
 
2a9fe1b
f61762b
 
 
 
2a9fe1b
 
f61762b
 
 
 
 
 
 
 
 
 
 
2a9fe1b
f61762b
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9fe1b
f61762b
2a9fe1b
f61762b
2a9fe1b
 
f61762b
 
 
 
 
2a9fe1b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
from anchor_utils import *
import os
import torch
import cv2
import numpy as np
from PIL import Image
from flask import Flask, request, send_file, make_response
from io import BytesIO

from flask import Flask, request, jsonify
from rembg import remove
import subprocess
import shutil

# Set up paths

image_dir = os.path.join(os.getcwd(), 'pifuhd', 'sample_images')
output_dir = os.path.join(os.getcwd(), "pifuhd", "results", "pifuhd_final", "recon")
ckpt_path = os.path.join(os.getcwd(), 'pifuhd', 'checkpoints', 'pifuhd.pt')

import io


# os.chdir(os.path.join(os.getcwd(), 'lightweight-human-pose-estimation.pytorch'))
print('cwd', os.getcwd())
print(os.listdir(os.getcwd()))

import sys
sys.path.append(os.path.join(os.getcwd(), 'lightweight-human-pose-estimation.pytorch'))
# Import necessary modules from lightweight human pose estimation
from models.with_mobilenet import PoseEstimationWithMobileNet
from modules.keypoints import extract_keypoints, group_keypoints
from modules.load_state import load_state
from modules.pose import Pose
import demo

# Initialize Flask app
app = Flask(__name__)

# Load pose estimation model
net = PoseEstimationWithMobileNet()
checkpoint = torch.load(os.path.join(os.getcwd(), "lightweight-human-pose-estimation.pytorch", "checkpoint_iter_370000.pth"), map_location='cpu')
load_state(net, checkpoint)
net = net.eval()

# Preprocess function to crop image
def get_rect(net, image_path, height_size=512):
    stride = 8
    upsample_ratio = 4
    num_keypoints = Pose.num_kpts
    img = cv2.imread(image_path, cv2.IMREAD_COLOR)
    orig_img = img.copy()
    heatmaps, pafs, scale, pad = demo.infer_fast(net, img, height_size, stride, upsample_ratio, cpu=True)

    total_keypoints_num = 0
    all_keypoints_by_type = []
    for kpt_idx in range(num_keypoints):
        total_keypoints_num += extract_keypoints(heatmaps[:, :, kpt_idx], all_keypoints_by_type, total_keypoints_num)

    pose_entries, all_keypoints = group_keypoints(all_keypoints_by_type, pafs)
    for kpt_id in range(all_keypoints.shape[0]):
        all_keypoints[kpt_id, 0] = (all_keypoints[kpt_id, 0] * stride / upsample_ratio - pad[1]) / scale
        all_keypoints[kpt_id, 1] = (all_keypoints[kpt_id, 1] * stride / upsample_ratio - pad[0]) / scale

    rects = []
    for n in range(len(pose_entries)):
        if len(pose_entries[n]) == 0:
            continue
        pose_keypoints = np.ones((num_keypoints, 2), dtype=np.int32) * -1
        valid_keypoints = []
        for kpt_id in range(num_keypoints):
            if pose_entries[n][kpt_id] != -1.0:
                pose_keypoints[kpt_id, 0] = int(all_keypoints[int(pose_entries[n][kpt_id]), 0])
                pose_keypoints[kpt_id, 1] = int(all_keypoints[int(pose_entries[n][kpt_id]), 1])
                valid_keypoints.append([pose_keypoints[kpt_id, 0], pose_keypoints[kpt_id, 1]])
        valid_keypoints = np.array(valid_keypoints)

        if pose_entries[n][10] != -1.0 or pose_entries[n][13] != -1.0:
            pmin = valid_keypoints.min(0)
            pmax = valid_keypoints.max(0)
            center = (0.5 * (pmax[:2] + pmin[:2])).astype(np.int32)
            radius = int(0.65 * max(pmax[0] - pmin[0], pmax[1] - pmin[1]))
        elif pose_entries[n][10] == -1.0 and pose_entries[n][13] == -1.0 and pose_entries[n][8] != -1.0 and pose_entries[n][11] != -1.0:
            center = (0.5 * (pose_keypoints[8] + pose_keypoints[11])).astype(np.int32)
            radius = int(1.45 * np.sqrt(((center[None, :] - valid_keypoints) ** 2).sum(1)).max(0))
            center[1] += int(0.05 * radius)
        else:
            center = np.array([img.shape[1] // 2, img.shape[0] // 2])
            radius = max(img.shape[1] // 2, img.shape[0] // 2)

        x1 = center[0] - radius
        y1 = center[1] - radius

        rects.append([x1, y1, 2 * radius, 2 * radius])

    return np.array(rects)

from pifuhd.apps.simple_test import run_pifuhd

# # Function to process image and generate mesh
# def process_image_pifuhd(image):
#     # Save the uploaded image
#     image_path = os.path.join(image_dir, "uploaded_image.png")
#     image.save(image_path)

#     # Preprocess the image to get rect
#     rects = get_rect(net, image_path)
#     rect_path = image_path.replace('.png', '_rect.txt')
#     np.savetxt(rect_path, rects, fmt='%d')

#     # Run PIFuHD
#     run_pifuhd(
#         input_path=image_dir,
#         out_path=output_dir,
#         ckpt_path=ckpt_path,
#         resolution=256,
#         use_rect=True
#     )

#     # Get the result object file path
#     file_name = "uploaded_image"
#     obj_path = os.path.join(output_dir, f"result_{file_name}_256.obj")

#     return obj_path


def process_image_pifuhd(image):
    # Define paths
    image_path = os.path.join(image_dir, "uploaded_image.png")
    obj_path = os.path.join(image_dir, "output.obj")
    
    # Save the uploaded image
    image.save(image_path)

    # Preprocess the image to get rect
    rects = get_rect(net, image_path)  # Assuming `net` is defined somewhere in your application
    rect_path = image_path.replace('.png', '_rect.txt')
    np.savetxt(rect_path, rects, fmt='%d')

    # Run PIFuHD and get the buffer
    obj_buffer = run_pifuhd(
        input_path=image_dir,
        ckpt_path=ckpt_path,
        resolution=256,
        use_rect=True
    )
    
    # # Save the first buffer as an OBJ file
    # with open(obj_path, 'wb') as f:
    #     f.write(obj_buffer[0].getvalue())
    
    return obj_buffer[0]



# # Flask route to process the image and return the OBJ file
# @app.route('/generate-mesh', methods=['POST'])
# def generate_mesh():
#     if 'file' not in request.files:
#         return "No file part", 400

#     file = request.files['file']
#     if file.filename == '':
#         return "No selected file", 400

#     if file:
#         # Convert the file to an image and process it
#         image = Image.open(file.stream)
#         obj_path = process_image_pifuhd(image)
        
#         # Return the OBJ file
#         return send_file(obj_path, as_attachment=True)

from flask import render_template

@app.route('/')
def pifuhd_page():
    return render_template('pifuhd.html')

@app.route('/generate-mesh', methods=['POST'])
def generate_mesh():
    if 'file' not in request.files:
        return "No file part", 400

    file = request.files['file']
    if file.filename == '':
        return "No selected file", 400

    if file:
        # Convert the file to an image and process it
        image = Image.open(file.stream)
        obj_buffer = process_image_pifuhd(image)
        
        # Create a BytesIO object to send the file
        obj_bytes_io = io.BytesIO(obj_buffer.getvalue())
        obj_bytes_io.seek(0)  # Ensure the buffer is at the start
        
        # Return the OBJ file in memory
        return send_file(
            obj_bytes_io,
            as_attachment=True,
            download_name='output.obj',
            mimetype='application/octet-stream'
        )



# Helper function to process images
def process_image(filename):
    # input_path = f'{os.getcwd()}/sample_images/{filename}'
    input_path = filename
    output_path = f'{os.getcwd()}/AnchorUDF/pics/my_test/RENDER/1/0_0_00.jpg'
    
    input_image = Image.open(input_path)

    # Determine new size
    if input_image.size[0] <= 600 or input_image.size[1] <= 600:
        new_size = (500, 500)
    elif input_image.size[0] >= 900 or input_image.size[1] >= 900:
        new_size = (1500, 1500)
    elif input_image.size[0] <= 900 or input_image.size[1] <= 900 and input_image.size[0] >= 700 or input_image.size[1] >= 700:
        new_size = (1000, 1000)
    else:
        new_size = input_image.size
    
    resized_image = input_image.resize(new_size, Image.LANCZOS)

    output_image = remove(resized_image)
    rgb_output_image = output_image.convert('RGB')
    
    # Save the processed image
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    rgb_output_image.save(output_path, quality=200, optimize=True)
    
    return output_path

# Helper function to generate mask
def generate_mask(image_path):
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, binary = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    mask = np.zeros_like(gray)
    cv2.drawContours(mask, contours, -1, 255, thickness=cv2.FILLED)

    mask_path = f"{os.getcwd()}/AnchorUDF/pics/my_test/MASK/1/0_0_00.png"
    cv2.imwrite(mask_path, mask)

    return mask_path


# Helper function for mesh processing and returning cleaned .ply file
def process_mesh(scale_factor=1.0, nb_neighbors=40, std_ratio=1.0, voxel_size=0.005):
    off_path = None
    al_obj = glob.glob(f'{os.getcwd()}/AnchorUDF/out/out/*.off')
    # print('all_obg', al_obj)
    for i in al_obj:
        if os.path.getsize(i) > 30000:
            print('found off file', i)
            off_path = i
            break

    if not off_path:
        raise FileNotFoundError("No suitable OFF file found.")

    filename = 'output'
    saved_ply_path = f"{off_path}_{filename}.ply"

    convert_off_to_ply(off_path, saved_ply_path, scale_factor)

    cleaned_ply_path, cleaned_pcd_path = remove_outliers_and_convert_to_point_cloud(saved_ply_path, nb_neighbors, std_ratio, voxel_size)

    return cleaned_ply_path, cleaned_pcd_path

# Helper function for garment inference
def run_garment_inference():
    # os.makedirs("out", exist_ok=True)
    print('garm working dir', os.getcwd())
    shutil.rmtree(os.path.join(os.getcwd(), "out"), ignore_errors=True)
    
    command = [
        "python", "-m", "apps.eval", "--results_path", "out", "--name", "out",
        "--dataroot", f'{os.getcwd()}/AnchorUDF/pics/my_test', "--test_folder_path", "1",
        "--load_netG_checkpoint_path", os.path.join(os.getcwd(), 'netG_epoch_59'),
        "--anchor", "--num_steps", "2", "--filter_val", "0.0075",
        "--max_dist", "0.05", "--num_gen_points", "850000", "--gamma", "1",
        "--aug_bri", "1.5", "--aug_con", "0.5", "--aug_sat", "0.5", "--aug_hue", "0.5"
    ]

    subprocess.run(command, cwd=os.path.join(os.getcwd(), "AnchorUDF"))
    print('garment generated!!!')

@app.route('/process', methods=['POST'])
def process():
    data = request.json
    filename = data.get('filename')

    if not filename:
        return jsonify({"error": "Filename is required"}), 400

    processed_image_path = process_image(filename)
    mask_path = generate_mask(processed_image_path)
    run_garment_inference()

    try:
        print('generating ply...')
        cleaned_ply_path = process_mesh(scale_factor=0.5, nb_neighbors=40, std_ratio=1.0, voxel_size=0.003)
        print('ply generated')
    except FileNotFoundError as e:
        import traceback
        traceback.print_exc()
        return jsonify({"error": str(e)}), 500

    return send_file(cleaned_ply_path, as_attachment=True)


# # Run the Flask app
# if __name__ == "__main__":
#     app.run(host='0.0.0.0', port=6100)