Parameters:
I1, I2 : numpy arrays
Grayscale images at t=1 and t=2, normalized to [0, 1].
windowSize : int
Size of the window for local calculations.
tau : float
Threshold for minimum eigenvalue of ATA.
Returns:
u, v : numpy arrays
Optical flow components in x and y directions.
hitMap : numpy array
Binary image indicating valid corner regions.
"""
assert windowSize % 2 == 1, "Window size must be odd."
half_win = windowSize // 2
# Compute image gradients using Sobel filter
kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.5
kernel_y = np.array([[-1, -1], [1, 1]]) * 0.5
kernel_t = np.ones((2, 2)) * 0.25
Ix = convolve(I1, kernel_x) + convolve(I2, kernel_x)
Iy = convolve(I1, kernel_y) + convolve(I2, kernel_y)
It = convolve(I2, kernel_t) - convolve(I1, kernel_t)
u = np.zeros_like(I1)
v = np.zeros_like(I1)
hitMap = np.zeros_like(I1, dtype=bool)
for i in range(half_win, I1.shape[0] - half_win):
for j in range(half_win, I1.shape[1] - half_win):
Ix_win = Ix[i-half_win:i+half_win+1, j-half_win:j+half_win+1].flatten()
Iy_win = Iy[i-half_win:i+half_win+1, j-half_win:j+half_win+1].flatten()
It_win = It[i-half_win:i+half_win+1, j-half_win:j+half_win+1].flatten()
A = np.stack((Ix_win, Iy_win), axis=1)
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau:
flow = lstsq(ATA, A.T @ b, cond=None)[0]
u[i, j], v[i, j] = flow
hitMap[i, j] = True
return u, v, hitMap
Step 3: Display Optical Flow Results and hitMap for each window size
def display_results(u, v, hitMap, I1, window_size):
"""Display optical flow results and hitmap with correctly scaled flow vectors."""
code
# Create a white canvas to display the flow vectors (white background)
flow_image = np.ones_like(I1) # White background with values [1.0] (in [0, 1] range)
# Create a new figure for each window size
plt.figure(figsize=(8, 8))
plt.imshow(flow_image, cmap='gray') # White canvas for flow vectors
plt.title(f"Optical Flow Vectors (Window Size {window_size})")
# Plot the flow vectors on the white canvas in blue color
plt.quiver(np.arange(0, u.shape[1], step=5), np.arange(0, v.shape[0], step=5),
u[::5, ::5], v[::5, ::5], color='blue', scale=50, width=0.005) # Adjust scale and density
plt.gca().invert_yaxis() # To match the image coordinate system
plt.show()
# Display hitMap as binary (black and white) image
plt.figure(figsize=(6, 6))
plt.imshow(hitMap, cmap='gray') # Black and white image (binary)
plt.title(f"Valid Areas (HitMap) - Window Size {window_size}")
plt.axis('off') # Hide axes
plt.show()
tau = 0.01 # Threshold for minimum eigenvalue of ATA
window_sizes = [15, 31, 101] # Three different window sizes (updated to be odd)
For each window size, compute and display results
for window_size in window_sizes:
u, v, hitMap = opticalFlow(I1, I2, window_size, tau)
display_results(u, v, hitMap, I1, window_size)
Assistant
The script provided demonstrates how to compute and visualize optical flow between two images using the Lucas-Kanade method. Here’s a breakdown of the main components:
Preprocessing: The preprocess_image function loads an image, converts it to grayscale, and normalizes the pixel values to be between [0, 1].
Optical Flow Calculation: The opticalFlow function computes the optical flow between two images using the classical Lucas-Kanade method:
Gradients: It computes image gradients Ix, Iy, and temporal gradient It using convolution with specific kernels.
Window Processing: For each pixel, within a defined window size, it constructs matrices A and b to solve the equation (A \times [u, v]^T = -b).
Eigenvalue Check: It verifies that the matrix ATA has eigenvalues greater than a threshold tau, which ensures that the area is a good feature for tracking.
Flow Vectors: Uses Scipy's lstsq function to solve the least-squares problem and obtain flow vectors u and v.
Visualization: The display_results function visualizes the computed optical flow vectors and hit maps:
Flow vectors are displayed over a white canvas for clarity, using matplotlib's quiver function for vector plotting.
The hit map is shown as a binary image to indicate valid regions for optical flow calculations.
Function Execution: Example usage computes and displays results for images specified by I1_path and I2_path, testing various window sizes specified in window_sizes.
Considerations:
Ensure the paths to images (I1_path and I2_path) are correct on your system.
The window size should always be odd to correctly center the neighborhood around a pixel.
The visualization using the quiver plot is set up with specific scales and step sizes for readability, which can be adjusted depending on the size of the flow vectors or the resolution of your images.
The use of convolve instead of more advanced gradient estimations or handling cases where the matrix (A^TA) is poorly conditioned (e.g., regularization) may influence results, but the method should work fine for well-textured areas.
User
ما می خواهیم فلش ها روی بوم سفید نمایش داده شوند لطفا این مشکل را حل کنید
Assistant
برای اطمینان از اینکه فلشها یا بردارهای جریان نوری روی یک بوم سفید نمایش داده میشوند، باید پسزمینه بوم نمایشگر جریان را بهطور مناسب تنظیم کنید. در کد فعلی، شما در حال تنظیم تصویری سفید برای نمایش نتایج جریان نوری هستید. اما ممکن است به تنظیمات جزئی برای بهبود دیداری نیاز داشته باشد. در اینجا چگونگی انجام این کار آمده است:
اطمینان حاصل کنید که تصویر بوم سفید بهدرستی تنظیم شده است.
تنظیمات برای رسم بردارهای جریان را بررسی کنید که تا حد امکان در برابر پسزمینه سفید قابل مشاهده باشند، مانند انتخاب رنگ فلشها.
در کد زیر، اطمینان حاصل میکنیم که بوم سفید بهدرستی تعریف شده و بردارهای جریان نوری بهوضوح روی آن نمایش داده میشوند:
python
def display_results(u, v, hitMap, window_size):
"""Display optical flow results and hitmap with correctly scaled flow vectors."""
# Create a white canvas based on the given dimensions
flow_image = np.ones_like(u) # White background with values [1.0] (normalized range)
# Create a new figure for optical flow
plt.figure(figsize=(8, 8))
plt.imshow(flow_image, cmap='gray', vmin=0, vmax=1) # Ensures a white background
plt.title(f"Optical Flow Vectors (Window Size {window_size})")
# Plot the flow vectors on the white canvas in blue color
plt.quiver(np.arange(0, u.shape[1], step=5), np.arange(0, v.shape[0], step=5),
u[::5, ::5], v[::5, ::5], color='blue', scale=50, width=0.005) # Adjust scale and density
plt.gca().invert_yaxis() # To match the image coordinate system
plt.show()
# Display hitMap as a binary (black and white) image
plt.figure(figsize=(6, 6))
plt.imshow(hitMap, cmap='gray', vmin=0, vmax=1) # Black and white image (binary)
plt.title(f"Valid Areas (HitMap) - Window Size {window_size}")
plt.axis('off') # Hide axes
plt.show()
# Calling this function for each window size after calculation as before
توضیحات:
بوم سفید با استفاده از np.ones_like(u) ایجاد شده بهطوری که هر پیکسل برابر با 1.0 (سفید در نمایش مقیاس خاکستری) تنظیم شده است.
imshow با vmin=0 و vmax=1 استفاده شده است تا اطمینان حاصل شود که نمایش بوم بهدرستی شامل سفید خالص است.
مطمئن شوید که رنگها و مقیاسهای انتخاب شده برای quiver مناسب هستند تا فلشها به وضوح دیده شوند؛ در این مثال از رنگ آبی استفاده شده است.
User
TypeError Traceback (most recent call last)
in <cell line: 106>()
106 for window_size in window_sizes:
107 u, v, hitMap = opticalFlow(I1, I2, window_size, tau)
--> 108 display_results(u, v, hitMap, I1, window_size)
TypeError: display_results() takes 4 positional arguments but 5 were given
Assistant
خطایی که دریافت میکنید به این دلیل است که تابع display_results با تعداد آرگومانهای اشتباه فراخوانی شده است. تابع شما در تعریفش چهار آرگومان میپذیرد اما در فراخوانی، پنج آرگومان به آن داده شده است. بیایید این مشکل را برطرف کنیم.
از آنجا که در خطای خود به صراحت مشاهده میشود که display_results مقدار I1 به آن میفرستد و تابع display_results در تعریفش چنین پارامتری نمیپذیرد، بیایید پارامتر اضافی را حذف کنیم.
در اینجا نسخه اصلاح شده از فراخوانی تابع است که باید مشکلتان را حل کند:
python
# Example usage
I1_path = "/content/coridor/hw4/data/corridor/bt.000.png"
I2_path = "/content/coridor/hw4/data/corridor/bt.001.png"
# Load images
I1 = preprocess_image(I1_path)
I2 = preprocess_image(I2_path)
# Set parameters
tau = 0.01 # Threshold for minimum eigenvalue of ATA
window_sizes = [15, 31, 101] # Three different window sizes (updated to be odd)
# For each window size, compute and display results
for window_size in window_sizes:
u, v, hitMap = opticalFlow(I1, I2, window_size, tau)
display_results(u, v, hitMap, window_size)
در فراخوانی تابع display_results، مقدار I1 دیگر ارسال نمیشود و تنها چهار آرگومان مورد نیاز یعنی u, v, hitMap و window_size ارسال میشوند. امیدوارم این راهحل مشکل را برطرف کند!
User
ابتدا باید تصاویر را به صورت سیا ه-سفید و مقادیر شدت را به محدوده ] 0,1 [ تبدیل کنید. با استفاده از الگوریتم هایی که برای شناسایی گوشه ها پیاده سازی استفاده می شوند 50 گوشه در تصاویر و با دایره های قرمز تو خالی
و نمایش دهیدنمایش دهید ارائه شده پیدا کنید. /content/coridor/hw4/data/corridor/bt.000.png /content/coridor/hw4/data/corridor/bt.001.png /content/coridor/hw4/data/sphere/sphere.0.png /content/coridor/hw4/data/sphere/sphere.1.png /content/coridor/hw4/data/synth/synth_000.png /content/coridor/hw4/data/synth/synth_001.png
Assistant
برای شناسایی گوشهها در تصاویر و نمایش آنها، میتوان از تابعی همچون دتکتور گوشه Harris یا شیوههایی مشابه استفاده کرد. این فرآیند شامل مراحل زیر است:
پیشپردازش تصاویر: بارگذاری و تبدیل به مقیاس خاکستری و نرمالسازی به محدوده [0, 1].
تشخیص گوشهها: پیادهسازی الگوریتم انتخاب گوشهها (مانند Harris) برای تشخیص گوشههای قوی.
انتخاب ۵۰ گوشه برتر: انتخاب ۵۰ گوشه با بالاترین مقادیر پاسخدهی.
نمایش گوشهها: نمایش گوشهها روی تصویر با استفاده از دایرههای قرمز توخالی.
حال یک کد کامل برای انجام این کار ارائه میشود:
python
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
def detect_and_display_corners(image_path, num_corners=50):
"""
Detect and display corners on the image with red hollow circles.
Parameters:
image_path : str
Path to the image file.
num_corners : int
Number of strongest corners to display.
"""
# Load and preprocess image
img = preprocess_image(image_path)
img = (img * 255).astype(np.uint8) # Convert to uint8 for cv2
# Detect corners using the Harris corner detector
gray = np.float32(img)
dst = cv2.cornerHarris(gray, blockSize=2, ksize=3, k=0.04)
# Dilate result to mark the corners
dst_dilated = cv2.dilate(dst, None)
# Threshold to detect corners
corners = np.argwhere(dst_dilated > 0.01 * dst_dilated.max())
corner_strengths = dst_dilated[corners[:, 0], corners[:, 1]]
# Select the strongest corners
indices = np.argsort(corner_strengths)[-num_corners:]
strongest_corners = corners[indices]
# Display the image with corners
plt.figure(figsize=(8, 8))
plt.imshow(img, cmap='gray')
for corner in strongest_corners:
y, x = corner
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none') # Red hollow circle
plt.title(f"Corners Detected in {image_path.split('/')[-1]}")
plt.axis('off')
plt.show()
# Paths to images
image_paths = [
"/content/coridor/hw4/data/corridor/bt.000.png",
"/content/coridor/hw4/data/corridor/bt.001.png",
"/content/coridor/hw4/data/sphere/sphere.0.png",
"/content/coridor/hw4/data/sphere/sphere.1.png",
"/content/coridor/hw4/data/synth/synth_000.png",
"/content/coridor/hw4/data/synth/synth_001.png"
]
# Detect and display corners for each image
for image_path in image_paths:
detect_and_display_corners(image_path, num_corners=50)
User
گوشه ها درست نیستند لطفا دقیقتر این کار را انجام دهید
Assistant
برای بهبود دقت شناسایی گوشهها، میتوانیم از روش شناسایی گوشهها با استفاده از الگوریتم Shi-Tomasi که به عنوان یک بهبوددهی در مقابل الگوریتم Harris عمل میکند، استفاده کنیم. این الگوریتم به شما اجازه میدهد تا گوشههای قویتر و دقیقتری پیدا کنید.
با استفاده از OpenCV، میتوانیم این کار را به صورت زیر انجام دهیم:
python
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
def detect_and_display_corners(image_path, num_corners=50):
"""
Detect and display corners on the image with red hollow circles.
Parameters:
image_path : str
Path to the image file.
num_corners : int
Number of strongest corners to display.
"""
# Load and preprocess image
img = preprocess_image(image_path)
img = (img * 255).astype(np.uint8) # Convert to uint8 for cv2
# Detect corners using the Shi-Tomasi corner detection method
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=10)
corners = np.int0(corners) # Convert corners to integer
# Display the image with corners
plt.figure(figsize=(8, 8))
plt.imshow(img, cmap='gray')
for corner in corners:
x, y = corner.ravel()
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none') # Red hollow circle
plt.title(f"Corners Detected in {image_path.split('/')[-1]}")
plt.axis('off')
plt.show()
# Paths to images
image_paths = [
"/content/coridor/hw4/data/corridor/bt.000.png",
"/content/coridor/hw4/data/corridor/bt.001.png",
"/content/coridor/hw4/data/sphere/sphere.0.png",
"/content/coridor/hw4/data/sphere/sphere.1.png",
"/content/coridor/hw4/data/synth/synth_000.png",
"/content/coridor/hw4/data/synth/synth_001.png"
]
# Detect and display corners for each image
for image_path in image_paths:
detect_and_display_corners(image_path, num_corners=50)
User
دو کد زیر را بر ای تعیین میدان optical flow در 50 گوشه شناسایی شده ترکیب کنید. تصویر نتیجه را مانند شکل زیر رسم کنید.
مقادیر مناسب بر ای اندازه پنجره و τ را انتخاب کنید که بهترین نتیجه را به شما بدهد . import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
def detect_and_display_corners(image_path, num_corners=50):
"""
Detect and display corners on the image with red hollow circles.
code
Parameters:
image_path : str
Path to the image file.
num_corners : int
Number of strongest corners to display.
"""
# Load and preprocess image
img = preprocess_image(image_path)
img = (img * 255).astype(np.uint8) # Convert to uint8 for cv2
# Detect corners using the Shi-Tomasi corner detection method
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=10)
corners = np.int0(corners) # Convert corners to integer
# Display the image with corners
plt.figure(figsize=(8, 8))
plt.imshow(img, cmap='gray')
for corner in corners:
x, y = corner.ravel()
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none') # Red hollow circle
plt.title(f"Corners Detected in {image_path.split('/')[-1]}")
plt.axis('off')
plt.show()
for image_path in image_paths:
detect_and_display_corners(image_path, num_corners=50) و کد زیر import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from scipy.ndimage import convolve
from scipy.linalg import lstsq
Assistant
برای ترکیب این دو کد بهمنظور شناسایی ۵۰ گوشه و سپس محاسبه میدان جریان نوری (optical flow) برای این نقاط، باید مراحل زیر را دنبال کنیم:
بارگذاری و پیشپردازش تصویرها: تصاویر را بهصورت مقیاس خاکستری و نرمالسازیشده بارگذاری میکنیم.
شناسایی گوشهها: ۵۰ گوشه قوی در تصویر اول شناسایی میشود.
محاسبه جریان نوری: برای هر یک از این گوشههای شناساییشده، جریان نوری محاسبه میشود.
نمایش نتایج: فلشهای جریان نوری را برای هر گوشه روی تصویر اولیه نمایش میدهیم.
به این صورت میتوانید این فرآیند را پیادهسازی کنید:
python
User
فلش های آبی خیلی کوچکند
Assistant
اگر فلشهای آبی کوچک هستند و به وضوح نمایش داده نمیشوند، میتوانیم با افزایش مقیاس یا بزرگتر کردن خود فلشها آنها را واضحتر جلوه بدهیم. در کد زیر، میتوان از پارامتر scale در تابع arrow (یا به جای آن از quiver) استفاده کرد تا به وضوح بیشتری دست یابیم. بهتر است سعی کنید طول این فلشها را نسبت به دادههای واقعی تنظیم کنید تا قابل خواندن و قابل درک باشد.
در اینجا چگونگی انجام این کار آمده است:
python
User
لطفا خیلی فلش ها را بزرگتر کنید
Assistant
برای اینکه فلشها بزرگتر و قابل مشاهدهتر شوند، میتوانیم پارامترهای مرتبط با نمایش فلشها را تغییر دهیم، به ویژه scale_factor، head_width و head_length را افزایش دهیم. این تغییرات باعث خواهند شد که فلشهای جریان نوری بزرگتر و واضحتر نمایش داده شوند.
در کد زیر، مقادیر این پارامترها را بهطور چشمگیری افزایش دادهام تا تأثیر بیشتری داشته باشد:
python
User
سر فلش ها بزرگ شده ولی طولش تغییری نکرده
Assistant
اگر طول فلشها به اندازه دلخواه بزرگ نشده باشد، بهتر است از تابع quiver برای رسم بردارها استفاده کنیم که امکان کنترل بیشتری بر روی مقیاس و طول فلشها به ما میدهد. با استفاده از quiver میتوانیم مستقیماً طول بردارها را کنترل کنیم.
در اینجا چگونگی پیادهسازی آن با استفاده از quiver آمده است:
python
User
نه نتیجه خیلی بد شد و حتی دایره های قرمز هم از بین رفت
Assistant
بیایید کد را اصلاح کنیم تا هم دایرههای قرمز باقی بمانند و هم فلشهای جریان نوری به وضوح نمایش داده شوند. هدف این است که دایرههای قرمز را ابتدا رسم کنیم و سپس از quiver برای اضافه کردن فلشهای جریان نوری استفاده کنیم. همچنین از یک مقیاس مناسب برای فلشها اطمینان حاصل کنیم.
در اینجا یک نسخه تعدیلشده از کد با این تنظیمات ارائه شده است:
پیشپردازش: تصویرها به مقیاس خاکستری تبدیل شده و به محدوده [0, 1] نرمالسازی میشوند.
تشخیص گوشه: از تابع cv2.cornerHarris برای تشخیص گوشهها استفاده میشود.
انتخاب گوشهها: ۵۰ گوشه قوی تر انتخاب میشوند.
نمایش: گوشهها با دایرههای قرمز توخالی با استفاده از matplotlib نمایش داده میشوند.
این کد گوشهها را بر اساس قدرت سیگنال آنها برای عملیاتهای دید ماشینی و بینایی کامپیوتر تشخیص میدهد و نمایش میدهد.
توضیحات:
روش Shi-Tomasi: این الگوریتم بر اساس توابع خاصیت گوشهها توسعه یافته و پایدارتر از Harris عمل میکند. این الگوریتم به شما اجازه میدهد تعداد مشخصی از نقاط گوشه قویتر را طبق maxCorners انتخاب کنید.
تنظیم پارامترها: qualityLevel و minDistance برای کنترل حساسیت و فاصله حداقل بین گوشهها تعیین شدهاند. این مقادیر میتوانند برای دادههای متفاوت بهینهسازی شوند.
نمایش: گوشهها با دایرههای قرمز توخالی نمایش داده میشوند، و از matplotlib برای این کار استفاده میشود.
این تنظیمات باید به شما کمک کند تا گوشههای دقیقتری را در تصاویر پیدا کنید.
Step 1: Preprocess images (normalize to [0, 1])
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
Step 2: Compute Optical Flow using Lucas-Kanade Method
Parameters:
I1, I2 : numpy arrays
Grayscale images at t=1 and t=2, normalized to [0, 1].
windowSize : int
Size of the window for local calculations.
tau : float
Threshold for minimum eigenvalue of ATA.
Returns:
u, v : numpy arrays
Optical flow components in x and y directions.
hitMap : numpy array
Binary image indicating valid corner regions.
"""
assert windowSize % 2 == 1, "Window size must be odd."
half_win = windowSize // 2
# Compute image gradients using Sobel filter
kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.5
kernel_y = np.array([[-1, -1], [1, 1]]) * 0.5
kernel_t = np.ones((2, 2)) * 0.25
Ix = convolve(I1, kernel_x) + convolve(I2, kernel_x)
Iy = convolve(I1, kernel_y) + convolve(I2, kernel_y)
It = convolve(I2, kernel_t) - convolve(I1, kernel_t)
u = np.zeros_like(I1)
v = np.zeros_like(I1)
hitMap = np.zeros_like(I1, dtype=bool)
for i in range(half_win, I1.shape[0] - half_win):
for j in range(half_win, I1.shape[1] - half_win):
Ix_win = Ix[i-half_win:i+half_win+1, j-half_win:j+half_win+1].flatten()
Iy_win = Iy[i-half_win:i+half_win+1, j-half_win:j+half_win+1].flatten()
It_win = It[i-half_win:i+half_win+1, j-half_win:j+half_win+1].flatten()
A = np.stack((Ix_win, Iy_win), axis=1)
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau:
flow = lstsq(ATA, A.T @ b, cond=None)[0]
u[i, j], v[i, j] = flow
hitMap[i, j] = True
return u, v, hitMap
def display_results(u, v, hitMap, window_size):
"""Display optical flow results and hitmap with correctly scaled flow vectors."""
code
# Create a white canvas based on the given dimensions
flow_image = np.ones_like(u) # White background with values [1.0] (normalized range)
# Create a new figure for optical flow
plt.figure(figsize=(8, 8))
plt.imshow(flow_image, cmap='gray', vmin=0, vmax=1) # Ensures a white background
plt.title(f"Optical Flow Vectors (Window Size {window_size})")
# Plot the flow vectors on the white canvas in blue color
plt.quiver(np.arange(0, u.shape[1], step=5), np.arange(0, v.shape[0], step=5),
u[::5, ::5], v[::5, ::5], color='blue', scale=50, width=0.005) # Adjust scale and density
plt.gca().invert_yaxis() # To match the image coordinate system
plt.show()
# Display hitMap as a binary (black and white) image
plt.figure(figsize=(6, 6))
plt.imshow(hitMap, cmap='gray', vmin=0, vmax=1) # Black and white image (binary)
plt.title(f"Valid Areas (HitMap) - Window Size {window_size}")
plt.axis('off') # Hide axes
plt.show()
Calling this function for each window size after calculation as before
tau = 0.01 # Threshold for minimum eigenvalue of ATA
window_sizes = [15, 31, 101] # Three different window sizes (updated to be odd)
For each window size, compute and display results
for window_size in window_sizes:
u, v, hitMap = opticalFlow(I1, I2, window_size, tau)
display_results(u, v, hitMap, window_size)
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from scipy.ndimage import convolve
from scipy.linalg import lstsq
# Preprocess images
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
# Detect corners
def detect_corners(image, num_corners=50):
"""Detect corners using Shi-Tomasi method."""
img = (image * 255).astype(np.uint8)
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=10)
return np.int0(corners)
# Compute Optical Flow for the corners
def compute_opt_flow(I1, I2, corners, windowSize, tau):
"""Compute optical flow at the specified corners using Lucas-Kanade method."""
half_win = windowSize // 2
Ix = convolve(I1, np.array([[-1, 1], [-1, 1]]) * 0.5) + convolve(I2, np.array([[-1, 1], [-1, 1]]) * 0.5)
Iy = convolve(I1, np.array([[-1, -1], [1, 1]]) * 0.5) + convolve(I2, np.array([[-1, -1], [1, 1]]) * 0.5)
It = convolve(I2, np.ones((2, 2)) * 0.25) - convolve(I1, np.ones((2, 2)) * 0.25)
u = np.zeros_like(I1)
v = np.zeros_like(I1)
for corner in corners:
y, x = corner.ravel()
if x - half_win < 0 or x + half_win >= I1.shape[1] or y - half_win < 0 or y + half_win >= I1.shape[0]:
continue
Ix_win = Ix[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
Iy_win = Iy[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
It_win = It[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
A = np.stack((Ix_win, Iy_win), axis=1)
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau:
flow = lstsq(ATA, A.T @ b, cond=None)[0]
u[y, x], v[y, x] = flow
return u, v
# Display optical flow results
def display_results(image, u, v, corners):
"""Display the image with optical flow vectors for detected corners."""
plt.figure(figsize=(8, 8))
plt.imshow(image, cmap='gray')
for corner in corners:
x, y = corner.ravel()
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none') # Red hollow circle
plt.arrow(x, y, u[y, x] * 5, v[y, x] * 5, color='blue', head_width=1.5, head_length=1.5)
plt.title("Optical Flow at Detected Corners")
plt.axis('off')
plt.show()
# Paths to images
I1_path = "/content/coridor/hw4/data/corridor/bt.000.png"
I2_path = "/content/coridor/hw4/data/corridor/bt.001.png"
# Load and preprocess images
I1 = preprocess_image(I1_path)
I2 = preprocess_image(I2_path)
# Detect corners in the first image
corners = detect_corners(I1)
# Compute optical flow for these corners
window_size = 15 # Example window size
tau = 0.01 # Example tau value
u, v = compute_opt_flow(I1, I2, corners, window_size, tau)
# Display the results
display_results(I1, u, v, corners)
تنظیمات:
اندازه پنجره (window_size): باید با توجه به جزئیات در تصویر تنظیم شود. در اینجا مقدار 15 به عنوان پیشنهادی ذکر شده است.
تساوی (tau): تنظیم دقیق این مقدار به شما کمک میکند گوشههای معتبرتری در نقاط شناساییشده داشته باشید. مقدار 0.01 به عنوان مقدار نمونه داده شده است.
این کد گوشهها را در تصویر اولیه پیدا میکند و سپس از روش Lucas-Kanade برای محاسبه جریان نوری در آن نقاط استفاده میکند، و در نهایت نتایج را با فلشهای آبی و دایرههای قرمز توخالی نمایش میدهد.
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from scipy.ndimage import convolve
from scipy.linalg import lstsq
# Preprocess images
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
# Detect corners
def detect_corners(image, num_corners=50):
"""Detect corners using Shi-Tomasi method."""
img = (image * 255).astype(np.uint8)
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=10)
return np.int0(corners)
# Compute Optical Flow for the corners
def compute_opt_flow(I1, I2, corners, windowSize, tau):
"""Compute optical flow at the specified corners using Lucas-Kanade method."""
half_win = windowSize // 2
Ix = convolve(I1, np.array([[-1, 1], [-1, 1]]) * 0.5) + convolve(I2, np.array([[-1, 1], [-1, 1]]) * 0.5)
Iy = convolve(I1, np.array([[-1, -1], [1, 1]]) * 0.5) + convolve(I2, np.array([[-1, -1], [1, 1]]) * 0.5)
It = convolve(I2, np.ones((2, 2)) * 0.25) - convolve(I1, np.ones((2, 2)) * 0.25)
u = np.zeros_like(I1)
v = np.zeros_like(I1)
for corner in corners:
y, x = corner.ravel()
if x - half_win < 0 or x + half_win >= I1.shape[1] or y - half_win < 0 or y + half_win >= I1.shape[0]:
continue
Ix_win = Ix[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
Iy_win = Iy[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
It_win = It[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
A = np.stack((Ix_win, Iy_win), axis=1)
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau:
flow = lstsq(ATA, A.T @ b, cond=None)[0]
u[y, x], v[y, x] = flow
return u, v
# Display optical flow results
def display_results(image, u, v, corners):
"""Display the image with optical flow vectors for detected corners."""
plt.figure(figsize=(8, 8))
plt.imshow(image, cmap='gray')
# Scale factor for better visibility of arrows
scale_factor = 5 # Adjust this scale factor to increase/decrease arrow size
for corner in corners:
x, y = corner.ravel()
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none') # Red hollow circle
plt.arrow(x, y, u[y, x] * scale_factor, v[y, x] * scale_factor,
color='blue', head_width=2, head_length=3, linewidth=1.5)
plt.title("Optical Flow at Detected Corners")
plt.axis('off')
plt.show()
# Paths to images
I1_path = "/content/coridor/hw4/data/corridor/bt.000.png"
I2_path = "/content/coridor/hw4/data/corridor/bt.001.png"
# Load and preprocess images
I1 = preprocess_image(I1_path)
I2 = preprocess_image(I2_path)
# Detect corners in the first image
corners = detect_corners(I1)
# Compute optical flow for these corners
window_size = 15 # Example window size
tau = 0.01 # Example tau value
u, v = compute_opt_flow(I1, I2, corners, window_size, tau)
# Display the results
display_results(I1, u, v, corners)
تنظیمات:
مقیاس (scale_factor): این پارامتر scale_factor برای افزایش اندازه فلشها استفاده میشود. مقدار 5 برای افزایش اندازه به عنوان امتحان پایه است، اما میتوانید این مقدار را برای نتایج بهتر و واضحتر تغییر دهید.
تنظیمات فلش: همچنین عرض فلش (linewidth) و طول و عرض نوک فلشها (head_width, head_length) جهت بهبود وضوح بیشتر تنظیم شدهاند. این مقادیر هم قابل تغییر هستند.
بعد از این تنظیمات، فلشها باید واضحتر و به اندازه کافی بزرگ باشند که بتوان حرکت را بهتر مشاهده کرد.
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from scipy.ndimage import convolve
from scipy.linalg import lstsq
# Preprocess images
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
# Detect corners
def detect_corners(image, num_corners=50):
"""Detect corners using Shi-Tomasi method."""
img = (image * 255).astype(np.uint8)
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=10)
return np.int0(corners)
# Compute Optical Flow for the corners
def compute_opt_flow(I1, I2, corners, windowSize, tau):
"""Compute optical flow at the specified corners using Lucas-Kanade method."""
half_win = windowSize // 2
Ix = convolve(I1, np.array([[-1, 1], [-1, 1]]) * 0.5) + convolve(I2, np.array([[-1, 1], [-1, 1]]) * 0.5)
Iy = convolve(I1, np.array([[-1, -1], [1, 1]]) * 0.5) + convolve(I2, np.array([[-1, -1], [1, 1]]) * 0.5)
It = convolve(I2, np.ones((2, 2)) * 0.25) - convolve(I1, np.ones((2, 2)) * 0.25)
u = np.zeros_like(I1)
v = np.zeros_like(I1)
for corner in corners:
y, x = corner.ravel()
if x - half_win < 0 or x + half_win >= I1.shape[1] or y - half_win < 0 or y + half_win >= I1.shape[0]:
continue
Ix_win = Ix[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
Iy_win = Iy[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
It_win = It[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
A = np.stack((Ix_win, Iy_win), axis=1)
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau:
flow = lstsq(ATA, A.T @ b, cond=None)[0]
u[y, x], v[y, x] = flow
return u, v
# Display optical flow results
def display_results(image, u, v, corners):
"""Display the image with optical flow vectors for detected corners."""
plt.figure(figsize=(8, 8))
plt.imshow(image, cmap='gray')
# Scale factor for better visibility of arrows
scale_factor = 20 # Increased scale factor for larger arrows
for corner in corners:
x, y = corner.ravel()
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none') # Red hollow circle
plt.arrow(x, y, u[y, x] * scale_factor, v[y, x] * scale_factor,
color='blue', head_width=5, head_length=7, linewidth=2) # Larger arrow settings
plt.title("Optical Flow at Detected Corners")
plt.axis('off')
plt.show()
# Paths to images
I1_path = "/content/coridor/hw4/data/corridor/bt.000.png"
I2_path = "/content/coridor/hw4/data/corridor/bt.001.png"
# Load and preprocess images
I1 = preprocess_image(I1_path)
I2 = preprocess_image(I2_path)
# Detect corners in the first image
corners = detect_corners(I1)
# Compute optical flow for these corners
window_size = 15 # Example window size
tau = 0.01 # Example tau value
u, v = compute_opt_flow(I1, I2, corners, window_size, tau)
# Display the results
display_results(I1, u, v, corners)
تغییریافتهها:
scale_factor: به مقدار 20 تنظیم شده است؛ این مقیاسدهی باعث بزرگتر شدن بردارهای فلش میشود.
head_width و head_length: به ترتیب به 5 و 7 تنظیم شدهاند تا نوک فلشها به وضوح قابل مشاهده باشد.
این تنظیمات باید به شما کمک کند تا فلشهای جریان نوری واضحتر و بزرگتر شوند و بهتر بتوانید حرکات محاسبه شده را بر روی تصویر مشاهده کنید.
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from scipy.ndimage import convolve
from scipy.linalg import lstsq
# Preprocess images
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
# Detect corners
def detect_corners(image, num_corners=50):
"""Detect corners using Shi-Tomasi method."""
img = (image * 255).astype(np.uint8)
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=10)
return np.int0(corners)
# Compute Optical Flow for the corners
def compute_opt_flow(I1, I2, corners, windowSize, tau):
"""Compute optical flow at the specified corners using Lucas-Kanade method."""
half_win = windowSize // 2
Ix = convolve(I1, np.array([[-1, 1], [-1, 1]]) * 0.5) + convolve(I2, np.array([[-1, 1], [-1, 1]]) * 0.5)
Iy = convolve(I1, np.array([[-1, -1], [1, 1]]) * 0.5) + convolve(I2, np.array([[-1, -1], [1, 1]]) * 0.5)
It = convolve(I2, np.ones((2, 2)) * 0.25) - convolve(I1, np.ones((2, 2)) * 0.25)
u = np.zeros_like(I1)
v = np.zeros_like(I1)
for corner in corners:
y, x = corner.ravel()
if x - half_win < 0 or x + half_win >= I1.shape[1] or y - half_win < 0 or y + half_win >= I1.shape[0]:
continue
Ix_win = Ix[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
Iy_win = Iy[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
It_win = It[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
A = np.stack((Ix_win, Iy_win), axis=1)
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau:
flow = lstsq(ATA, A.T @ b, cond=None)[0]
u[y, x], v[y, x] = flow
return u, v
# Display optical flow results
def display_results(image, u, v, corners):
"""Display the image with optical flow vectors for detected corners."""
plt.figure(figsize=(8, 8))
plt.imshow(image, cmap='gray')
# Increase the scale factor to make arrows longer
scale_factor = 20 # Increased scale factor for longer arrows
# Extract corner points
x_coords, y_coords = zip(*[corner.ravel() for corner in corners])
# Plot using quiver for better arrow scaling
plt.quiver(x_coords, y_coords, u[y_coords, x_coords] * scale_factor, v[y_coords, x_coords] * scale_factor,
color='blue', angles='xy', scale_units='xy', scale=1, headwidth=5, headlength=7, linewidth=2)
plt.title("Optical Flow at Detected Corners")
plt.axis('off')
plt.show()
# Paths to images
I1_path = "/content/coridor/hw4/data/corridor/bt.000.png"
I2_path = "/content/coridor/hw4/data/corridor/bt.001.png"
# Load and preprocess images
I1 = preprocess_image(I1_path)
I2 = preprocess_image(I2_path)
# Detect corners in the first image
corners = detect_corners(I1)
# Compute optical flow for these corners
window_size = 15 # Example window size
tau = 0.01 # Example tau value
u, v = compute_opt_flow(I1, I2, corners, window_size, tau)
# Display the results
display_results(I1, u, v, corners)
توضیحات:
از plt.quiver برای رسم بردارهای جریان نوری استفاده میکنیم که به شما اجازه میدهد مستقیماً طول فلشها را با پارامتر scale کنترل کنید.
scale_factor برای این است که طول فلشها بیشتر نمایان شود. اگر هنوز نیاز به تغییر دارید، میتوانید این مقیاس را باز هم افزایش دهید.
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from scipy.ndimage import convolve
from scipy.linalg import lstsq
# Preprocess images
def preprocess_image(image_path):
"""Load and preprocess image (grayscale and normalized)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
return np.array(image) / 255.0 # Normalize to [0, 1]
# Detect corners
def detect_corners(image, num_corners=50):
"""Detect corners using Shi-Tomasi method."""
img = (image * 255).astype(np.uint8)
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=10)
return np.int0(corners)
# Compute Optical Flow for the corners
def compute_opt_flow(I1, I2, corners, windowSize, tau):
"""Compute optical flow at the specified corners using Lucas-Kanade method."""
half_win = windowSize // 2
Ix = convolve(I1, np.array([[-1, 1], [-1, 1]]) * 0.5) + convolve(I2, np.array([[-1, 1], [-1, 1]]) * 0.5)
Iy = convolve(I1, np.array([[-1, -1], [1, 1]]) * 0.5) + convolve(I2, np.array([[-1, -1], [1, 1]]) * 0.5)
It = convolve(I2, np.ones((2, 2)) * 0.25) - convolve(I1, np.ones((2, 2)) * 0.25)
u = np.zeros_like(I1)
v = np.zeros_like(I1)
for corner in corners:
y, x = corner.ravel()
if x - half_win < 0 or x + half_win >= I1.shape[1] or y - half_win < 0 or y + half_win >= I1.shape[0]:
continue
Ix_win = Ix[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
Iy_win = Iy[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
It_win = It[y-half_win:y+half_win+1, x-half_win:x+half_win+1].flatten()
A = np.stack((Ix_win, Iy_win), axis=1)
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau:
flow = lstsq(ATA, A.T @ b, cond=None)[0]
u[y, x], v[y, x] = flow
return u, v
# Display optical flow results
def display_results(image, u, v, corners):
"""Display the image with optical flow vectors for detected corners."""
plt.figure(figsize=(8, 8))
plt.imshow(image, cmap='gray')
# Extract corner points
x_coords, y_coords = zip(*[corner.ravel() for corner in corners])
# Plot red circles for corners
plt.scatter(x_coords, y_coords, color='red', s=100, facecolors='none', edgecolors='r')
# Plot using quiver for better arrow scaling
scale_factor = 50 # Scale factor for arrow length
plt.quiver(x_coords, y_coords, u[y_coords, x_coords], v[y_coords, x_coords],
color='blue', angles='xy', scale_units='xy', scale=scale_factor, headwidth=3, headlength=5, linewidth=1)
plt.title("Optical Flow at Detected Corners")
plt.axis('off')
plt.show()
# Paths to images
I1_path = "/content/coridor/hw4/data/corridor/bt.000.png"
I2_path = "/content/coridor/hw4/data/corridor/bt.001.png"
# Load and preprocess images
I1 = preprocess_image(I1_path)
I2 = preprocess_image(I2_path)
# Detect corners in the first image
corners = detect_corners(I1)
# Compute optical flow for these corners
window_size = 15 # Example window size
tau = 0.01 # Example tau value
u, v = compute_opt_flow(I1, I2, corners, window_size, tau)
# Display the results
display_results(I1, u, v, corners)
نکات:
از scatter برای رسم نقاط قرمز توخالی استفاده کردهایم که دایرههای قرمز نمایان باشند.
از quiver برای ایجاد فلشها استفاده شده و با scale_factor میزان امتداد فلشها قابل تنظیم است. این پارامتر تعیین میکند چقدر فلشها دراز باشند. میتوانید مقادیر مربوطه را افزایش دهید تا طول فلشها به مقدار دلخواه برسد.
پارامترهای headwidth و headlength برای تنظیم بیشتر شکل فلشها مورد استفاده قرار گرفتهاند.
این تغییرات باید کمک کند تا دایرهها واضح باقی بمانند و فلشها به اندازه کافی بزرگ نمایش داده شوند تا جریان نوری را بهخوبی نشان دهند.