• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Pablo1990 / pyVertexModel / 12007661861

25 Nov 2024 10:04AM UTC coverage: 0.781% (-0.002%) from 0.783%
12007661861

push

github

Pablo1990
improving plots

0 of 1027 branches covered (0.0%)

Branch coverage included in aggregate %.

0 of 27 new or added lines in 1 file covered. (0.0%)

4 existing lines in 1 file now uncovered.

51 of 5502 relevant lines covered (0.93%)

0.01 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/pyVertexModel/analysis/analyse_simulation.py
1
import os
×
2
import pickle
×
3
import cv2
×
4

5
import numpy as np
×
6
import pandas as pd
×
7
from matplotlib import pyplot as plt
×
8
from scipy.optimize import curve_fit
×
9

10
from src.pyVertexModel.algorithm.vertexModel import VertexModel, logger
×
11
from src.pyVertexModel.util.utils import load_state, load_variables, save_variables
×
12

13

14
def analyse_simulation(folder):
×
15
    """
16
    Analyse the simulation results
17
    :param folder:
18
    :return:
19
    """
20

21
    # Check if the pkl file exists
22
    if not os.path.exists(os.path.join(folder, 'features_per_time.pkl')):
×
23
        # return None, None, None, None
24
        vModel = VertexModel(create_output_folder=False)
×
25

26
        features_per_time = []
×
27
        features_per_time_all_cells = []
×
28

29
        # Go through all the files in the folder
30
        all_files = os.listdir(folder)
×
31

32
        # Sort files by date
33
        all_files = sorted(all_files, key=lambda x: os.path.getmtime(os.path.join(folder, x)))
×
34

35
        # if all_files has less than 20 files, return None
36
        if len(all_files) < 20:
×
37
            return None, None, None, None
×
38

39
        for file_id, file in enumerate(all_files):
×
40
            if file.endswith('.pkl') and not file.__contains__('data_step_before_remodelling') and not file.__contains__('recoil'):
×
41
                # Load the state of the model
42
                load_state(vModel, os.path.join(folder, file))
×
43

44
                # Analyse the simulation
45
                all_cells, avg_cells = vModel.analyse_vertex_model()
×
46
                features_per_time_all_cells.append(all_cells)
×
47
                features_per_time.append(avg_cells)
×
48

49
                # # Create a temporary directory to store the images
50
                # temp_dir = os.path.join(folder, 'images')
51
                # if not os.path.exists(temp_dir):
52
                #     os.mkdir(temp_dir)
53
                # vModel.screenshot(temp_dir)
54

55
                # temp_dir = os.path.join(folder, 'images_wound_edge')
56
                # if not os.path.exists(temp_dir):
57
                #     os.mkdir(temp_dir)
58
                # _, debris_cells = vModel.geo.compute_wound_centre()
59
                # list_of_cell_distances_top = vModel.geo.compute_cell_distance_to_wound(debris_cells, location_filter=0)
60
                # alive_cells = [cell.ID for cell in vModel.geo.Cells if cell.AliveStatus == 1]
61
                # wound_edge_cells = []
62
                # for cell_num, cell_id in enumerate(alive_cells):
63
                #     if list_of_cell_distances_top[cell_num] == 1:
64
                #         wound_edge_cells.append(cell_id)
65
                # vModel.screenshot(temp_dir, wound_edge_cells)
66

67
        if not features_per_time:
×
68
            return None, None, None, None
×
69

70
        # Export to xlsx
71
        features_per_time_all_cells_df = pd.DataFrame(np.concatenate(features_per_time_all_cells),
×
72
                                                      columns=features_per_time_all_cells[0].columns)
73
        features_per_time_all_cells_df.sort_values(by='time', inplace=True)
×
74
        features_per_time_all_cells_df.to_excel(os.path.join(folder, 'features_per_time_all_cells.xlsx'))
×
75

76
        features_per_time_df = pd.DataFrame(features_per_time)
×
77
        features_per_time_df.sort_values(by='time', inplace=True)
×
78
        features_per_time_df.to_excel(os.path.join(folder, 'features_per_time.xlsx'))
×
79

80
        # Save dataframes to a single pkl
NEW
81
        with open(os.path.join(folder, 'features_per_time.pkl'), 'wb') as f:
×
NEW
82
            pickle.dump(features_per_time_df, f)
×
NEW
83
            pickle.dump(None, f)
×
NEW
84
            pickle.dump(None, f)
