اگر هیچ جهتی نمایش داده نمیشود، ممکن است یکی از موارد زیر باعث این مشکل باشد:
دلایل ممکن:
-
نقطههای گوشهای (Corners) در تصویر کافی یا معتبر نیستند:
گوشهها ممکن است در بخشهای تصویر که عملاً هیچ حرکتی وجود ندارد، شناسایی شده باشند. بدون نقاط گوشه با اطلاعات معتبر، جریان نوری قابل محاسبه نخواهد بود.
-
مقادیر جریان نوری خیلی کوچک هستند (فلشها حذف شدهاند):
پارامتر آستانه (threshold) در کد تعریف شده تا بردارهای نوری خیلی کوچک حذف شوند. اگر تمام بردارها کوچکتر از threshold باشند، هیچ فلشی نمایش داده نمیشود.
-
تغییرات بین تصاویر ورودی کوچک است:
اگر شیء در تصویر واقعی حرکتی ندارد یا تغییرات هندسی یا شدت روشنایی بین فریمها خیلی کم است، جریان نوری نمیتواند به درستی جهت حرکت را محاسبه کند.
-
ابعاد تصویر ورودی متفاوت است:
اگر دو تصویر ورودی ابعاد متفاوت داشته باشند، محاسبه اشتباه خواهد بود و نتایج نادرست خواهند بود.
راهکارها برای حل مشکل:
1. بررسی گوشههای شناسایی شده:
ابتدا بررسی کنید که تعداد گوشههایی که شناسایی شدهاند منطقی باشند و در موقعیتهای واقعی در تصویر قرار دارند. میتوانید این گوشهها را روی تصویر رسم کنید:
def visualize_corners(image, corners):
"""Plot detected corners on the input image."""
plt.imshow(image, cmap='gray')
for corner in corners:
x, y = corner.ravel()
plt.plot(x, y, 'ro', markersize=5)
plt.title("Detected Corners")
plt.axis("off")
plt.show()
# Visualize corners
visualize_corners(I1, corners)
2. کاهش آستانه (threshold) برای نمایش بردارهای کوچک:
مقدار پیشفرض threshold=0.001 ممکن است خیلی بالا باشد و بردارهای کوچک را فیلتر کند. این مقدار را کاهش دهید، برای مثال:
display_results(I1, u, v, corners, threshold=0.0001, scale_factor=200)
3. بررسی حرکت بین تصاویر:
حرکت شیء در تصاویر ورودی را بررسی کنید. اگر هیچ حرکتی بین دو فریم وجود ندارد یا تغییر خیلی کوچک است، نتایج منطقی خواهند بود. میتوانید تصاویر ورودی را رسم کنید:
plt.imshow(I1, cmap='gray')
plt.title('First Image')
plt.show()
plt.imshow(I2, cmap='gray')
plt.title('Second Image')
plt.show()
4. تبدیل تصاویر به سایز یکسان:
مطمئن شوید که ابعاد تصاویر یکسان باشند. میتوانید تصاویر را به ابعاد یکسان تغییر دهید:
from PIL import Image
target_size = (432, 568) # Change width and height based on your data
def preprocess_image(image_path, target_size=None):
image = Image.open(image_path).convert('L') # Convert to grayscale
if target_size: # Resize if necessary
image = image.resize(target_size, Image.Resampling.LANCZOS)
return np.array(image) / 255.0
# Resize both images to same dimensions
I1 = preprocess_image(I1_path, target_size)
I2 = preprocess_image(I2_path, target_size)
بهروزرسانی کد نمایش بردارها:
برای افزایش وضوح و تسهیل نمایش بردارهای کوچکتر، کد تابع display_results به شکل زیر بهروزرسانی میشود:
def display_results(image, u, v, corners, threshold=0.0001, scale_factor=300):
"""Display the image with optical flow vectors for detected corners."""
plt.figure(figsize=(12, 12))
plt.imshow(image, cmap='gray')
for corner in corners:
x, y = corner.ravel()
# Check for small or noisy vectors
magnitude = np.sqrt(u[y, x]**2 + v[y, x]**2) # Compute vector magnitude
if magnitude < threshold:
continue # Skip small motion
# Draw the corner point
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none') # Red hollow circle
# Draw flow vector as an arrow
plt.arrow(x, y, u[y, x] * scale_factor, v[y, x] * scale_factor,
color='blue', head_width=5, head_length=10, linewidth=2)
plt.title("Optical Flow (Lucas-Kanade)", fontsize=16)
plt.axis('off')
plt.show()
تست کد اصلاحشده:
import numpy as np
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from scipy.linalg import lstsq
# Preprocess images (convert to grayscale and normalize)
def preprocess_image(image_path, target_size=None):
"""Load and preprocess image (grayscale, normalize, and resize if needed)."""
image = Image.open(image_path).convert('L') # Convert to grayscale
if target_size:
image = image.resize(target_size, Image.Resampling.LANCZOS)
return np.array(image) / 255.0 # Normalize to [0, 1]
# Detect corners in the image
def detect_corners(image, num_corners=50):
"""Detect corners using the Shi-Tomasi method."""
img = (image * 255).astype(np.uint8)
corners = cv2.goodFeaturesToTrack(img, maxCorners=num_corners, qualityLevel=0.01, minDistance=7)
return np.intp(corners) # Use np.intp to avoid deprecation warnings
# Compute Optical Flow for corners
def compute_opt_flow(I1, I2, corners, window_size, tau):
"""Compute optical flow for corners using the Lucas-Kanade method."""
half_win = window_size // 2
Ix = cv2.Sobel(I1, cv2.CV_64F, 1, 0, ksize=3) # Gradient in X
Iy = cv2.Sobel(I1, cv2.CV_64F, 0, 1, ksize=3) # Gradient in Y
It = I2 - I1 # Temporal gradient
u = np.zeros_like(I1)
v = np.zeros_like(I1)
for corner in corners:
y, x = corner.ravel()
if x - half_win < 0 or y - half_win < 0 or x + half_win >= I1.shape[1] or y + half_win >= I1.shape[0]:
continue
# Extract window for gradients
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()
# Solve for flow vectors using least squares
A = np.vstack((Ix_win, Iy_win)).T
b = -It_win
ATA = A.T @ A
eigenvalues = np.linalg.eigvals(ATA)
if min(eigenvalues) >= tau: # Check eigenvalue threshold
flow = lstsq(ATA, A.T @ b, cond=None)[0] # Solve linear system
u[y, x], v[y, x] = flow
return u, v
# Display results with arrows
def display_results(image, u, v, corners, threshold=0.0001, scale_factor=200):
"""Display optical flow with arrows."""
plt.figure(figsize=(12, 12))
plt.imshow(image, cmap='gray')
for corner in corners:
x, y = corner.ravel()
magnitude = np.sqrt(u[y, x]**2 + v[y, x]**2)
if magnitude < threshold:
continue
plt.plot(x, y, 'ro', markersize=5, markerfacecolor='none')
plt.arrow(x, y, u[y, x] * scale_factor, v[y, x] * scale_factor,
color='blue', head_width=5, head_length=10, linewidth=2)
plt.title("Optical Flow (Lucas-Kanade)", fontsize=16)
plt.axis('off')
plt.show()
# Paths
I1_path = "image1.png"
I2_path = "image2.png"
# Preprocess images
target_size = (432, 568) # Resize both images to the same size
I1 = preprocess_image(I1_path, target_size)
I2 = preprocess_image(I2_path, target_size)
# Detect corners
corners = detect_corners(I1)
# Compute optical flow
window_size = 15
tau = 1e-2
u, v = compute_opt_flow(I1, I2, corners, window_size, tau)
# Display results
display_results(I1, u, v, corners)
بررسی:
- تصاویر ورودی و ابعاد آنها تنظیم شوند.
- اگر مشکل ادامه داشت، اطلاعات بیشتری از تصاویر و خطای احتمالی ارائه دهید تا مشکل دقیقتر بررسی شود. 😊