USER
کد زیر را تحلیل کنید و کاری کنید تراز تصاویرش بهبود یابد شیفت بردار جابه جایی را تغییر دهید یا کاری کنید بتوان به صورت دستی کمی آند را تغییر داد تا تصاویر هم تراز شوند: import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
# مسیرهای تصاویر
image_paths = [
'/content/prokudin-Gorskii2/data_2/01047u.tif',
'/content/prokudin-Gorskii2/data_2/01861a.tif'
]
# تابع برای پیدا کردن شیفت با استفاده از همبستگی نرمالیزه
def find_shift_with_ncc(img_ref, img_to_align, shift_range=10, window_size=50):
best_shift = (0, 0)
max_corr = -1
# نرمال کردن تصاویر
img_ref = (img_ref - np.mean(img_ref)) / (np.std(img_ref) + 1e-5)
img_to_align = (img_to_align - np.mean(img_to_align)) / (np.std(img_to_align) + 1e-5)
# انتخاب ناحیه مرکزی برای محاسبه همبستگی
center_y, center_x = img_ref.shape[0] // 2, img_ref.shape[1] // 2
half_window = window_size // 2
img_ref_window = img_ref[center_y-half_window:center_y+half_window, center_x-half_window:center_x+half_window]
for x_shift in range(-shift_range, shift_range + 1):
for y_shift in range(-shift_range, shift_range + 1):
M = np.float32([[1, 0, x_shift], [0, 1, y_shift]])
shifted = cv2.warpAffine(img_to_align, M, (img_to_align.shape[1], img_to_align.shape[0]))
# اعمال ماسک برای انتخاب ناحیه موردنظر برای همبستگی
shifted_window = shifted[center_y-half_window:center_y+half_window, center_x-half_window:center_x+half_window]
valid_mask = (shifted_window != 0) & (img_ref_window != 0)
# اضافه کردن بررسی برای وجود ماسک معتبر
if np.any(valid_mask):
corr = np.sum(img_ref_window[valid_mask] * shifted_window[valid_mask])
corr /= (np.sqrt(np.sum(img_ref_window[valid_mask]**2)) * np.sqrt(np.sum(shifted_window[valid_mask]**2)) + 1e-5)
# بررسی اینکه آیا corr بهتر از مقدار فعلی max_corr است یا خیر
if corr > max_corr:
max_corr = corr
best_shift = (x_shift, y_shift)
return best_shift
# تابع برای اعمال شیفت
def apply_shift(image, shift):
M = np.float32([[1, 0, -shift[0]], [0, 1, -shift[1]]])
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
return shifted
# تابع برای ساخت هرم Gaussian از تصویر
def build_image_pyramid(image, levels=3):
pyramid = [image]
for i in range(1, levels):
image = cv2.pyrDown(image) # کاهش رزولوشن
pyramid.append(image)
return pyramid
# تابع برای ترازبندی تصویر با استفاده از هرم
def pyramid_align(ref_image, image, levels=3, shift_range=10):
# ساخت هرم تصاویر برای هر دو تصویر
ref_pyramid = build_image_pyramid(ref_image, levels)
img_pyramid = build_image_pyramid(image, levels)
shift = (0, 0) # مقدار اولیه برای شیفت
for level in range(levels-1, -1, -1):
# تصویر مرجع و تصویر دیگر در سطح فعلی از هرم
ref_level = ref_pyramid[level]
img_level = img_pyramid[level]
# پیدا کردن شیفت در سطح فعلی از هرم
level_shift = find_shift_with_ncc(ref_level, img_level, shift_range=shift_range)
# بهروزرسانی شیفت برای سطح فعلی
shift = (shift[0] + level_shift[0] * (2**level), shift[1] + level_shift[1] * (2**level))
return shift
for image_path in image_paths:
if not os.path.exists(image_path):
print(f"فایل {image_path} وجود ندارد.")
continue
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
print(f"تصویر {image_path} یافت نشد یا خواندن آن با مشکل مواجه شد.")
continue
height = image.shape[0] // 3
width = image.shape[1]
# جداکردن کانالها از یک تصویر
B = image[0:height]
G = image[height:2*height]
R = image[2*height:3*height]
ref = R
# پیدا کردن شیفت با استفاده از هرم تصویر
shift_G_found = pyramid_align(ref, G, levels=3, shift_range=10)
shift_B_found = pyramid_align(ref, B, levels=3, shift_range=10)
print(f"برای تصویر {os.path.basename(image_path)}:")
print(f"شیفت لایه سبز: {shift_G_found}")
print(f"شیفت لایه آبی: {shift_B_found}")
# اعمال شیفت
aligned_G = apply_shift(G, shift_G_found)
aligned_B = apply_shift(B, shift_B_found)
# ادغام لایههای تراز شده به یک تصویر رنگی
aligned_image = cv2.merge([aligned_B, aligned_G, ref])
# نمایش تصویر تراز شده
plt.figure(figsize=(10,10))
plt.title(f'Aligned Image - {os.path.basename(image_path)}')
aligned_image_rgb = cv2.cvtColor(aligned_image, cv2.COLOR_BGR2RGB)
plt.imshow(aligned_image_rgb)
plt.axis('off')
plt.show()
# ذخیره تصویر تراز شده
output_filename = f"aligned_{os.path.basename(image_path)}"
cv2.imwrite(output_filename, aligned_image)
print(f"تصویر تراز شده با موفقیت ذخیره شد: '{output_filename}'\n")ASSISTANT
برای بهبود تراز تصاویر، میتوان پارامترهای برنامه مانند دامنه شیفت و اندازه پنجره را تنظیم کرد. برای افزایش کنترل کاربر بر روی تراز تصاویر، میتوانید به کاربر اجازه دهید این پارامترها را به صورت دستی تنظیم کند. در زیر نمونهای از تغییریافتهی کد با این قابلیت قرار دارد:
```python
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
# مسیرهای تصاویر
image_paths = [
'/content/prokudin-Gorskii2/data_2/01047u.tif',
'/content/prokudin-Gorskii2/data_2/01861a.tif'
]
# تابع برای پیدا کردن شیفت با استفاده از همبستگی نرمالیزه
def find_shift_with_ncc(img_ref, img_to_align, shift_range=10, window_size=50):
best_shift = (0, 0)
max_corr = -1
# نرمال کردن تصاویر
img_ref = (img_ref - np.mean(img_ref)) / (np.std(img_ref) + 1e-5)
img_to_align = (img_to_align - np.mean(img_to_align)) / (np.std(img_to_align) + 1e-5)
# انتخاب ناحیه مرکزی برای محاسبه همبستگی
center_y, center_x = img_ref.shape[0] // 2, img_ref.shape[1] // 2
half_window = window_size // 2
img_ref_window = img_ref[center_y-half_window:center_y+half_window, center_x-half_window:center_x+half_window]
for x_shift in range(-shift_range, shift_range + 1):
for y_shift in range(-shift_range, shift_range + 1):
M = np.float32([[1, 0, x_shift], [0, 1, y_shift]])
shifted = cv2.warpAffine(img_to_align, M, (img_to_align.shape[1], img_to_align.shape[0]))
# اعمال ماسک برای انتخاب ناحیه موردنظر برای همبستگی
shifted_window = shifted[center_y-half_window:center_y+half_window, center_x-half_window:center_x+half_window]
valid_mask = (shifted_window != 0) & (img_ref_window != 0)
# اضافه کردن بررسی برای وجود ماسک معتبر
if np.any(valid_mask):
corr = np.sum(img_ref_window[valid_mask] * shifted_window[valid_mask])
corr /= (np.sqrt(np.sum(img_ref_window[valid_mask]**2)) * np.sqrt(np.sum(shifted_window[valid_mask]**2)) + 1e-5)
# بررسی اینکه آیا corr بهتر از مقدار فعلی max_corr است یا خیر
if corr > max_corr:
max_corr = corr
best_shift = (x_shift, y_shift)
return best_shift
# تابع برای اعمال شیفت
def apply_shift(image, shift):
M = np.float32([[1, 0, -shift[0]], [0, 1, -shift[1]]])
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
return shifted
# تابع برای ساخت هرم Gaussian از تصویر
def build_image_pyramid(image, levels=3):
pyramid = [image]
for i in range(1, levels):
image = cv2.pyrDown(image) # کاهش رزولوشن
pyramid.append(image)
return pyramid
# تابع برای ترازبندی تصویر با استفاده از هرم
def pyramid_align(ref_image, image, levels=3, shift_range=10, window_size=50):
# ساخت هرم تصاویر برای هر دو تصویر
ref_pyramid = build_image_pyramid(ref_image, levels)
img_pyramid = build_image_pyramid(image, levels)
shift = (0, 0) # مقدار اولیه برای شیفت
for level in range(levels-1, -1, -1):
# تصویر مرجع و تصویر دیگر در سطح فعلی از هرم
ref_level = ref_pyramid[level]
img_level = img_pyramid[level]
# پیدا کردن شیفت در سطح فعلی از هرم
level_shift = find_shift_with_ncc(ref_level, img_level, shift_range=shift_range, window_size=window_size)
# بهروزرسانی شیفت برای سطح فعلی
shift = (shift[0] + level_shift[0] * (2**level), shift[1] + level_shift[1] * (2**level))
return shift
# تنظیمات اولیه، کاربر میتواند این مقادیر را تغییر دهد
levels = 3
shift_range = 10
window_size = 50
for image_path in image_paths:
if not os.path.exists(image_path):
print(f"فایل {image_path} وجود ندارد.")
continue
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
print(f"تصویر {image_path} یافت نشد یا خواندن آن با مشکل مواجه شد.")
continue
height = image.shape[0] // 3
width = image.shape[1]
# جداکردن کانالها از یک تصویر
B = image[0:height]
G = image[height:2*height]
R = image[2*height:3*height]
ref = R
# پیدا کردن شیفت با استفاده از هرم تصویر
shift_G_found = pyramid_align(ref, G, levels=levels, shift_range=shift_range, window_size=window_size)
shift_B_found = pyramid_align(ref, B, levels=levels, shift_range=shift_range, window_size=window_size)
print(f"برای تصویر {os.path.basename(image_path)}:")
print(f"شیفت لایه سبز: {shift_G_found}")
print(f"شیفت لایه آبی: {shift_B_found}")
# اعمال شیفت
aligned_G = apply_shift(G, shift_G_found)
aligned_B = apply_shift(B, shift_B_found)
# ادغام لایههای تراز شده به یک تصویر رنگی
aligned_image = cv2.merge([aligned_B, aligned_G, ref])
# نمایش تصویر تراز شده
plt.figure(figsize=(10,10))
plt.title(f'Aligned Image - {os.path.basename(image_path)}')
aligned_image_rgb = cv2.cvtColor(aligned_image, cv2.COLOR_BGR2RGB)
plt.imshow(aligned_image_rgb)
plt.axis('off')
plt.show()
# ذخیره تصویر تراز شده
output_filename = f"aligned_{os.path.basename(image_path)}"
cv2.imwrite(output_filename, aligned_image)
print(f"تصویر تراز شده با موفقیت ذخیره شد: '{output_filename}'\n")
```
### تغییرات انجام شده:
1. **پارامترهای کاربر:** متغیرهای `levels`, `shift_range`, و `window_size` به عنوان پارامترهای قابل تغییر توسط کاربر قرار داده شد.
2. **تابع `pyramid_align`:** این تابع اکنون `window_size` را نیز دریافت میکند که میتواند توسط کاربر تعیین شود.
با تنظیم پارامترهای `shift_range`، `window_size` و `levels`، کاربر میتواند به دقت بیشتری برای تراز کردن تصاویر برسد که ممکن است به نتایج بهتری منجر شود.