Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
torhaa1 authored Aug 16, 2023
1 parent 3e1136d commit dd6a55e
Show file tree
Hide file tree
Showing 8 changed files with 1,427 additions and 0 deletions.
18 changes: 18 additions & 0 deletions 2018_SD_processing_parameters
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Used function from rov_preprocessing.py with adjustable parameters
def full_preprocessing3_7(image_rgb, enable_udcp=True, enable_wb=True, enable_clahe1=True,
enable_clahe2=True, enable_canny=True, enable_unsharp=True):
if enable_udcp:
image_rgb = UDCP(image_rgb, omega=0.50, t0=0.7, r=15, eps=1e-3, radius=25)
if enable_wb:
image_rgb = white_balance_blend(image_rgb, gamma=0.95, blend_factor=0.25)
if enable_clahe1:
image_rgb = preprocess_clahe(image_rgb, clipLimit=0.2, tileGridSize=(8,8))
if enable_clahe2:
image_rgb = color_balance_and_saturation_enhancement(image_rgb, saturation_factor=1.0, clip_limit=0.2, tile_grid_size=(8,8))
if enable_canny:
image_rgb = edge_enhancement_canny(image_rgb, edge_intensity=0.00005)
if enable_unsharp:
image_rgb = unsharp_mask(image_rgb, sigma=1.0, strength=1.0)

return image_rgb.astype('uint8')

21 changes: 21 additions & 0 deletions 2019_HD_processing_parameters
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 2019 Processing parameters
## 2019 had high quality HD videos


# Used function from rov_preprocessing.py with adjustable parameters
def full_preprocessing3_7(image_rgb, enable_udcp=False, enable_wb=True, enable_clahe1=True,
enable_clahe2=True, enable_canny=True, enable_unsharp=True):
if enable_udcp:
image_rgb = UDCP(image_rgb, omega=0.50, t0=0.7, r=15, eps=1e-3, radius=25)
if enable_wb:
image_rgb = white_balance_blend(image_rgb, gamma=0.85, blend_factor=0.5)
if enable_clahe1:
image_rgb = preprocess_clahe(image_rgb, clipLimit=0.2, tileGridSize=(8,8))
if enable_clahe2:
image_rgb = color_balance_and_saturation_enhancement(image_rgb, saturation_factor=1.1, clip_limit=0.2, tile_grid_size=(8,8))
if enable_canny:
image_rgb = edge_enhancement_canny(image_rgb, edge_intensity=0.05)
if enable_unsharp:
image_rgb = unsharp_mask(image_rgb, sigma=1.0, strength=3.0)

