From 56abdcd6c7815e9d5980dddf68fb376246989ab0 Mon Sep 17 00:00:00 2001
From: Adriaens <ines.adriaens@wur.nl>
Date: Mon, 19 Jul 2021 12:11:11 +0200
Subject: [PATCH] finish frame sampler

---
 S3_sampleframes.py | 51 ++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 42 insertions(+), 9 deletions(-)

diff --git a/S3_sampleframes.py b/S3_sampleframes.py
index 7c70878..1eb5867 100644
--- a/S3_sampleframes.py
+++ b/S3_sampleframes.py
@@ -17,7 +17,9 @@ import numpy as np
 import pandas as pd
 import cv2
 import random as rand
-
+from datetime import date
+from datetime import datetime
+#import openpyxl
 
 #%% define constants and filepaths
 
@@ -68,8 +70,8 @@ fn["noframes"] = noframes
 # define start and stop ranges for selection of samples
 edges = []
 for i in range(0,len(fn)):
-    arr = np.linspace(0, noframes[i],
-                      num = nosamples+1,
+    arr = np.linspace(0, noframes[i][0],
+                      num=nosamples+1,
                       dtype = "int")
     edges.append(np.transpose(arr))
 
@@ -77,16 +79,47 @@ for i in range(0,len(fn)):
 fn["edges"] = edges
 
 # sample random numbers (frames) within edges per video
+sampledframes = []
 for i in range(0,len(fn)):
+    frame = []
+    for j in range(0,nosamples):
+        sample = rand.randrange(fn["edges"][i][j],fn["edges"][i][j+1])
+        frame.append(sample)
+    sampledframes.append(frame)
     
-    
-   
-# clear workspace from redundant variables
-del noframes, samplename, i, 
+# add to fn dataframe
+fn["sampledframes"] = sampledframes
 
+# clear workspace memory
+del arr, edges, i, sampledframes, j, sample, samplename, frame
 
-#%% do the actual sampling and write fn to excel
- 
 
+#%% do the actual sampling and write fn to excel
 
+for i in range(0,len(fn)):
+    print(fn["file"][i])            # print filename read
+    cap = cv2.VideoCapture(src+fn["file"][i])  # capture video
+    
+    # read and write selected frames
+    for j in range(0,nosamples):
+        # set frame name for writing + print
+        samplename = dst + fn["samplename"][i] + \
+                     "_" + "frame_" + str(j) + ".jpg"
+        print(fn["samplename"][i] + "_" + "frame_" + str(j) + ".jpg")
+        # set frame number that has to be read
+        cap.set(cv2.CAP_PROP_POS_FRAMES, fn["sampledframes"][i][j])
+        # read frame
+        ret, img = cap.read()
+        # save sampled frame
+        cv2.imwrite(samplename, img) 
+
+    # release videocapture
+    cap.release()
+    
+# write metadata frames to excel file in dest
+today = date.today()
+today = today.strftime("%Y%m%d")
+fn.to_excel(dst+"FrameSelection.xlsx",sheet_name = str(today))
 
+# save as pkl
+fn.to_pickle(dst+"SFrameSelection_"+today)
-- 
GitLab