Vinh.Vu commited on
Commit
d83c5c7
·
1 Parent(s): dae52bd

Update to handle big data

Browse files
.gitignore CHANGED
@@ -136,3 +136,4 @@ mtcnn/
136
  /split_dataset
137
  /prepared_dataset
138
  /App/uploads
 
 
136
  /split_dataset
137
  /prepared_dataset
138
  /App/uploads
139
+ archive.zip
01a-crop_faces_with_mtcnn.py → 01-crop_faces_with_mtcnn.py RENAMED
File without changes
01b-crop_faces_with_azure-vision-api.py DELETED
@@ -1,89 +0,0 @@
1
- import cv2
2
- import sys, os.path
3
- import json
4
- import http.client, urllib.request, urllib.parse, urllib.error, base64
5
-
6
- base_path = '.\\train_sample_videos\\'
7
- AZURE_COMPUTER_VISION_NAME = '----REPLACE-WITH-YOUR-SERVICE-NAME----' # e.g. xxxxxxxxxx.cognitiveservices.azure.com
8
- AZURE_COMPUTER_VISION_API_KEY = '----REPLACE-WITH-YOUR-KEY----'
9
-
10
- def get_filename_only(file_path):
11
- file_basename = os.path.basename(file_path)
12
- filename_only = file_basename.split('.')[0]
13
- return filename_only
14
-
15
- with open(os.path.join(base_path, 'metadata.json')) as metadata_json:
16
- metadata = json.load(metadata_json)
17
- print(len(metadata))
18
-
19
- for filename in metadata.keys():
20
- tmp_path = os.path.join(base_path, get_filename_only(filename))
21
- print('Processing Directory: ' + tmp_path)
22
- frame_images = [x for x in os.listdir(tmp_path) if os.path.isfile(os.path.join(tmp_path, x))]
23
- faces_path = os.path.join(tmp_path, 'faces')
24
- print('Creating Directory: ' + faces_path)
25
- os.makedirs(faces_path, exist_ok=True)
26
- print('Cropping Faces from Images...')
27
-
28
- for frame in frame_images:
29
- print('Processing ', frame)
30
- image = cv2.cvtColor(cv2.imread(os.path.join(tmp_path, frame)), cv2.COLOR_BGR2RGB)
31
-
32
- # Open the binary file
33
- with open(os.path.join(tmp_path, frame), 'rb') as file_contents:
34
- img_data = file_contents.read()
35
-
36
- ######### Azure Computer Vision API
37
- headers = {
38
- # Request headers
39
- 'Content-Type': 'application/octet-stream',
40
- 'Ocp-Apim-Subscription-Key': AZURE_COMPUTER_VISION_API_KEY,
41
- }
42
-
43
- params = urllib.parse.urlencode({
44
- # Request parameters
45
- 'visualFeatures': 'Faces'
46
- })
47
-
48
- try:
49
- conn = http.client.HTTPSConnection(AZURE_COMPUTER_VISION_NAME)
50
- conn.request("POST", "/vision/v3.0/analyze?%s" % params, img_data, headers)
51
- response = conn.getresponse().read()
52
- data = json.loads(response.decode('utf-8'))
53
- print(data)
54
- conn.close()
55
- except Exception as e:
56
- print("[Errno {0}] {1}".format(e.errno, e.strerror))
57
- continue
58
-
59
- print(data['faces'])
60
- print('Face Detected: ', len(data['faces']))
61
- count = 0
62
-
63
- for result in data['faces']:
64
- bounding_box = []
65
- bounding_box.append(result['faceRectangle']['left'])
66
- bounding_box.append(result['faceRectangle']['top'])
67
- bounding_box.append(result['faceRectangle']['width'])
68
- bounding_box.append(result['faceRectangle']['height'])
69
- print(bounding_box)
70
-
71
- margin_x = bounding_box[2] * 0.3 # 30% as the margin
72
- margin_y = bounding_box[3] * 0.3 # 30% as the margin
73
- x1 = int(bounding_box[0] - margin_x)
74
- if x1 < 0:
75
- x1 = 0
76
- x2 = int(bounding_box[0] + bounding_box[2] + margin_x)
77
- if x2 > image.shape[1]:
78
- x2 = image.shape[1]
79
- y1 = int(bounding_box[1] - margin_y)
80
- if y1 < 0:
81
- y1 = 0
82
- y2 = int(bounding_box[1] + bounding_box[3] + margin_y)
83
- if y2 > image.shape[0]:
84
- y2 = image.shape[0]
85
- print(x1, y1, x2, y2)
86
- crop_image = image[y1:y2, x1:x2]
87
- new_filename = '{}-{:02d}.png'.format(os.path.join(faces_path, get_filename_only(frame)), count)
88
- count = count + 1
89
- cv2.imwrite(new_filename, cv2.cvtColor(crop_image, cv2.COLOR_RGB2BGR))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02-prepare_fake_real_dataset.py CHANGED
@@ -3,6 +3,9 @@ import os
3
  import shutil
4
  import numpy as np
5
  import splitfolders as split_folders
 
 
 
6
 
7
  base_path = '.\\train_sample_videos\\Deepfakes\\'
8
  dataset_path = '.\\prepared_dataset\\'
@@ -11,13 +14,36 @@ os.makedirs(dataset_path, exist_ok=True)
11
 
12
  tmp_fake_path = '.\\tmp_fake_faces'
13
  print('Creating Directory: ' + tmp_fake_path)
14
- os.makedirs(tmp_fake_path, exist_ok=True)
 
 
15
 
16
  def get_filename_only(file_path):
17
  file_basename = os.path.basename(file_path)
18
  filename_only = file_basename.split('.')[0]
