from PIL import Image import numpy as np import math import os T=50#阈值设定,大于T则判定偏离xy轴过多…
Jump to turn (6)
- User
from PIL import Image import numpy as np import math import os
T=50#阈值设定,大于T则判定偏离xy轴过多
#复数类 class complex: def init(self): self.real = 0.0 self.image = 0.0
#复数乘法 def mul_ee(complex0, complex1): complex_ret = complex() complex_ret.real = complex0.real * complex1.real - complex0.image * complex1.image complex_ret.image = complex0.real * complex1.image + complex0.image * complex1.real return complex_ret
#复数加法 def add_ee(complex0, complex1): complex_ret = complex() complex_ret.real = complex0.real + complex1.real complex_ret.image = complex0.image + complex1.image return complex_ret
#复数减法 def sub_ee(complex0, complex1): complex_ret = complex() complex_ret.real = complex0.real - complex1.real complex_ret.image = complex0.image - complex1.image return complex_ret
#对输入数据进行倒序排列
def forward_input_data(input_data, num):
j = num //2
for i in range(1, num - 2):
if(i < j):
complex_tmp = input_data[i]
input_data[i] = input_data[j]
input_data[j] = complex_tmp
#print "forward x[%d] <==> x[%d]" % (i, j)
k = num // 2
while (j >= k):
j = j - k
k = k // 2
j = j + k
#实现1D FFT def fft_1d(in_data, num): PI = 3.1415926 forward_input_data(in_data, num) #倒序输入数据
#计算蝶形级数,也就是迭代次数
M = 1 #num = 2^m
tmp = num // 2;
while (tmp != 1):
M = M + 1
tmp = tmp // 2
#print "FFT level:%d" % M
complex_ret = complex()
for L in range(1, M + 1):
B = int(math.pow(2, L -1)) #B为指数函数返回值,为float,需要转换integer
for J in range(0, B):
P = math.pow(2, M - L) * J
for K in range(J, num, int(math.pow(2, L))):
#print "L:%d B:%d, J:%d, K:%d, P:%f" % (L, B, J, K, P)
complex_ret.real = math.cos((2 * PI / num) * P)
complex_ret.image = -math.sin((2 * PI / num) * P)
complex_mul = mul_ee(complex_ret, in_data[K + B])
complex_add = add_ee(in_data[K], complex_mul)
complex_sub = sub_ee(in_data[K], complex_mul)
in_data[K] = complex_add
in_data[K + B] = complex_sub
#print "A[%d] real: %f, image: %f" % (K, in_data[K].real, in_data[K].image)
# print "A[%d] real: %f, image: %f" % (K + B, in_data[K + B].real, in_data[K + B].image)
def test_fft_1d(in_data): #in_data = [2,3,4,5,7,9,10,11,100,12,14,11,56,12,67,12] #待测试的x点元素 k=1 while(1): if len(in_data)>pow(2,k) and len(in_data)<=pow(2,k+1):#不足的补0 #fftlen=pow(2,k+1) #in_data.extend([0 for i in range(pow(2,k+1)-len(in_data))]) fftlen=pow(2,k) break k+=1 #变量data为长度为x、元素为complex类实例的list,用于存储输入数据 data = [(complex()) for i in range(len(in_data))] #将8个测试点转换为complex类的形式,存储在变量data中 for i in range(len(in_data)): data[i].real = in_data[i] data[i].image = 0.0
##输出FFT需要处理的数据
#print("The input data:")
#for i in range(len(in_data)):
# print("x[%d] real: %f, image: %f" % (i, data[i].real, data[i].image))
fft_1d(data, fftlen)
##输出经过FFT处理后的结果
#print("The output data:")
#for i in range(len(in_data)):
# print("X[%d] real: %f, image: %f" % (i, data[i].real, data[i].image))
Tnum=0
for i in range(len(in_data)):#虚实值都大于T的才叫偏离
if abs(data[i].real)>T and abs(data[i].image)>T:
Tnum+=1
print(Tnum)
print(str(round(Tnum/len(in_data),4)*100)+"%")
if name=="main":
#test the 1d fft
#in_data=[2,3,4,5,7,9,10,11]
# image_path='/home/notebook/data/group/Ruby/stereo-from-mono-master/refine_results'
image_path='/home/notebook/data/group/Ruby/stereo-from-mono-master/dirty_results'
filenames=[file for file in os.listdir(image_path) if("_disp.png" in file)]
for i in range(len(filenames)):
print(i)
filename=os.path.join(image_path,filenames[i])
demo=Image.open(filename)
im=np.array(demo.convert('L'))#灰度化矩阵
in_data=[]
for item in im:
in_data.extend(item)
test_fft_1d(in_data)
# if round(Tnum/len(in_data),4)*100 > 48
# in_data=[]
# for item in im:
# in_data.extend(item)
# test_fft_1d(in_data)
The provided code snippet is intended to perform the Fast Fourier Transform (FFT) on 1D data derived from images. Let's break down the steps and better understand what each component does:
Complex Number Operations:
complex class and implements addition, subtraction, and multiplication for complex numbers.FFT Implementation:
fft_1d(). It performs the transformation by reordering the input data through bit-reversal and using the Cooley-Tukey FFT algorithm to compute the discrete Fourier transform.Data Preparation & Processing:
in_data).Threshold Calculation:
T. It seems to measure how much of the data diverges from the axis, likely indicating the presence of a certain feature or anomaly.Main Function:
Here's a more detailed explanation of each component:
Complex Number Operations: The class and its functions are straightforward implementations of mathematical operations on complex numbers. You might consider using Python's built-in complex type to simplify these parts.
FFT Algorithm: The fft_1d() function takes a list of complex numbers and computes their FFT using a radix-2 Cooley-Tukey method. Note that forward_input_data() is used to rearrange input data as part of the in-place FFT.
Image Processing: The process of converting images to grayscale and flattening them into a list makes the data suitable for one-dimensional FFT processing.
Threshold Calculation: After the transform, test_fft_1d() evaluates the transformed signal against a threshold T and checks how many components exceed this threshold.
请说中文
当然可以!这个代码片段的作用是对从图像中提取的一维数据执行快速傅里叶变换(FFT)。下面是对代码各部分的详细解释:
复数运算:
complex 类,并实现了复数的加法、减法和乘法。FFT 实现:
fft_1d() 函数中实现。该函数通过使用倒序排列输入数据和 Cooley-Tukey FFT 算法来计算离散傅里叶变换。数据准备与处理:
in_data)。阈值计算:
T。这可能用来检测某些特征或异常。主函数:
性能:可以使用 Python 内置的 complex 类型和 numpy.fft 模块来简化和加速实现过程。
代码清晰度:将与 fft_1d() 相关的函数与可重用的工具函数区分开来可以提高代码的可读性。
错误处理:为文件读取、图像数据处理以及数学运算添加错误处理能使脚本更加健壮。
模块化结构:将代码拆分为不同的函数用于图像加载、FFT 处理和结果评估,可以提高代码的可维护性和可用性。
如果你需要对这个代码进行具体的修改或优化,我很乐意提供帮助!
请把这个代码写成在GPU上运行的版本
要在 GPU 上运行这个代码,我们可以使用 cupy 库,它是 numpy 的 GPU 版本,可以利用 NVIDIA 的 CUDA 来加速计算。首先,确保你的环境中安装了 cupy,安装方式如下:
pip install cupy-cuda11x # 选择适合你的 CUDA 版本
接下来,是将代码转换为在 GPU 上运行的版本。我们将使用 cupy 代替 numpy,并使用 cupy.fft 来进行 GPU 加速的快速傅里叶变换。以下是修改后的代码:
import cupy as cp
from PIL import Image
import os
T = 50 # 阈值设定,大于T则判定偏离xy轴过多
def compute_fft_on_gpu(in_data):
# 将数据转移到 GPU 上
data_gpu = cp.asarray(in_data, dtype=cp.float32)
# 执行 1D FFT 变换
fft_result = cp.fft.fft(data_gpu)
# 计算实部和虚部大于阈值的数量
real_part = cp.abs(cp.real(fft_result))
imag_part = cp.abs(cp.imag(fft_result))
Tnum = cp.sum((real_part > T) & (imag_part > T))
return Tnum, data_gpu.size
def process_images(image_path):
filenames = [file for file in os.listdir(image_path) if "_disp.png" in file]
for i, filename in enumerate(filenames):
print(f"Processing file {i + 1}/{len(filenames)}: {filename}")
full_path = os.path.join(image_path, filename)
demo = Image.open(full_path)
im = cp.array(demo.convert('L')) # 将图像灰度化,并转换为 GPU 上的数组
# 展平图像数据
in_data = im.ravel()
Tnum, total_size = compute_fft_on_gpu(in_data)
# 输出结果
percentage = round(float(Tnum) / total_size, 4) * 100
print(f"Percentage of significant frequency components: {percentage}%")
if __name__ == "__main__":
# image_path是你存放图像文件的路径
image_path = '/path/to/your/image/directory'
process_images(image_path)
使用 cupy 进行 GPU 加速:
cupy.asarray 将数据从 CPU 内存转移到 GPU 内存。cp.fft.fft 来在 GPU 上执行快速傅里叶变换。图像处理:
PIL 库打开和灰度化图像,然后使用 cupy 将其转换为 GPU 上的数组。计算结果:
T 的频率成分的数量。请确保你的 CUDA 环境已正确配置,并且你的 GPU 支持 CUDA 才能成功运行此代码。如果你有任何问题,欢迎随时问我!
能不能不用cupy在GPU上计算
如果你想在不使用 cupy 的情况下在 GPU 上进行计算,可以考虑使用其他图形库或深度学习框架,它们通常会集成 GPU 加速功能。一个推荐的方法是使用 PyTorch 或 TensorFlow,因为它们都提供了流畅的 GPU 运算接口,并且可以处理张量计算,包括傅里叶变换。
下面是使用 PyTorch 进行 GPU 加速计算傅里叶变换的一个示例:
import torch
from PIL import Image
import numpy as np
import os
T = 50 # 阈值设定,大于T则判定偏离xy轴过多
def compute_fft_on_gpu(in_data):
# 将数据转换为 PyTorch 张量并移动到 GPU
data_tensor = torch.tensor(in_data, dtype=torch.float32, device='cuda')
# 执行 1D FFT 变换,返回实部和虚部
fft_result = torch.fft.fft(data_tensor)
# 计算实部和虚部大于阈值的数量
real_part = torch.abs(torch.real(fft_result))
imag_part = torch.abs(torch.imag(fft_result))
Tnum = torch.sum((real_part > T) & (imag_part > T))
return Tnum.item(), data_tensor.numel()
def process_images(image_path):
filenames = [file for file in os.listdir(image_path) if "_disp.png" in file]
for i, filename in enumerate(filenames):
print(f"Processing file {i + 1}/{len(filenames)}: {filename}")
full_path = os.path.join(image_path, filename)
demo = Image.open(full_path)
im = np.array(demo.convert('L')) # 将图像灰度化并转换为 NumPy 数组
# 展平图像数据
in_data = im.ravel()
Tnum, total_size = compute_fft_on_gpu(in_data)
# 输出结果
percentage = round(float(Tnum) / total_size, 4) * 100
print(f"Percentage of significant frequency components: {percentage}%")
if __name__ == "__main__":
# image_path 是你存放图像文件的路径
image_path = '/path/to/your/image/directory'
process_images(image_path)
使用 PyTorch 进行 GPU 加速:
torch.tensor 生成 GPU 上的张量,确保把张量数据转移到 cuda 设备。torch.fft.fft 在 GPU 上执行快速傅里叶变换。张量计算:
fft 模块支持复杂操作,可以直接计算 FFT,并处理实部和虚部。安装说明:
如有任何问题或需要进一步的帮助,请随时与我联系!
请使用pytorch 改进之前的代码,使得它能在GPU上跑
当然可以!让我们使用 PyTorch 来重写代码,使其能够在 GPU 上运行。我们将使用 PyTorch 的张量和 FFT 支持来实现这个功能。以下是优化后的代码:
import torch
from PIL import Image
import numpy as np
import os
# 阈值设定,大于T则判定偏离xy轴过多
T = 50
def compute_fft_on_gpu(in_data):
# 将数据转换为 PyTorch 张量并移动到 GPU
data_tensor = torch.tensor(in_data, dtype=torch.float32, device='cuda')
# 执行 1D FFT 变换
fft_result = torch.fft.fft(data_tensor)
# 计算实部和虚部大于阈值的数量
real_part = torch.abs(fft_result.real)
imag_part = torch.abs(fft_result.imag)
Tnum = torch.sum((real_part > T) & (imag_part > T))
return Tnum.item(), data_tensor.numel()
def process_images(image_path):
filenames = [file for file in os.listdir(image_path) if "_disp.png" in file]
for i, filename in enumerate(filenames):
print(f"Processing file {i + 1}/{len(filenames)}: {filename}")
full_path = os.path.join(image_path, filename)
demo = Image.open(full_path)
im = np.array(demo.convert('L')) # 将图像灰度化并转换为 NumPy 数组
# 展平图像数据
in_data = im.ravel()
Tnum, total_size = compute_fft_on_gpu(in_data)
# 输出结果
percentage = round(float(Tnum) / total_size, 4) * 100
print(f"Percentage of significant frequency components: {percentage}%")
if __name__ == "__main__":
# image_path 是你存放图像文件的路径
image_path = '/path/to/your/image/directory'
process_images(image_path)
设备设置:
device='cuda' 将数据移动到 GPU。如果你没有 GPU 或者 CUDA 未正确安装,可以将 'cuda' 改为 'cpu' 来在 CPU 上运行。张量计算:
PyTorch 的安装:
输入路径:
image_path 包含待处理的图像文件。这个代码将读取指定目录下的图像文件、转换为一维数据、执行 GPU 加速的 FFT,以及计算超过指定阈值的频率成分比例。祝你好运处理你的数据,如有问题请联系我!
在上述基础上再加一个功能,把percentage大于93的图像复制到目标文件夹
我们可以在原有代码的基础上添加一个功能:将计算得到的百分比大于 93% 的图像复制到一个目标文件夹。为了实现这一点,我们将使用 Python 的 shutil 模块来复制文件。以下是改进后的代码:
import torch
from PIL import Image
import numpy as np
import os
import shutil
# 阈值设定,大于T则判定偏离xy轴过多
T = 50
def compute_fft_on_gpu(in_data):
# 将数据转换为 PyTorch 张量并移动到 GPU
data_tensor = torch.tensor(in_data, dtype=torch.float32, device='cuda')
# 执行 1D FFT 变换
fft_result = torch.fft.fft(data_tensor)
# 计算实部和虚部大于阈值的数量
real_part = torch.abs(fft_result.real)
imag_part = torch.abs(fft_result.imag)
Tnum = torch.sum((real_part > T) & (imag_part > T))
return Tnum.item(), data_tensor.numel()
def process_images(image_path, target_path):
filenames = [file for file in os.listdir(image_path) if "_disp.png" in file]
# 确保目标文件夹存在
if not os.path.exists(target_path):
os.makedirs(target_path)
for i, filename in enumerate(filenames):
print(f"Processing file {i + 1}/{len(filenames)}: {filename}")
full_path = os.path.join(image_path, filename)
demo = Image.open(full_path)
im = np.array(demo.convert('L')) # 将图像灰度化并转换为 NumPy 数组
# 展平图像数据
in_data = im.ravel()
Tnum, total_size = compute_fft_on_gpu(in_data)
# 计算并输出结果
percentage = round(float(Tnum) / total_size, 4) * 100
print(f"Percentage of significant frequency components: {percentage}%")
# 如果百分比大于93%,将图像复制到目标文件夹
if percentage > 93:
shutil.copy(full_path, target_path)
print(f"Copied {filename} to {target_path}")
if __name__ == "__main__":
# 指定存放图像文件的路径和目标文件夹的路径
image_path = '/path/to/your/image/directory'
target_path = '/path/to/your/target/directory'
process_images(image_path, target_path)
文件夹操作:
os.makedirs(target_path) 确保目标文件夹存在,如果不存在则创建它。文件复制:
shutil.copy(full_path, target_path) 将符合条件的图像文件复制到目标文件夹。流程输出:
请确保更新你自己的 image_path 和 target_path 为实际的文件夹路径。这将有助于管理和分析符合特定条件的图像文件。如有需进一步帮助的地方,请随时告诉我!
Not yet included in a published release.
Execution: The main function reads image files from a directory, processes each file, and computes the FFT, printing the percentage of the signal that exceeds the threshold.
Performance: Using Python's built-in complex type and numpy.fft module can significantly simplify and speed up the implementation.
Code Clarity: Distinguishing between fft_1d() related functions and reusable utility functions will enhance readability.
Error Handling: Adding error handling for reading files, working with image data, and mathematical operations will make the script more robust.
Modular Structure: Splitting the code into separate functions for image loading, FFT processing, and result evaluation could improve maintainability and usability.
Would you like specific revisions or enhancements applied to this code snippet?