8. Perform video classification using deep learning
techniques.
import os
import cv2
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import TimeDistributed,
LSTM, Dense, Conv2D, MaxPooling2D, Flatten
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
FRAME_COUNT = 20
IMG_HEIGHT, IMG_WIDTH = 64, 64
CHANNELS = 3
def load_video_frames(video_path,
max_frames=FRAME_COUNT):
cap = cv2.VideoCapture(video_path)
frames = []
count = 0
while count < max_frames:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, (IMG_WIDTH,
IMG_HEIGHT))
frame = frame / 255.0 # Normalize
frames.append(frame)
count += 1
cap.release()
while len(frames) < max_frames:
frames.append(np.zeros((IMG_HEIGHT,
IMG_WIDTH, CHANNELS)))
return np.array(frames)
X, y = [], []
dataset_path = "dataset"
for label in os.listdir(dataset_path):
class_folder = os.path.join(dataset_path, label)
if os.path.isdir(class_folder):
for video_file in os.listdir(class_folder):
video_path = os.path.join(class_folder, video_file)
frames = load_video_frames(video_path)
X.append(frames)
y.append(label)
X = np.array(X)
y = np.array(y)
le = LabelEncoder()
y = le.fit_transform(y)
y = to_categorical(y)
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
model = Sequential()
model.add(TimeDistributed(Conv2D(32, (3,3),
activation='relu'), input_shape=(FRAME_COUNT,
IMG_HEIGHT, IMG_WIDTH, CHANNELS)))
model.add(TimeDistributed(MaxPooling2D((2,2))))
model.add(TimeDistributed(Conv2D(64, (3,3),
activation='relu')))
model.add(TimeDistributed(MaxPooling2D((2,2))))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(64))
model.add(Dense(64, activation='relu'))
model.add(Dense(y.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics=['accuracy'])
model.summary()
model.fit(X_train, y_train, epochs=10, batch_size=4,
validation_data=(X_test, y_test))
loss, acc = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {acc*100:.2f}%")
