File size: 6,014 Bytes
1222018
2ce2e04
1222018
 
d900482
 
 
 
 
 
1222018
f531e56
1222018
 
f531e56
d900482
 
 
 
1222018
2ce2e04
 
1222018
 
f531e56
1222018
 
 
 
f531e56
1222018
 
 
 
 
d900482
 
 
 
 
f531e56
6f4e9ea
 
f531e56
 
 
d900482
 
 
f531e56
d900482
f531e56
d900482
f531e56
803d634
f531e56
803d634
f531e56
 
803d634
f531e56
803d634
f531e56
 
 
803d634
f531e56
 
803d634
f531e56
 
 
 
 
803d634
f531e56
 
 
803d634
f531e56
 
 
 
 
803d634
f531e56
 
 
 
 
 
803d634
f531e56
 
 
 
 
803d634
f531e56
 
 
 
 
803d634
f531e56
 
 
 
d900482
f531e56
 
 
2ce2e04
 
 
 
 
 
 
 
f531e56
 
 
d900482
 
 
 
 
 
 
 
 
 
 
 
1222018
f531e56
d900482
f531e56
d900482
6f4e9ea
 
1222018
f531e56
d900482
 
 
 
 
 
 
6f4e9ea
d900482
6f4e9ea
1222018
f531e56
 
 
d900482
 
 
 
 
 
 
 
 
f531e56
2ce2e04
f531e56
1222018
6f4e9ea
 
f531e56
 
 
d900482
1222018
d900482
 
 
 
 
6f4e9ea
 
1222018
f531e56
d900482
f531e56
d900482
1222018
 
 
 
f531e56
2ce2e04
 
 
 
1222018
 
2ce2e04
1222018
 
2ce2e04
 
 
 
 
 
1222018
d900482
 
 
6f4e9ea
 
 
 
d900482
 
 
 
 
6f4e9ea
f531e56
6f4e9ea
 
2ce2e04
 
 
 
 
d900482
 
 
 
2ce2e04
6f4e9ea
 
 
 
2ce2e04
 
f531e56
2ce2e04
 
 
 
f531e56
 
2ce2e04
 
d900482
 
 
 
 
6f4e9ea
f531e56
 
6f4e9ea
d900482
f531e56
2ce2e04
 
f531e56
 
 
6f4e9ea
 
 
d900482
 
 
 
 
 
 
6f4e9ea
d900482
 
 
 
f531e56
2ce2e04
6f4e9ea
 
d900482
 
 
 
6f4e9ea
 
d900482
6f4e9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
1222018
6f4e9ea
1222018
6f4e9ea
 
 
 
 
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
import numpy as np
from PIL import Image


def depth_to_pointcloud(
    depth,
    image=None,
    mask=None,
    stride=4
):
    """
    Converte mapa de profundidade em nuvem de pontos 3D.
    """

    # Depth precisa ser uma matriz 2D
    depth = np.asarray(
        depth,
        dtype=np.float32
    )

    depth = np.squeeze(depth)

    if depth.ndim != 2:
        raise ValueError(
            f"Formato de depth inesperado: {depth.shape}"
        )

    height, width = depth.shape

    # Grid de pixels
    y, x = np.mgrid[
        0:height:stride,
        0:width:stride
    ]

    z = depth[
        ::stride,
        ::stride
    ]

    # Pontos válidos
    valid = np.isfinite(z)

    # ==========================================
    # MÁSCARA DO OBJETO
    # ==========================================

    if mask is not None:

        if isinstance(mask, Image.Image):

            mask_image = mask

        else:

            mask_array = np.asarray(mask)

            # Se vier RGB/RGBA, converte corretamente
            if mask_array.ndim == 3:

                mask_array = mask_array[:, :, 0]

            mask_image = Image.fromarray(
                mask_array.astype(np.uint8)
            )

        # Sempre transforma em escala de cinza
        mask_image = mask_image.convert("L")

        # Mesmo tamanho da profundidade
        mask_image = mask_image.resize(
            (width, height),
            Image.Resampling.LANCZOS
        )

        mask_array = np.asarray(
            mask_image
        )

        print(
            "DEBUG máscara:",
            mask_array.shape,
            flush=True
        )

        object_mask = (
            mask_array[
                ::stride,
                ::stride
            ] > 128
        )

        print(
            "DEBUG object_mask:",
            object_mask.shape,
            flush=True
        )

        print(
            "DEBUG valid:",
            valid.shape,
            flush=True
        )

        valid = (
            valid
            & object_mask
        )

    # ==========================================
    # VERIFICA PONTOS
    # ==========================================

    if not np.any(valid):

        raise ValueError(
            "Nenhum ponto 3D válido foi encontrado. "
            "A máscara pode ter removido todo o objeto."
        )

    # ==========================================
    # FILTRA PONTOS
    # ==========================================

    x = x[valid].astype(
        np.float32
    )

    y = y[valid].astype(
        np.float32
    )

    z = z[valid].astype(
        np.float32
    )

    # ==========================================
    # NORMALIZA PROFUNDIDADE
    # ==========================================

    z_min = np.min(z)
    z_max = np.max(z)

    if z_max - z_min > 1e-8:

        z = (
            z - z_min
        ) / (
            z_max - z_min
        )

    else:

        z[:] = 0.5

    # ==========================================
    # CENTRALIZA X/Y
    # ==========================================

    x = (
        x - width / 2
    ) / width

    y = -(
        y - height / 2
    ) / height

    # ==========================================
    # ESCALA Z
    # ==========================================

    z = z * 2.0

    # ==========================================
    # XYZ
    # ==========================================

    points = np.stack(
        [
            x,
            y,
            z
        ],
        axis=1
    )

    # ==========================================
    # CORES
    # ==========================================

    colors = None

    if image is not None:

        image = image.convert("RGB")

        image = image.resize(
            (width, height)
        )

        image_array = np.asarray(
            image
        )

        sampled_colors = (
            image_array[
                ::stride,
                ::stride
            ]
        )

        colors = sampled_colors[
            valid
        ]

    return points, colors


def save_pointcloud_ply(
    filename,
    points,
    colors=None
):
    """
    Salva a nuvem de pontos no formato PLY.
    """

    points = np.asarray(
        points,
        dtype=np.float32
    )

    if (
        points.ndim != 2
        or points.shape[1] != 3
    ):

        raise ValueError(
            "points precisa ter formato (N, 3)."
        )

    if colors is not None:

        colors = np.asarray(colors)

        if len(colors) != len(points):

            raise ValueError(
                "A quantidade de cores precisa "
                "ser igual à quantidade de pontos."
            )

    with open(
        filename,
        "w",
        encoding="utf-8"
    ) as file:

        file.write("ply\n")
        file.write("format ascii 1.0\n")

        file.write(
            f"element vertex {len(points)}\n"
        )

        file.write("property float x\n")
        file.write("property float y\n")
        file.write("property float z\n")

        if colors is not None:

            file.write(
                "property uchar red\n"
            )

            file.write(
                "property uchar green\n"
            )

            file.write(
                "property uchar blue\n"
            )

        file.write("end_header\n")

        if colors is not None:

            for point, color in zip(
                points,
                colors
            ):

                x, y, z = point

                r, g, b = color

                file.write(
                    f"{x:.6f} "
                    f"{y:.6f} "
                    f"{z:.6f} "
                    f"{int(r)} "
                    f"{int(g)} "
                    f"{int(b)}\n"
                )

        else:

            for point in points:

                x, y, z = point

                file.write(
                    f"{x:.6f} "
                    f"{y:.6f} "
                    f"{z:.6f}\n"
                )