19
  return filename_only
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  with open(os.path.join('.\\train_sample_videos\\csv\\', 'Deepfakes.csv'), newline='', encoding='utf-8') as csvfile:
22
  reader = csv.DictReader(csvfile)
23
  metadata = {}
@@ -27,11 +53,15 @@ with open(os.path.join('.\\train_sample_videos\\csv\\', 'Deepfakes.csv'), newlin
27
 
28
  real_path = os.path.join(dataset_path, 'real')
29
  print('Creating Directory: ' + real_path)
30
- os.makedirs(real_path, exist_ok=True)
 
 
31
 
32
  fake_path = os.path.join(dataset_path, 'fake')
33
  print('Creating Directory: ' + fake_path)
34
- os.makedirs(fake_path, exist_ok=True)
 
 
35
 
36
  for filename, label in metadata.items():
37
  print(filename)
@@ -41,10 +71,10 @@ for filename, label in metadata.items():
41
  if os.path.exists(tmp_path):
42
  if label == 'REAL':
43
  print('Copying to :' + real_path)
44
- shutil.copytree(tmp_path, real_path, dirs_exist_ok=True)
45
  elif label == 'FAKE':
46
  print('Copying to :' + tmp_fake_path)
47
- shutil.copytree(tmp_path, tmp_fake_path, dirs_exist_ok=True)
48
  else:
49
  print('Ignored..')
50
 
@@ -54,13 +84,10 @@ print('Total Number of Real faces: ', len(all_real_faces))
54
  all_fake_faces = [f for f in os.listdir(tmp_fake_path) if os.path.isfile(os.path.join(tmp_fake_path, f))]
55
  print('Total Number of Fake faces: ', len(all_fake_faces))
56
 
57
- random_faces = np.random.choice(all_fake_faces, len(all_real_faces), replace=False)
58
- for fname in random_faces:
59
- src = os.path.join(tmp_fake_path, fname)
60
- dst = os.path.join(fake_path, fname)
61
- shutil.copyfile(src, dst)
62
 
63
- print('Down-sampling Done!')
64
 
65
  # Split into Train/ Val/ Test folders
66
  split_folders.ratio(dataset_path, output='split_dataset', seed=1377, ratio=(.8, .1, .1)) # default values
 
3
  import shutil
4
  import numpy as np
5
  import splitfolders as split_folders
6
+ from PIL import Image
7
+
8
+ MIN_IMAGE_SIZE = 90 # minimum width and height in pixels
9
 
10
  base_path = '.\\train_sample_videos\\Deepfakes\\'
11
  dataset_path = '.\\prepared_dataset\\'
 
14
 
15
  tmp_fake_path = '.\\tmp_fake_faces'
16
  print('Creating Directory: ' + tmp_fake_path)
17
+ if os.path.exists(tmp_fake_path):
18
+ shutil.rmtree(tmp_fake_path)
19
+ os.makedirs(tmp_fake_path)
20
 
21
  def get_filename_only(file_path):
22
  file_basename = os.path.basename(file_path)
23
  filename_only = file_basename.split('.')[0]
24
  return filename_only
25
 
26
+ def copy_large_faces(src_dir, dst_dir):
27
+ """Copy only images that are at least MIN_IMAGE_SIZE x MIN_IMAGE_SIZE."""
28
+ skipped = 0
29
+ copied = 0
30
+ for fname in os.listdir(src_dir):
31
+ src_file = os.path.join(src_dir, fname)
32
+ if not os.path.isfile(src_file):
33
+ continue
34
+ try:
35
+ with Image.open(src_file) as img:
36
+ w, h = img.size
37
+ if w >= MIN_IMAGE_SIZE and h >= MIN_IMAGE_SIZE:
38
+ shutil.copy2(src_file, os.path.join(dst_dir, fname))
39
+ copied += 1
40
+ print(f'Copied: {copied}')
41
+ else:
42
+ print(f'Skipped {fname}: {w}x{h}')
43
+ skipped += 1
44
+ except Exception:
45
+ skipped += 1
46
+
47
  with open(os.path.join('.\\train_sample_videos\\csv\\', 'Deepfakes.csv'), newline='', encoding='utf-8') as csvfile:
48
  reader = csv.DictReader(csvfile)
49
  metadata = {}
 
53
 
54
  real_path = os.path.join(dataset_path, 'real')
55
  print('Creating Directory: ' + real_path)
56
+ if os.path.exists(real_path):
57
+ shutil.rmtree(real_path)
58
+ os.makedirs(real_path)
59
 
60
  fake_path = os.path.join(dataset_path, 'fake')
61
  print('Creating Directory: ' + fake_path)
62
+ if os.path.exists(fake_path):
63
+ shutil.rmtree(fake_path)
64
+ os.makedirs(fake_path)
65
 
66
  for filename, label in metadata.items():
67
  print(filename)
 
71
  if os.path.exists(tmp_path):
72
  if label == 'REAL':
73
  print('Copying to :' + real_path)
74
+ copy_large_faces(tmp_path, real_path)
75
  elif label == 'FAKE':
76
  print('Copying to :' + tmp_fake_path)
77
+ copy_large_faces(tmp_path, tmp_fake_path)
78
  else:
79
  print('Ignored..')
80
 
 
84
  all_fake_faces = [f for f in os.listdir(tmp_fake_path) if os.path.isfile(os.path.join(tmp_fake_path, f))]
85
  print('Total Number of Fake faces: ', len(all_fake_faces))
86
 
87
+ print('Copying filtered fake faces to: ' + fake_path)
88
+ copy_large_faces(tmp_fake_path, fake_path)
 
 
 
89
 
90
+ print('Copying all fake faces Done!')
91
 
92
  # Split into Train/ Val/ Test folders
93
  split_folders.ratio(dataset_path, output='split_dataset', seed=1377, ratio=(.8, .1, .1)) # default values