Я попытался реализовать формулу, по которой можно было бы рассчитать коэффициенты ряда Фурье. (Я использовал видео 3B1B об этом: Видео) и написав для этого код, моим первым объектом тестирования был единичный контур логотипа Бэтмена. Сначала я делаю двоичное изображение логотипа Бэтмена и использую алгоритм марширующих квадратов, чтобы найти его контур. после этого я масштабирую значения и получаю следующие результаты:
А вот код для создания этих точек: (Contour_Classifier.py)
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure, draw
def read_binary_image(file_path):
# Open the file and read line by line
with open(file_path, 'r') as file:
lines = file.readlines()
height, width = len(lines), len(lines[0])
print(height, width)
# Process lines into a 2D numpy array
image_data = []
for i in range(height + 2):
arr = []
for j in range(width + 2):
arr.append(0)
image_data.append(arr)
for i in range(2, height + 1):
for j in range(2, width + 1):
if(lines[j - 2] != '1'):
image_data[j] = 0
else:
image_data[j] = 1
# Convert list to numpy array for easier manipulation
image_array = np.array(image_data)
return image_array
def display_image(image_array):
# Display the binary image using matplotlib
plt.imshow(image_array, cmap="gray")
plt.axis('off') # Hide axes
plt.show()
# Example usage
file_path = 'KOREKT\images\sbetmeni.txt' # Replace with the path to your file
image_array = read_binary_image(file_path)
#display_image(image_array)
def visualize_colored_contours(contours, title="Colored Contours"):
# Create a plot
plt.figure(figsize=(8, 8))
for i, contour in enumerate(contours):
# Extract X and Y coordinates
x, y = zip(*contour)
# Plot the points with a unique color
plt.plot(x, y, marker='o', label=f'Contour {i+1}')
# Visualize the normalized contours
visualize_colored_contours(contours)
< /code>
Теперь мы переходим к основной части, где мы реализуем алгоритм серии Фурье. Я разделяю время на меж (t) на количество предоставленных точек, и я предполагаю, что все эти точки относительно T имеют одинаковые расстояния между друг другу. Я использую аппроксимацию интеграла в качестве суммы точек, которые предоставлены в формуле. /> И вот Code реализует его (fourier_coefficients.py): < /p>
import numpy as np
def calculate_Fourier(points, num_coefficients):
complex_points = []
for point in points:
complex_points.append(point[0] + 1j * point[1])
t = np.linspace(0, 1, len(complex_points), endpoint=False)
for i in range(num_coefficients):
c_k = np.sum(complex_points * np.exp(-2j * np.pi * i * t) * t[1])
return c_k
< /code>
(Примечание: для этого кода T1 в основном является Deltat, потому что он равна 1 /len (specblem_points)
и теперь, на следующем слайде, я оживляю весь процесс, где я Также написал дополнительный фрагмент кода для создания GIF. Является ли фрагмент кода для этой части < /p>
import numpy as np
import matplotlib.pyplot as plt
import imageio
from Fourier_Coefficients import calculate_Fourier
from Countour_Classifier import contours
# List to store file names for GIF creation
png_files = []
# Generate plots iteratively
for i in range(len(contours[0])):
contour_coefficients = []
for contour in contours:
contour_coefficients.append(calculate_Fourier(contour, i))
# Fourier coefficients (complex numbers) and frequencies
coefficients = contour_coefficients[0] # First contour
frequencies = np.arange(len(coefficients))
# Time parameters
t = np.linspace(0, 1, len(coefficients)) # One period
curve = np.zeros(len(t), dtype=complex)
# Use the first (i + 1) coefficients
for j in range(len(coefficients)):
c, f = coefficients[j], frequencies[j]
curve += c * np.exp(1j * 2 * np.pi * f * t)
# Plotting
plt.figure(figsize=(8, 8))
plt.plot(curve.real, curve.imag, label="Trajectory", color="blue")
plt.scatter(0, 0, color="black", label="Origin")
plt.axis("equal")
plt.title(f"Fourier Series with {i + 1} Coefficients")
plt.xlabel("Real Part (X)")
plt.ylabel("Imaginary Part (Y)")
plt.legend()
plt.text(-0.5, -0.5, f"Using {i + 1} coefficients", fontsize=12, color="red")
# Save the figure as a PNG file
filename = f"fourier_{i + 1}_coefficients.png"
plt.savefig(filename)
plt.close()
# Append the file name to the list
png_files.append(filename)
# Create a GIF from the PNG files
gif_filename = "fourier_series.gif"
with imageio.get_writer(gif_filename, mode='I', duration=0.5) as writer:
for filename in png_files:
image = imageio.imread(filename)
writer.append_data(image)
print("Plots saved as PNG files and GIF created as 'fourier_series.gif'.")
< /code>
Теперь это результат
gif < /p> наблюдение #1 < /strong>
Когда число коэффициентов 0, 1, 2 или 3 он ничего не рисует.
наблюдение #2
Повышение номера коэффициентов, мы Получите шаткую круговую форму, где нижняя часть изображения немного более идентична оригинальной, но наносится на его крылья наблюдение № 3 < /p>
Когда мы приближаемся к LEN (Complex_Numbers), изменяется ситуация, и мы получаем эти странные формы, отличающиеся от круговой < /p> наблюдение # 4
Когда мы превзойдут LEN (ocleds_number), он рисует случайный тамплер
после всей этой информации Ребята помогите мне, что не так с моим кодом
Я попытался реализовать формулу, по которой можно было бы рассчитать коэффициенты ряда Фурье. (Я использовал видео 3B1B об этом: Видео) и написав для этого код, моим первым объектом тестирования был единичный контур логотипа Бэтмена. Сначала я делаю двоичное изображение логотипа Бэтмена и использую алгоритм марширующих квадратов, чтобы найти его контур. после этого я масштабирую значения и получаю следующие результаты: [img]https://i.sstatic.net/QSm82Ucn.png[/img] А вот код для создания этих точек: (Contour_Classifier.py) import numpy as np import matplotlib.pyplot as plt from skimage import measure, draw
def read_binary_image(file_path): # Open the file and read line by line with open(file_path, 'r') as file: lines = file.readlines()
height, width = len(lines), len(lines[0]) print(height, width) # Process lines into a 2D numpy array image_data = []
for i in range(height + 2): arr = [] for j in range(width + 2): arr.append(0) image_data.append(arr)
for i in range(2, height + 1): for j in range(2, width + 1): if(lines[i - 2][j - 2] != '1'): image_data[i][j] = 0 else: image_data[i][j] = 1
# Convert list to numpy array for easier manipulation image_array = np.array(image_data)
return image_array
def display_image(image_array): # Display the binary image using matplotlib plt.imshow(image_array, cmap="gray") plt.axis('off') # Hide axes plt.show()
# Example usage file_path = 'KOREKT\images\sbetmeni.txt' # Replace with the path to your file image_array = read_binary_image(file_path) #display_image(image_array)
def visualize_colored_contours(contours, title="Colored Contours"): # Create a plot plt.figure(figsize=(8, 8))
for i, contour in enumerate(contours): # Extract X and Y coordinates x, y = zip(*contour) # Plot the points with a unique color plt.plot(x, y, marker='o', label=f'Contour {i+1}')
# Visualize the normalized contours visualize_colored_contours(contours) < /code> Теперь мы переходим к основной части, где мы реализуем алгоритм серии Фурье. Я разделяю время на меж (t) на количество предоставленных точек, и я предполагаю, что все эти точки относительно T имеют одинаковые расстояния между друг другу. Я использую аппроксимацию интеграла в качестве суммы точек, которые предоставлены в формуле. /> И вот Code реализует его (fourier_coefficients.py): < /p> import numpy as np
def calculate_Fourier(points, num_coefficients): complex_points = [] for point in points: complex_points.append(point[0] + 1j * point[1])
t = np.linspace(0, 1, len(complex_points), endpoint=False)
for i in range(num_coefficients): c_k[i] = np.sum(complex_points * np.exp(-2j * np.pi * i * t) * t[1])
return c_k < /code> (Примечание: для этого кода T1 в основном является Deltat, потому что он равна 1 /len (specblem_points) и теперь, на следующем слайде, я оживляю весь процесс, где я Также написал дополнительный фрагмент кода для создания GIF. Является ли фрагмент кода для этой части < /p> import numpy as np import matplotlib.pyplot as plt import imageio from Fourier_Coefficients import calculate_Fourier from Countour_Classifier import contours
# List to store file names for GIF creation png_files = []
# Generate plots iteratively for i in range(len(contours[0])):
contour_coefficients = []
for contour in contours: contour_coefficients.append(calculate_Fourier(contour, i))
# Fourier coefficients (complex numbers) and frequencies coefficients = contour_coefficients[0] # First contour frequencies = np.arange(len(coefficients))
# Time parameters t = np.linspace(0, 1, len(coefficients)) # One period curve = np.zeros(len(t), dtype=complex)
# Use the first (i + 1) coefficients for j in range(len(coefficients)): c, f = coefficients[j], frequencies[j] curve += c * np.exp(1j * 2 * np.pi * f * t)
# Plotting plt.figure(figsize=(8, 8)) plt.plot(curve.real, curve.imag, label="Trajectory", color="blue") plt.scatter(0, 0, color="black", label="Origin") plt.axis("equal") plt.title(f"Fourier Series with {i + 1} Coefficients") plt.xlabel("Real Part (X)") plt.ylabel("Imaginary Part (Y)") plt.legend() plt.text(-0.5, -0.5, f"Using {i + 1} coefficients", fontsize=12, color="red")
# Save the figure as a PNG file filename = f"fourier_{i + 1}_coefficients.png" plt.savefig(filename) plt.close()
# Append the file name to the list png_files.append(filename)
# Create a GIF from the PNG files gif_filename = "fourier_series.gif" with imageio.get_writer(gif_filename, mode='I', duration=0.5) as writer: for filename in png_files: image = imageio.imread(filename) writer.append_data(image)
print("Plots saved as PNG files and GIF created as 'fourier_series.gif'.") < /code> Теперь это результат gif < /p> [b] наблюдение #1 < /strong> Когда число коэффициентов 0, 1, 2 или 3 он ничего не рисует. наблюдение #2 [/b] Повышение номера коэффициентов, мы Получите шаткую круговую форму, где нижняя часть изображения немного более идентична оригинальной, но наносится на его крылья [b] наблюдение № 3 [/b] < /p> Когда мы приближаемся к LEN (Complex_Numbers), изменяется ситуация, и мы получаем эти странные формы, отличающиеся от круговой < /p> [b] наблюдение # 4 [/b] Когда мы превзойдут LEN (ocleds_number), он рисует случайный тамплер после всей этой информации Ребята помогите мне, что не так с моим кодом