×
NEW
85
            pickle.dump(features_per_time_all_cells_df, f)
×
86
    else:
87
        # Load dataframes from pkl
NEW
88
        with open(os.path.join(folder, 'features_per_time.pkl'), 'rb') as f:
×
NEW
89
            features_per_time_df = pickle.load(f)
×
NEW
90
            important_features = pickle.load(f)
×
NEW
91
            post_wound_features = pickle.load(f)
×
NEW
92
            features_per_time_all_cells_df = pickle.load(f)
×
93

94
        # load 'before_ablation.pkl' file
NEW
95
        vModel = VertexModel(create_output_folder=False)
×
NEW
96
        load_state(vModel, os.path.join(folder, 'before_ablation.pkl'))
×
97

98
        # Obtain pre-wound features
99
        try:
×
100
            pre_wound_features = features_per_time_df['time'][features_per_time_df['time'] < vModel.set.TInitAblation]
×
101
            pre_wound_features = features_per_time_df[features_per_time_df['time'] ==
×
102
                                                      pre_wound_features.iloc[-1]]
103
        except Exception as e:
×
NEW
104
            pre_wound_features = features_per_time_df['time'][features_per_time_df['time'] > features_per_time_df['time'][0]]
×
NEW
105
            pre_wound_features = features_per_time_df[features_per_time_df['time'] ==
×
106
                                                      pre_wound_features.iloc[0]]
107

108
        # Obtain post-wound features
109
        post_wound_features = features_per_time_df[features_per_time_df['time'] >= vModel.set.TInitAblation]
×
110

111
        if not post_wound_features.empty:
×
112
            # Reset time to ablation time.
113
            post_wound_features.loc[:, 'time'] = post_wound_features['time'] - vModel.set.TInitAblation
×
114

115
            # Compare post-wound features with pre-wound features in percentage
116
            for feature in post_wound_features.columns:
×
117
                if np.any(np.isnan(pre_wound_features[feature])) or np.any(np.isnan(post_wound_features[feature])):
×
118
                    continue
×
119

NEW
120
                if 'indentation' in feature:
×
NEW
121
                    post_wound_features.loc[:, feature] = (post_wound_features[feature] - np.array(
×
122
                        pre_wound_features[feature]))
NEW
123
                    continue
×
124

125
                if feature == 'time':
×
126
                    continue
×
127
                post_wound_features.loc[:, feature] = (post_wound_features[feature] / np.array(
×
128
                    pre_wound_features[feature])) * 100
129

130
            # Export to xlsx
131
            post_wound_features.to_excel(os.path.join(folder, 'post_wound_features.xlsx'))
×
132

133
            important_features = calculate_important_features(post_wound_features)
×
134
        else:
135
            important_features = {
×
136
                'max_recoiling_top': np.nan,
137
                'max_recoiling_time_top': np.nan,
138
                'min_height_change': np.nan,
139
                'min_height_change_time': np.nan,
140
            }
141

142
        # Export to xlsx
143
        df = pd.DataFrame([important_features])
×
144
        df.to_excel(os.path.join(folder, 'important_features.xlsx'))
×
145

146

147
    # Plot wound area top evolution over time and save it to a file
148
    plot_feature(folder, post_wound_features, name='wound_area_top')
×
149
    plot_feature(folder, post_wound_features, name='num_cells_wound_edge_top')
×
NEW
150
    plot_feature(folder, post_wound_features, name='wound_height')
×
NEW
151
    try:
×
NEW
152
        plot_feature(folder, post_wound_features, name='wound_indentation_top')
×
NEW
153
        plot_feature(folder, post_wound_features, name='wound_indentation_bottom')
×
NEW
154
    except Exception as e:
×
NEW
155
        pass
×
NEW
156
    plot_feature(folder, post_wound_features, name='wound_area_bottom')
×
157

158
    return features_per_time_df, post_wound_features, important_features, features_per_time_all_cells_df
×
159

160

161
def plot_feature(folder, post_wound_features, name='wound_area_top'):
×
162
    """
163
    Plot a feature and save it to a file
164
    :param folder:
165
    :param post_wound_features:
166
    :param name:
167
    :return:
168
    """
169
    plt.figure()
×
170
    plt.plot(post_wound_features['time'], post_wound_features[name])
×
171
    plt.xlabel('Time (h)')
×
172
    plt.ylabel(name)
×
173
    # Change axis limits
