import cv2
import os
from pathlib import Path
import numpy as np
def video_to_frames(video_path, output_folder, frame_size=(512, 512)):
"""
Extracts frames from a video and saves them as images.
code
Args:
video_path (str): Path to the input video file.
output_folder (str): Directory where extracted frames will be saved.
frame_size (tuple): Desired size of output frames (width, height).
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Open the video file
cap = cv2.VideoCapture(video_path)
frame_count = 0
success = True
file_name = Path(video_path).stem
previous_frame = None
while success:
success, frame = cap.read()
if success:
frame = cv2.resize(frame, frame_size)
if previous_frame is not None and np.array_equal(frame, previous_frame):
continue
frame_filename = os.path.join(output_folder, f"{file_name}_{frame_count:06d}.png")
cv2.imwrite(frame_filename, frame)
frame_count += 1
previous_frame = frame
cap.release()
print(f"Extracted {frame_count} frames from {video_path} to {output_folder}")
In[2]:
from os import listdir
from os.path import isfile, join
if(use_activation):
self.activation = nn.ReLU()
else:
self.activation = None
def forward(self, x):
y = self.linear1(x)
x = self.linear2(x) + y
if(self.activation is not None):
return self.activation(x)
return x
def forward(self, x):
# Apply the standard sigmoid function
sigmoid = torch.sigmoid(x)
# Scale and shift the sigmoid output
return self.scale * sigmoid + self.shift
class Multiply(nn.Module):
def init(self):
super(Multiply, self).init()
self.scale = nn.Parameter(torch.ones(1))
code
def forward(self, x):
print(self.scale.item())
return x * self.scale
class Decoder2(nn.Module):
def init(self, embedding_dim=256):
super(Decoder2, self).init()
def __len__(self):
return len(self.frames_paths) # Minus one to create pairs
def __getitem__(self, idx):
# Load two consecutive frames
frame1path = self.frames_paths[idx]
frame1 = Image.open(self.directory + '/' + frame1path).convert('RGB')
# Apply transformations
processed = self.preprocessor(images=frame1, return_tensors="pt")
# Return individual frames and the concatenated pair
return {'frame1': processed['pixel_values'][0], 'real_frame': self.transform(frame1)}
def load_images_in_pairs(self, directory):
image_pairs = []
# Iterate over all files in the specified directory
for filename in os.listdir(directory):
if filename.endswith('.png') or filename.endswith('.jpg'):
image_pairs.append(filename)
return image_pairs
In[7]:
import torch
from torchvision import transforms
import matplotlib.pyplot as plt
import numpy as np
Define the inverse normalization transform
def denormalize(tensor):
"""
Denormalizes a tensor using the mean and std used during preprocessing.
Args:
tensor (torch.Tensor): Normalized tensor.
Returns:
torch.Tensor: Denormalized tensor.
"""
# Mean and std used during preprocessing (ImageNet statistics)
#mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
#std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
#tensor = tensor * std + mean
return tensor
import torch
from torchvision import transforms
import matplotlib.pyplot as plt
import numpy as np
Define the inverse normalization transform
def denormalize(tensor):
"""
Denormalizes a tensor using the mean and std used during preprocessing.
Args:
tensor (torch.Tensor): Normalized tensor.
Returns:
torch.Tensor: Denormalized tensor.
"""
# Mean and std used during preprocessing (ImageNet statistics)
mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
tensor = tensor * std + mean
return tensor
find issue why reconstructed images are pixel art like, like squares 16x16 per each patch, has almost single color, like inside patch there are almost only one color
The issue you're describing—reconstructed images appearing as pixelated patches, almost like 16x16 blocks with single colors—might stem from several potential factors related to your model's architecture or training process. Here are some suggestions for diagnosing and addressing this problem:
Check the Reconstruction Process:
Ensure the decoder's architecture is correctly handling the spatial dimensions. The process of reshaping (viewing) and permuting tensors before decoding should map correctly to the expected output shape.
Validate that your decoder fully reconstructs the desired output size, and the order of operations (particularly reshaping) corresponds with the model expectations.
Latent Dimensionality:
The compressed information in the latent space might not capture enough details about the input image if the latent dimensionality is too low. Try increasing the latent dimension to see if it captures more detail.
Model Architecture and Complexity:
Check if your decoder network is powerful enough to reconstruct the images accurately. If not, consider adding more layers or increasing layer width.
In your loss function design, evaluate if any architectural elements in the decoder inadvertently introduce biases towards uniform patches.
Training Process:
Ensure that the model is properly trained. Sometimes, pixelated outputs can occur due to inadequate training or convergence issues. Consider increasing the number of epochs or modifying the learning rate.
Monitor training and validation losses to ensure the model is not overfitting to the training set.
Regularization Techniques:
If applicable, implement regularization techniques to improve learning generalization, like dropout, weight decay, or others, depending on your current architecture.
VAE-specific Adjustments:
Since you are using a VAE (Variational Autoencoder) setup, check the balance between the reconstruction loss (e.g., Binary Cross-Entropy) and the KL divergence loss term. Sometimes, these need tuning to ensure that the model is neither over-regularized nor too free.
Visual Inspection during Training:
Visualize the outputs at different stages of the training to assess when and if the network starts converging towards pixel artifacts.
Data Normalization and Post-processing:
Double-check the preprocessors and postprocessors ensure that they correctly format inputs/outputs, without leaving room for unintended transformations.
Analyze Overhead with a Debugger:
Utilize visual debugging tools, like those provided by torchsummary or other PyTorch inspection utilities, to run the model step-by-step and evaluate tensor sizes and shapes through particular layers for potential mismatches.
Approach the above steps iteratively, applying changes one at a time to observe improvements, thoroughly analyze model inputs and outputs at each stage, and ensure that any applied transformation matches expectations as it flows through the layers.
To address the issue with the pixelated, 16x16 block-like reconstructions in your model, there are several modifications and improvements that we can make to the model architecture and training loop. Let's focus on revising the key parts of your existing setup, especially the decoder:
Improve the Decoder Network:
Ensure that the decoder has enough capacity to reconstruct detailed images. This involves using more convolution layers or upsampling layers, such as nn.ConvTranspose2d for better spatial feature reconstruction.
Review the VAE Loss Function:
It appears you're using a standard VAE loss, but ensure proper balancing between the reconstruction and KL divergence terms.
Check image normalization:
Make sure image normalization and denormalization are consistent throughout preprocessing and postprocessing.
Here is a refactored approach to your model and loss function:
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from transformers import AutoProcessor, SiglipVisionModel
from PIL import Image
import os
import numpy as np
class ResidualLinear(nn.Module):
def __init__(self, in_dim, out_dim, use_activation=True):
super(ResidualLinear, self).__init__()
self.linear1 = nn.Linear(in_dim, out_dim)
self.linear2 = nn.Linear(in_dim, out_dim)
self.activation = nn.ReLU() if use_activation else nn.Identity()
def forward(self, x):
return self.activation(self.linear2(x) + self.linear1(x))
class ResidualAttention(nn.Module):
def __init__(self, dim):
super(ResidualAttention, self).__init__()
self.linear = ResidualLinear(dim, dim)
self.attention = nn.MultiheadAttention(dim, num_heads=8, batch_first=True)
def forward(self, x):
x = self.linear(x)
attn_output, _ = self.attention(x, x, x)
return x + attn_output
class Decoder(nn.Module):
def __init__(self, latent_dim=768, img_size=224, img_channels=3):
super(Decoder, self).__init__()
self.latent_dim = latent_dim
self.img_size = img_size
self.img_channels = img_channels
self.fc1 = ResidualLinear(latent_dim, latent_dim)
self.fc2 = ResidualAttention(latent_dim)
self.fc3 = nn.Linear(latent_dim, img_channels * img_size * img_size)
def forward(self, x):
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
x = x.view(-1, self.img_channels, self.img_size, self.img_size)
return torch.sigmoid(x)
def loss_function(recon_x, x, mu, logvar):
BCE = F.binary_cross_entropy(recon_x, x, reduction='sum')
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD
class ImageDataset(Dataset):
def __init__(self, frames_folder, preprocessor, transform=None):
self.frames_folder = frames_folder
self.frames_paths = [os.path.join(frames_folder, fname) for fname in os.listdir(frames_folder) if fname.endswith(('.png', '.jpg'))]
self.preprocessor = preprocessor
self.transform = transform or transforms.Compose([transforms.ToTensor()])
def __len__(self):
return len(self.frames_paths)
def __getitem__(self, idx):
img_path = self.frames_paths[idx]
img = Image.open(img_path).convert('RGB')
return self.preprocessor(images=img, return_tensors="pt")['pixel_values'][0], self.transform(img)
def train():
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Initialize models and training setup
processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
siglip = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224").to(device)
decoder = Decoder().to(device)
optimizer = torch.optim.Adam(list(decoder.parameters()), lr=1e-4)
# Load dataset
dataset = ImageDataset('/path/to/frames_folder', processor=processor)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
# Training loop
num_epochs = 50
for epoch in range(num_epochs):
for img_tensors, real_frames in dataloader:
img_tensors, real_frames = img_tensors.to(device), real_frames.to(device)
hidden_states = siglip(img_tensors, output_hidden_states=True)['hidden_states'][-1]
# Forward pass
recon_frames = decoder(hidden_states)
# Compute loss
loss = F.binary_cross_entropy(recon_frames, real_frames) # Optional: add KL divergence term for VAE
# Backpropagation and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"Epoch [{epoch+1}/{num_epochs}] Loss: {loss.item():.4f}")
train()
Key Updates and Checks:
Decoder Modifications: Expanded and refactored to include linear and attention layers more uniformly. Optional image reconstruction parts like upscaling via transposed convolutions or simple reshaping for output have been added.
Loss Checks: Adjusted the loss function to focus on using binary_cross_entropy, with the option to refine KL-divergence if applicable.
Training Loop: Integrated processing and device compatibility strategies to structure within the loop.
This should provide finer batches compared to the noted artifacts, pending adequate training and configurations. With these changes, see how your model improves on the reconstruction task – checking image outputs during training is encouraged for insights into intermediate progress as well.
The issue you're encountering, where the model produces square-like artifacts that seem to originate from the 16x16 transformer patch sizes, might indicate a few possibilities about your training setup or model architecture. Here’s a breakdown of how you can address the issue:
Model Architecture and Decoder Refinement:
Ensure that your decoder can effectively upscale and merge patch representations into coherent images. Consider using layers that enhance spatial correlation, such as:
ConvTranspose2d for upsampling operations.
Interpolation layers (e.g., torch.nn.functional.interpolate) for smoother upscaling.
Possibly add more layers or features to progressively refine details.
Patch Embedding Sensitivity:
The model might not be effectively blending or utilizing the embeddings beyond preserving patches. Ensuring after-transformer integration to smooth over patch boundaries might be beneficial.
Investigate the Upsampling Approach:
If your latent space or decoder excessively relies on linear layers without layers that blend spatial features, it could struggle to interpret embeddings between distinct patches coherently.
Experiment with combinations of convolutional, non-linearity, and normalization layers for better spatial smoothing and fidelity.
Enhanced Decoder Block:
Consider using U-Net style architectures or skip connections to offer finer granularity control across different resolutions for the model.
Integrate attention modules or global-local feature merges to improve spatial coherency.
Learning Schedule:
A steady learning rate like 1e-5 being too low might not yield visible improvements initially, and a dynamic scheduler might assist. Try varying the learning rate over epochs proportionate to loss trends or architectures.
Initialization and Batch Sizes:
Starting from varying initializations or increasing batch sizes might mitigate overfitting by balancing updates more uniformly across sample features.
With these insights, let’s refine the decoder setup to improve the tendencies toward 16x16 artifacts. Here’s an updated model approach focusing more on spatial coherency:
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from transformers import AutoProcessor, SiglipVisionModel
from PIL import Image
import os
class EnhancedDecoder(nn.Module):
def __init__(self, img_channels=3, init_features=768):
super(EnhancedDecoder, self).__init__()
self.upconv1 = nn.ConvTranspose2d(init_features, 256, kernel_size=4, stride=2, padding=1)
self.conv1 = nn.Sequential(
nn.Conv2d(256, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(128, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
self.upconv2 = nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1)
self.conv2 = nn.Sequential(
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
self.final_layer = nn.Sequential(
nn.Conv2d(64, img_channels, kernel_size=3, padding=1),
nn.Sigmoid()
)
def forward(self, x):
x = self.upconv1(x.reshape(x.size(0), -1, 14, 14)) # Ensure the reshaping suits model input
x = self.conv1(x)
x = self.upconv2(x)
x = self.conv2(x)
return self.final_layer(x)
def train():
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Initialize models and training setup
processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
siglip = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224").to(device)
decoder = EnhancedDecoder().to(device)
optimizer = torch.optim.Adam(list(decoder.parameters()), lr=1e-4)
# Load dataset
dataset = ImageDataset('/path/to/frames_folder', processor=processor)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
# Training loop
num_epochs = 50
for epoch in range(num_epochs):
for img_tensors, real_frames in dataloader:
img_tensors, real_frames = img_tensors.to(device), real_frames.to(device)
hidden_states = siglip(img_tensors, output_hidden_states=True)['hidden_states'][-1]
# Forward pass
recon_frames = decoder(hidden_states)
# Compute loss
loss = F.mse_loss(recon_frames, real_frames)
# Backpropagation and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"Epoch [{epoch+1}/{num_epochs}] Loss: {loss.item():.4f}")
train()
Key Changes:
Enhanced Upsampling: Use of transposed convolutions or other upsampling tactics to turn patches into full-scale images softly.
Improved Spatial Convolution: Introduce convolutions after upsampling to emphasize feature sharpening and spatial variability.
Training Stability: Additional regularizations and checks ensure improved latent space dynamics that prevent overfitting 16x16 bias.
These changes explicitly attempt to smooth the output space between and potentially inside subtle patches. As always, incremental stepwise evaluations should be done for model performance tuning and effectiveness.