Spaces:
Sleeping
Sleeping
File size: 8,968 Bytes
05afd51 6feafa3 05afd51 87e3aca 05afd51 87e3aca 05afd51 87e3aca 05afd51 87e3aca 05afd51 89411fa 05afd51 48a6ec4 05afd51 |
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 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
#%matplotlib inline
np.random.seed(2)
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools
from tensorflow.keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau, EarlyStopping
sns.set(style='white', context='notebook', palette='deep')
from PIL import Image
import os
from pylab import *
import re
from PIL import Image, ImageChops, ImageEnhance
def get_imlist(path):
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg') or f.endswith('.png')]
def convert_to_ela_image(path, quality):
filename = path
resaved_filename = filename.split('.')[0] + '.resaved.jpg'
ELA_filename = filename.split('.')[0] + '.ela.png'
im = Image.open(filename).convert('RGB')
im.save(resaved_filename, 'JPEG', quality=quality)
resaved_im = Image.open(resaved_filename)
ela_im = ImageChops.difference(im, resaved_im)
extrema = ela_im.getextrema()
max_diff = max([ex[1] for ex in extrema])
if max_diff == 0:
max_diff = 1
scale = 255.0 / max_diff
ela_im = ImageEnhance.Brightness(ela_im).enhance(scale)
return ela_im
Image.open('Images for Deep Fake/real_images/6401_0.jpg')
convert_to_ela_image('Images for Deep Fake/real_images/6401_0.jpg', 90)
Image.open('Images for Deep Fake/fake_images/1601_0.jpg')
convert_to_ela_image('Images for Deep Fake/fake_images/1601_0.jpg', 90)
import os
import csv
from PIL import Image # Use PIL for image processing
def create_image_dataset_csv(fake_folder, real_folder, output_csv):
# Initialize an empty list to store image information
image_data = []
# Process fake images
fake_files = os.listdir(fake_folder)
for filename in fake_files:
if filename.endswith('.jpg') or filename.endswith('.png'): # Adjust based on your image formats
file_path = os.path.join(fake_folder, filename)
label = 0 # Assign label 0 for fake
image_data.append((file_path, label))
# Process real images
real_files = os.listdir(real_folder)
for filename in real_files:
if filename.endswith('.jpg') or filename.endswith('.png'): # Adjust based on your image formats
file_path = os.path.join(real_folder, filename)
label = 1 # Assign label 1 for real
image_data.append((file_path, label))
# Write image data to CSV file
with open(output_csv, 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(['file_path', 'label']) # Header row
csv_writer.writerows(image_data)
print(f"CSV file '{output_csv}' has been created successfully with {len(image_data)} entries.")
# Example usage:
fake_images_folder = 'Images for Deep Fake/fake_images'
real_images_folder = 'Images for Deep Fake/real_images'
output_csv_file = 'image_dataset.csv'
create_image_dataset_csv(fake_images_folder, real_images_folder, output_csv_file)
import pandas as pd
# dataset = pd.read_csv('datasets/dataset.csv')
dataset = pd.read_csv('image_dataset.csv')
dataset.head()
X = []
Y = []
X
for index, row in dataset.iterrows():
X.append(array(convert_to_ela_image(row[0], 90).resize((128, 128))).flatten() / 255.0)
Y.append(row[1])
X = np.array(X)
Y = to_categorical(Y, 2)
X = X.reshape(-1, 128, 128, 3)
X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size = 0.2, random_state=5)
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'valid',
activation ='relu', input_shape = (128,128,3)))
print("Input: ", model.input_shape)
print("Output: ", model.output_shape)
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'valid',
activation ='relu'))
print("Input: ", model.input_shape)
print("Output: ", model.output_shape)
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
print("Input: ", model.input_shape)
print("Output: ", model.output_shape)
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(2, activation = "softmax"))
model.summary()
optimizer = RMSprop(learning_rate=0.0005, rho=0.9, epsilon=1e-08, decay=0.0)
model.compile(optimizer = optimizer , loss = "categorical_crossentropy", metrics=["accuracy"])
early_stopping = EarlyStopping(monitor='val_acc',
min_delta=0,
patience=2,
verbose=0, mode='max')
epochs = 10
batch_size = 100
history = model.fit(X_train, Y_train, batch_size = batch_size, epochs = epochs,
validation_data = (X_val, Y_val), verbose = 2, callbacks=[early_stopping])
# Plot the loss and accuracy curves for training and validation
fig, ax = plt.subplots(2,1)
ax[0].plot(history.history['loss'], color='b', label="Training loss")
ax[0].plot(history.history['val_loss'], color='r', label="validation loss")
legend = ax[0].legend(loc='best', shadow=True)
ax[1].plot(history.history['accuracy'], color='b', label="Training accuracy")
ax[1].plot(history.history['val_accuracy'], color='r',label="Validation accuracy")
legend = ax[1].legend(loc='best', shadow=True)
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Predict the values from the validation dataset
Y_pred = model.predict(X_val)
# Convert predictions classes to one hot vectors
Y_pred_classes = np.argmax(Y_pred,axis = 1)
# Convert validation observations to one hot vectors
Y_true = np.argmax(Y_val,axis = 1)
# compute the confusion matrix
confusion_mtx = confusion_matrix(Y_true, Y_pred_classes)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
sns.heatmap(confusion_mtx/np.sum(confusion_mtx), annot=True,
fmt='.2%', cmap='Blues')
from sklearn.metrics import classification_report
print(classification_report(Y_true, Y_pred_classes))
#saving the trained cnn model
model.save("fake-image-detection.h5")
import gradio as gr
import numpy as np
from PIL import Image, ImageChops, ImageEnhance
from keras.models import load_model
import tensorflow as tf
# Load the trained model
model = load_model("fake-image-detection.h5")
# Function to convert an image to its ELA form
def convert_to_ela_image(image, quality=90):
resaved_image = image.convert('RGB')
resaved_image.save("resaved_image.jpg", 'JPEG', quality=quality)
resaved_image = Image.open("resaved_image.jpg")
ela_image = ImageChops.difference(image, resaved_image)
extrema = ela_image.getextrema()
max_diff = max([ex[1] for ex in extrema])
if max_diff == 0:
max_diff = 1
scale = 255.0 / max_diff
ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
return ela_image
# Prediction function
def predict(image):
# Convert the input image to an ELA image
ela_image = convert_to_ela_image(image)
ela_image = ela_image.resize((128, 128)) # Resize to match the input size of the model
ela_array = np.array(ela_image).astype('float32') / 255.0
ela_array = ela_array.reshape(1, 128, 128, 3) # Reshape for model input
# Make a prediction
prediction = model.predict(ela_array)
class_idx = np.argmax(prediction, axis=1)[0]
# Map the prediction to labels
labels = {0: "Fake", 1: "Real"}
return labels[class_idx]
# Gradio interface
interface = gr.Interface(
fn=predict, # Prediction function
inputs=gr.Image(type="pil"), # Image input (PIL format)
outputs="label", # Output a label
title="Deep Fake Detector",
description="Upload an image to detect if it's a real or fake image using ELA and a trained CNN model."
)
# Launch the interface
interface.launch() |