174
    if np.max(post_wound_features['time']) > 60:
×
175
        #plt.xlim([0, np.max(post_wound_features['time'])])
NEW
176
        plt.xlim([0, 60])
×
177
    else:
178
        plt.xlim([0, 60])
×
179

NEW
180
    if not name.startswith('wound_indentation_'):
×
NEW
181
        plt.ylim([0, 250])
×
182
    plt.savefig(os.path.join(folder, name + '.png'))
×
183
    plt.close()
×
184

185

186
def calculate_important_features(post_wound_features):
×
187
    """
188
    Calculate important features from the post-wound features
189
    :param post_wound_features:
190
    :return:
191
    """
192
    # Obtain important features for post-wound
193
    if not post_wound_features['wound_area_top'].empty and post_wound_features['time'].iloc[-1] > 4:
×
194
        important_features = {
×
195
            'max_recoiling_top': np.max(post_wound_features['wound_area_top']),
196
            'max_recoiling_time_top': np.array(post_wound_features['time'])[
197
                np.argmax(post_wound_features['wound_area_top'])],
198
            'min_recoiling_top': np.min(post_wound_features['wound_area_top']),
199
            'min_recoiling_time_top': np.array(post_wound_features['time'])[
200
                np.argmin(post_wound_features['wound_area_top'])],
201
            'min_height_change': np.min(post_wound_features['wound_height']),
202
            'min_height_change_time': np.array(post_wound_features['time'])[
203
                np.argmin(post_wound_features['wound_height'])],
204
            'last_area_top': post_wound_features['wound_area_top'].iloc[-1],
205
            'last_area_time_top': post_wound_features['time'].iloc[-1],
206
        }
207

208
        # Extrapolate features to a given time
209
        times_to_extrapolate = {3.0, 6.0, 9.0, 12.0, 15.0, 21.0, 30.0, 36.0, 45.0, 51.0, 60.0}
×
210
        columns_to_extrapolate = {'wound_area_top', 'wound_height'}  # post_wound_features.columns
×
211
        for feature in columns_to_extrapolate:
×
212
            for time in times_to_extrapolate:
×
213
                # Extrapolate results to a given time
214
                important_features[feature + '_extrapolated_' + str(time)] = np.interp(time,
×
215
                                                                                       post_wound_features['time'],
216
                                                                                       post_wound_features[feature])
217

218
        # # Get ratio from area the first time to the other times
219
        # for time in times_to_extrapolate:
220
        #     if time != 6.0:
221
        #         important_features['ratio_area_top_' + str(time)] = (
222
        #                 important_features['wound_area_top_extrapolated_' + str(time)] /
223
        #                 important_features['wound_area_top_extrapolated_6.0'])
224

225
    else:
226
        important_features = {
×
227
            'max_recoiling_top': np.nan,
228
            'max_recoiling_time_top': np.nan,
229
            'min_height_change': np.nan,
230
            'min_height_change_time': np.nan,
231
        }
232

233
    return important_features
×
234

235

236
def analyse_edge_recoil(file_name_v_model, type_of_ablation='recoil_edge_info_apical', n_ablations=2, location_filter=0, t_end=0.5):
×
237
    """
238
    Analyse how much an edge recoil if we ablate an edge of a cell
239
    :param type_of_ablation:
240
    :param t_end: Time to iterate after the ablation
241
    :param file_name_v_model: file nae of the Vertex model
242
    :param n_ablations: Number of ablations to perform
243
    :param location_filter: Location filter
244
    :return:
245
    """
246

247
    v_model = VertexModel(create_output_folder=False)
×
248
    load_state(v_model, file_name_v_model)
×
249

250
    # Cells to ablate
251
    # cell_to_ablate = np.random.choice(possible_cells_to_ablate, 1)
252
    cell_to_ablate = [v_model.geo.Cells[0]]
×
253

254
    #Pick the neighbouring cell to ablate
255
    neighbours = cell_to_ablate[0].compute_neighbours(location_filter)
×
256

257
    # Random order of neighbours
258
    np.random.seed(0)
×
259
    np.random.shuffle(neighbours)
×
260

261
    list_of_dicts_to_save = []
×
262
    for num_ablation in range(n_ablations):
×
263
        load_state(v_model, file_name_v_model)
×
264
        try:
×
265
            vars = load_variables(file_name_v_model.replace('before_ablation.pkl', type_of_ablation + '.pkl'))