return image_rgb.astype('uint8')
119 changes: 119 additions & 0 deletions concatenate_videos.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "f4884294",
"metadata": {},
"source": [
"# Concatenate videos for visual comparison\n",
"1) Concatenate in series, several shorter video clips into 1 longer video.\n",
"2) Process/restore the combined video.\n",
"3) Concatenate the Original and Restored videos side-by-side for visual comparison.\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "1b2346eb",
"metadata": {},
"outputs": [],
"source": [
"#%% import libraries\n",
"import numpy as np\n",
"import cv2\n",
"\n",
"# custom functions\n",
"from restoration_toolbox import *"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "63f322a4",
"metadata": {},
"outputs": [],
"source": [
"#%% Set directory\n",
"WORKING_DIR = \"C:\\\\Users\\\\torha\\\\div.prog\\\\Image-analysis\\\\Preprocessing\\\\\"\n",
"VIDEO_DIR = \"2019\\\\HD\\\\test-videos\\\\\"\n",
"OUTPUT_VID = \"2019\\\\HD\\\\result-videos\\\\\"\n",
"\n",
"# test videos\n",
"videoA = VIDEO_DIR + \"videoA.mp4\"\n",
"videoB = VIDEO_DIR + \"videoB.mp4\"\n",
"list_of_original_short_clips = [videoA, videoB]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cec28d36",
"metadata": {},
"outputs": [],
"source": [
"# concatenate several video clips into 1 video\n",
"video_list = list_of_original_short_clips\n",
"concatenate_videos(video_list, OUTPUT_VID + 'concatenated_video_clips.mp4')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cf74ac62",
"metadata": {},
"outputs": [],
"source": [
"# Run image restoration (2019 HD parameter settings) on combined video\n",
"process_video(video_for_processing=OUTPUT_VID + 'concatenated_video_clips.mp4', \n",
" output_vid_name=OUTPUT_VID+\"concatenated_video_clips_processed_steps3_7.mp4\",\n",
" processing_func=full_preprocessing3_7_2019hd,\n",
" video_codec='H264')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "950842bd",
"metadata": {},
"outputs": [],
"source": [
"# Prepare videos for concatenation - now side by side\n",
"concatenated_video = OUTPUT_VID + \"concatenated_video_clips.mp4\"\n",
"concatenated_video_processed_steps3_7 = OUTPUT_VID + \"concatenated_video_clips_processed_steps3_7.mp4\"\n",
"list_of_concat_vids = [concatenated_video, concatenated_video_processed_steps3_7]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6a0f0ef0",
"metadata": {},
"outputs": [],
"source": [
"# Comparison of Original video(left) and Restored video(right) playing next to each other\n",
"combine_videos_side_by_side(concatenated_video, concatenated_video_processed_steps3_7, 'SideBySideComparison.mp4')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
175 changes: 175 additions & 0 deletions plot_toolbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities: Functions/Methods frequently used
"""
# import packages
import math
import numpy as np
import matplotlib.pyplot as plt

from PIL import Image
import cv2

from restoration_toolbox import *

# #%% SETUP DIRECTORY
# WORKING_DIR = "abc_home"
# IMAGE_FOLDER = "test-images/"
# OUTPUT_FOLDER = "result-images/"

# #%% READ IMAGES

# # PIL package
# image_path = "image_path" ### SET IMAGE HERE ###
# image = Image.open(image_path)
# image_array = np.array(image)

# # Open CV package
# image_path = "image_path" #### SET NEW IMAGE HERE ###
# image_bgr = cv2.imread(image_path) # BGR by open-cv default
# image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) # Convert from BGR to RGB

#######################################################################
# NORMAL PLOTS
#######################################################################
def plot_image(image, title="Image"):
""" Plot an image, either from a file path (str) or numpy array """
plt.figure(figsize=(6,6))

if isinstance(image, str): # If image is a file path, read the image
image = cv2.imread(image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert from BGR to RGB

# plot single image with title
plt.imshow(image)
plt.title(title)
plt.axis('off'); plt.show()

def plot_gray_image(img, title, cmap='viridis'):
plt.imshow(img, cmap=cmap)
plt.title(title)
plt.axis('off'); plt.show()

def plot_histogram(img, color='gray', alpha=0.7, title='Histogram', xlabel='Pixel Intensity', ylabel='Frequency'):
flat_img = img.flatten()
plt.hist(flat_img, bins=256, color='gray', alpha=0.7)
plt.title(title); plt.xlabel(xlabel);plt.ylabel(ylabel);plt.show()

def plot_image_list(image_list):
""" Plot a list of images, which can either be file paths (str) or numpy arrays """
for i, image in enumerate(image_list):
plt.figure(figsize=(6,6))

# Check if the image is a file path string
if isinstance(image, str):
image = cv2.imread(image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert from BGR to RGB

plt.imshow(image)
plt.title("Image " + str(i+1))
plt.axis('off')
plt.show()

def plot_original_and_processed(image_original, image_processed):
""" Plot an image, either from a file path (str) or numpy array """
plt.figure(figsize=(6,6))

if isinstance(image_original, str): # If image is a file path, read the image
image_original = cv2.imread(image_original)
image_original = cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB) # Convert from BGR to RGB

if isinstance(image_processed, str): # If image is a file path, read the image
image_processed = cv2.imread(image_processed)
image_processed = cv2.cvtColor(image_processed, cv2.COLOR_BGR2RGB) # Convert from BGR to RGB

# plot original image
plt.imshow(image_original)
plt.title("Original")
plt.axis('off')
plt.show()

# plot processed image
plt.imshow(image_processed)
plt.title("Processed")
plt.axis('off')
plt.show()



#######################################################################
# IMAGE ANALYSIS - INSPECTION PLOTS
#######################################################################
def visualize_images_and_histograms(image):
# Calculate features
ndbi = calculate_ndbi(image)
intensity = calculate_intensity(image)
background_index = calculate_background_index(image)
segmented_background = segment_background(image)

# Prepare data for plotting
images = [ndbi, intensity, background_index, segmented_background]
titles = ["NDBI", "Intensity", "Background Index", "Segmented Background"]

# Create 2x4 subplot
fig, axes = plt.subplots(2, 4, figsize=(16, 8))

for i, ax in enumerate(axes[0]):
# Plot image
ax.imshow(images[i], cmap='gray')
ax.set_title(titles[i])
ax.axis('off')

for i, ax in enumerate(axes[1]):
# Plot histogram
ax.hist(images[i].ravel(), bins=256, color='blue', alpha=0.7)
ax.set_title(titles[i] + ' Histogram')

# Display the plot
plt.tight_layout()
plt.show()

def plot_hist_rgb(image_bgr):
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)

# Split the image into R,G,B channels
r, g, b = cv2.split(image_rgb)

fig, ax = plt.subplots()
# Calculate and plot the histogram for each channel
colors = ['r', 'g', 'b']
for i, color in enumerate(colors):
histogram = cv2.calcHist([image_rgb], [i], None, [256], [0, 256])
ax.plot(histogram, color=color)

ax.set_title('RGB Histogram')
ax.set_xlabel('Bins')
ax.set_ylabel('# of Pixels')
plt.show()

def plot_image_and_hist_rgb(image_rgb):
fig, ax = plt.subplots(1, 2, figsize=(12, 6))

# Display the image
ax[0].imshow(cv2.cvtColor(image_rgb, cv2.COLOR_BGR2RGB)) # assuming the image is in BGR format
ax[0].axis('off')

# Plot the histogram
colors = ['r', 'g', 'b']
for i, color in enumerate(colors):
histogram = cv2.calcHist([image_rgb], [i], None, [256], [0, 256])
ax[1].plot(histogram, color=color)

ax[1].set_title('RGB Histogram')
ax[1].set_xlabel('Bins')
ax[1].set_ylabel('# of Pixels')

plt.tight_layout()
plt.show()






Loading

0 comments on commit dd6a55e

Please sign in to comment.