×
266
            list_of_dicts_to_save_loaded = vars['recoiling_info_df_apical']
×
267

268
            cell_to_ablate_ID = list_of_dicts_to_save_loaded['cell_to_ablate'][num_ablation]
×
269
            neighbour_to_ablate_ID = list_of_dicts_to_save_loaded['neighbour_to_ablate'][num_ablation]
×
270
            edge_length_init = list_of_dicts_to_save_loaded['edge_length_init'][num_ablation]
×
271
            edge_length_final = list_of_dicts_to_save_loaded['edge_length_final'][num_ablation]
×
272
            if 'edge_length_final_normalized' in list_of_dicts_to_save_loaded:
×
273
                edge_length_final_normalized = list_of_dicts_to_save_loaded['edge_length_final_normalized'][
×
274
                    num_ablation]
275
            else:
276
                edge_length_final_normalized = (edge_length_final - edge_length_init) / edge_length_init
×
277

278
            initial_recoil = list_of_dicts_to_save_loaded['initial_recoil_in_s'][num_ablation]
×
279
            K = list_of_dicts_to_save_loaded['K'][num_ablation]
×
280
            scutoid_face = list_of_dicts_to_save_loaded['scutoid_face'][num_ablation]
×
281
            distance_to_centre = list_of_dicts_to_save_loaded['distance_to_centre'][num_ablation]
×
282
            if 'time_steps' in list_of_dicts_to_save_loaded:
×
283
                time_steps = list_of_dicts_to_save_loaded['time_steps'][num_ablation]
×
284
            else:
285
                time_steps = np.arange(0, len(edge_length_final)) * 6
×
286

287
            if edge_length_final[0] == 0:
×
288
                # Remove the first element
289
                edge_length_final = edge_length_final[1:]
×
290
                time_steps = time_steps[1:]
×
291
        except Exception as e:
×
292
            logger.info('Performing the analysis...' + str(e))
×
293
            # Change name of folder and create it
294
            if type_of_ablation == 'recoil_info_apical':
×
295
                v_model.set.OutputFolder = v_model.set.OutputFolder + '_ablation_' + str(num_ablation)
×
296
            else:
297
                v_model.set.OutputFolder = v_model.set.OutputFolder + '_ablation_edge_' + str(num_ablation)
×
298

299
            if not os.path.exists(v_model.set.OutputFolder):
×
300
                os.mkdir(v_model.set.OutputFolder)
×
301

302
            neighbour_to_ablate = [neighbours[num_ablation]]
×
303

304
            # Calculate if the cell is neighbour on both sides
305
            scutoid_face = None
×
306
            neighbours_other_side = []
×
307
            if location_filter == 0:
×
308
                neighbours_other_side = cell_to_ablate[0].compute_neighbours(location_filter=2)
×
309
                scutoid_face = np.nan
×
310
            elif location_filter == 2:
×
311
                neighbours_other_side = cell_to_ablate[0].compute_neighbours(location_filter=0)
×
312
                scutoid_face = np.nan
×
313

314
            if scutoid_face is not None:
×
315
                if neighbour_to_ablate[0] in neighbours_other_side:
×
316
                    scutoid_face = True
×
317
                else:
318
                    scutoid_face = False
×
319

320
            # Get the centre of the tissue
321
            centre_of_tissue = v_model.geo.compute_centre_of_tissue()
×
322
            neighbour_to_ablate_cell = [cell for cell in v_model.geo.Cells if cell.ID == neighbour_to_ablate[0]][0]
×
323
            distance_to_centre = np.mean([cell_to_ablate[0].compute_distance_to_centre(centre_of_tissue),
×
324
                                          neighbour_to_ablate_cell.compute_distance_to_centre(centre_of_tissue)])
325

326
            # Pick the neighbour and put it in the list
327
            cells_to_ablate = [cell_to_ablate[0].ID, neighbour_to_ablate[0]]
×
328

329
            # Get the edge that share both cells
330
            edge_length_init = v_model.geo.get_edge_length(cells_to_ablate, location_filter)
×
331

332
            # Ablate the edge
333
            v_model.set.ablation = True
×
334
            v_model.geo.cellsToAblate = cells_to_ablate
×
335
            v_model.set.TInitAblation = v_model.t
×
336
            if type_of_ablation == 'recoil_info_apical':
×
337
                v_model.geo.ablate_cells(v_model.set, v_model.t, combine_cells=False)
×
338
                v_model.geo.y_ablated = []
×
339
            elif type_of_ablation == 'recoil_edge_info_apical':
×
340
                v_model.geo.y_ablated = v_model.geo.ablate_edge(v_model.set, v_model.t, domain=location_filter,
×
341
                                                                adjacent_surface=False)
342

343
            # Relax the system
344
            initial_time = v_model.t
×
345
            v_model.set.tend = v_model.t + t_end
×
346
            if type_of_ablation == 'recoil_info_apical':
×
347
                v_model.set.dt = 0.005
×
348
            elif type_of_ablation == 'recoil_edge_info_apical':
×
349
                v_model.set.dt = 0.005
×
350

351
            v_model.set.Remodelling = False
×
352

353
            v_model.set.dt0 = v_model.set.dt
×
354
            if type_of_ablation == 'recoil_edge_info_apical':
×
355
                v_model.set.RemodelingFrequency = 0.05
×
356
            else:
357
                v_model.set.RemodelingFrequency = 100
×
358
            v_model.set.ablation = False
×
359
            v_model.set.export_images = True
×
360
            if v_model.set.export_images and not os.path.exists(v_model.set.OutputFolder + '/images'):
×
361
                os.mkdir(v_model.set.OutputFolder + '/images')
×
362
            edge_length_final_normalized = []
×
363
            edge_length_final = []
×
364
            recoil_speed = []
×
365
            time_steps = []
×
366

367
            # if os.path.exists(v_model.set.OutputFolder):
368
            #     list_of_files = os.listdir(v_model.set.OutputFolder)
369
            #     # Get file modification times and sort files by date
370
            #     files_with_dates = [(file, os.path.getmtime(os.path.join(v_model.set.OutputFolder, file))) for file in
371
            #                         list_of_files]
372
            #     files_with_dates.sort(key=lambda x: x[1])
373
            #     for file in files_with_dates:
374
            #         load_state(v_model, os.path.join(v_model.set.OutputFolder, file[0]))
375
            #         compute_edge_length_v_model(cells_to_ablate, edge_length_final, edge_length_final_normalized,
376
            #                                     edge_length_init, initial_time, location_filter, recoil_speed,
377
            #                                     time_steps,
378
            #                                     v_model)
379

380
            while v_model.t <= v_model.set.tend and not v_model.didNotConverge:
×
381
                gr = v_model.single_iteration()
×
382

383
                compute_edge_length_v_model(cells_to_ablate, edge_length_final, edge_length_final_normalized,
×
384
                                            edge_length_init, initial_time, location_filter, recoil_speed, time_steps,
385
                                            v_model)
386

387
                if np.isnan(gr):
×
388
                    break
×
389

390
            cell_to_ablate_ID = cell_to_ablate[0].ID
×
391
            neighbour_to_ablate_ID = neighbour_to_ablate[0]
×
392

393
        K, initial_recoil, error_bars = fit_ablation_equation(edge_length_final, time_steps)
×
394

395
        # Generate a plot with the edge length final and the fit for each ablation
396
        plt.figure()
×
397
        plt.plot(time_steps, edge_length_final_normalized, 'o')
×
398
        # Plot fit line of the Kelvin-Voigt model
399
        plt.plot(time_steps, recoil_model(np.array(time_steps), initial_recoil, K), 'r')
×
400
        plt.xlabel('Time (s)')
×
401
        plt.ylabel('Edge length final')
×
402
        plt.title('Ablation fit - ' + str(cell_to_ablate_ID) + ' ' + str(neighbour_to_ablate_ID))
×
403

404
        # Save plot
405
        if type_of_ablation == 'recoil_info_apical':
×
406
            plt.savefig(
×
407
                os.path.join(file_name_v_model.replace('before_ablation.pkl', 'ablation_fit_' + str(num_ablation) + '.png'))
408
            )
409
        elif type_of_ablation == 'recoil_edge_info_apical':
×
410
            plt.savefig(
×
411
                os.path.join(file_name_v_model.replace('before_ablation.pkl', 'ablation_edge_fit_' + str(num_ablation) + '.png'))
412
            )
413
        plt.close()
×
414

415
        # Save the results
416
        dict_to_save = {
×
417
            'cell_to_ablate': cell_to_ablate_ID,
418
            'neighbour_to_ablate': neighbour_to_ablate_ID,
419
            'edge_length_init': edge_length_init,
420
            'edge_length_final': edge_length_final,
421
            'edge_length_final_normalized': edge_length_final_normalized,
422
            'initial_recoil_in_s': initial_recoil,
423
            'K': K,
424
            'scutoid_face': scutoid_face,
425
            'location_filter': location_filter,
426
            'distance_to_centre': distance_to_centre,
427
            'time_steps': time_steps,
428
        }
429
        list_of_dicts_to_save.append(dict_to_save)
×
430

431
    recoiling_info_df_apical = pd.DataFrame(list_of_dicts_to_save)
×
432
    recoiling_info_df_apical.to_excel(file_name_v_model.replace('before_ablation.pkl', type_of_ablation+'.xlsx'))
×
433
    save_variables({'recoiling_info_df_apical': recoiling_info_df_apical},
×
434
                   file_name_v_model.replace('before_ablation.pkl', type_of_ablation+'.pkl'))
435

436
    return list_of_dicts_to_save
×
437

438

439
def recoil_model(x, initial_recoil, K):
×
440
    """
441
    Model of the recoil based on a Kelvin-Voigt model
442
    :param x:
443
    :param initial_recoil:
444
    :param K:
445
    :return:   Recoil
446
    """
447
    return (initial_recoil / K) * (1 - np.exp(-K * x))
×
448

449

450
def fit_ablation_equation(edge_length_final_normalized, time_steps):
×
451
    """
452
    Fit the ablation equation. Thanks to Veronika Lachina.
453
    :param edge_length_final_normalized:
454
    :param time_steps:
455
    :return:    K, initial_recoil
456
    """
457

458
    # Normalize the edge length
459
    edge_length_init = edge_length_final_normalized[0]
×
460
    edge_length_final_normalized = (edge_length_final_normalized - edge_length_init) / edge_length_init
×
461

462
    # Fit the model to the data
463
    [params, covariance] = curve_fit(recoil_model, time_steps, edge_length_final_normalized,
×
464
                                     p0=[0.00001, 3], bounds=(0, np.inf))
465

466
    # Get the error
467
    error_bars = np.sqrt(np.diag(covariance))
×
468

469
    initial_recoil, K = params
×
470
    return K, initial_recoil, error_bars
×
471

472

473
def compute_edge_length_v_model(cells_to_ablate, edge_length_final, edge_length_final_normalized, edge_length_init,
×
474
                                initial_time, location_filter, recoil_speed, time_steps, v_model):
475
    """
476
    Compute the edge length of the edge that share the cells_to_ablate
477
    :param cells_to_ablate:
478
    :param edge_length_final:
479
    :param edge_length_final_normalized:
480
    :param edge_length_init:
481
    :param initial_time:
482
    :param location_filter:
483
    :param recoil_speed:
484
    :param time_steps:
485
    :param v_model:
486
    :return:
487
    """
488
    if v_model.t == initial_time:
×
489
        return
×
490
    # Get the edge length
491
    edge_length_final.append(v_model.geo.get_edge_length(cells_to_ablate, location_filter))
×
492
    edge_length_final_normalized.append((edge_length_final[-1] - edge_length_init) / edge_length_init)
×
493
    print('Edge length final: ', edge_length_final[-1])
×
494
    # In seconds. 1 t = 1 minute = 60 seconds
495
    time_steps.append((v_model.t - initial_time) * 60)
×
496
    # Calculate the recoil
497
    recoil_speed.append(edge_length_final_normalized[-1] / time_steps[-1])
×
498

499
def create_video(folder, name_containing_images='top_'):
×
500
    """
501
    Create a video of the images in the folder
502
    :param folder:
503
    :return:
504
    """
505

506
    # Get the images
507
    images = [img for img in os.listdir(folder) if img.endswith(".png") and name_containing_images in img]
×
508
    images.sort(key=lambda x: int(x.split('_')[-1].split('.')[0]))
×
509

510
    # Determine the width and height from the first image
511
    image_path = os.path.join(folder, images[0])
×
512
    frame = cv2.imread(image_path)
×
513
    height, width, layers = frame.shape
×
514

515
    # Define the codec and create VideoWriter object
516
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Use 'mp4v' for MP4
×
517
    video = cv2.VideoWriter(os.path.join(folder, name_containing_images + 'video.mp4'), fourcc, 7, (width, height))
×
518

519
    for image in images:
×
520
        video.write(cv2.imread(os.path.join(folder, image)))
×
521

522
    cv2.destroyAllWindows()
×
523
    video.release()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc