Introduce my name Fadli, I work as a bug bounty hunter, I found a vulnerability in an existing gitlab system which allows me to change the gitlab administrator/root password and also be able to view all source code and secret credentials. This finding is Critical, get shell to access server/linux operating system. please reply my email bfadliyanto@gmail.com

Commit e8b53c1b authored by 朱婉杰's avatar 朱婉杰

所有数据上传

parent 631b9800

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

import numpy as np
import matplotlib.pyplot as plt
import pywt
from scipy.fft import fft2, ifft2, fftshift, ifftshift
import os
def fft2c(img):
"""Centered 2D FFT."""
return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(img)))
def ifft2c(kspace):
"""Centered 2D IFFT."""
return np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(kspace)))
def soft_threshold(x, lam):
"""软阈值操作"""
return np.sign(x) * np.maximum(np.abs(x) - lam, 0)
def total_variation(x, alpha):
"""计算图像的总变分"""
dx = np.diff(x, axis=0)
dy = np.diff(x, axis=1)
return alpha * (np.sum(np.abs(dx)) + np.sum(np.abs(dy)))
def reconstruct_image(kspace_data):
im = fftshift(ifft2(kspace_data, (256, 256)), axes=0)
# 取模得到实值图像
magnitude_image = np.abs(im)
# 归一化图像
normalized_image = (magnitude_image - magnitude_image.min()) / (magnitude_image.max() - magnitude_image.min())
return normalized_image
def gpm_mri_reconstruction(kspace_sampled, mask, lam, num_iters=2000, step_size=0.05, tv_alpha=0.05):
"""
使用梯度投影法(Gradient Projection Method, GPM)进行MRI重建,并引入总变分约束
:param kspace_sampled: 采样的k空间数据
:param mask: 采样掩码
:param lam: 正则化参数
:param num_iters: 迭代次数
:param step_size: 步长
:param tv_alpha: 总变分约束强度
:return: 重建的图像
"""
# 初始重建(零填充)
img_reconstructed = reconstruct_image(kspace_sampled)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title('Initial Reconstructed MRI Image')
plt.show()
plt.imsave('initial_reconstructed_image.png', np.abs(img_reconstructed), cmap='gray')
for i in range(num_iters):
# 计算梯度:数据保真项的梯度
kspace_current = fft2c(img_reconstructed)
grad_data_fidelity = 2 * ifft2c((kspace_current - kspace_sampled) * mask)
# 计算梯度:稀疏项的梯度(使用小波变换)
coeffs = pywt.wavedec2(img_reconstructed, 'db4', level=3)
new_coeffs = []
for c in coeffs:
if isinstance(c, tuple):
c_soft = tuple([soft_threshold(x, lam) for x in c])
grad_sparse = [x - c_ for x, c_ in zip(c, c_soft)]
new_coeffs.append(grad_sparse)
else:
c_soft = soft_threshold(c, lam)
grad_sparse = c - c_soft
new_coeffs.append(grad_sparse)
grad_sparse_image = pywt.waverec2(new_coeffs, 'db4')
# 计算梯度:总变分项的梯度
grad_x, grad_y = np.gradient(img_reconstructed)
grad_tv = np.sqrt(grad_x ** 2 + grad_y ** 2)
grad_tv = tv_alpha * grad_tv
# 计算总的梯度
grad_total = grad_data_fidelity + grad_sparse_image + grad_tv
# 梯度下降步骤
img_temp = img_reconstructed - step_size * grad_total
# 投影步骤:保证满足k空间采样约束
kspace_temp = fft2c(img_temp)
kspace_reconstructed = kspace_sampled * mask + kspace_temp * (1 - mask)
img_reconstructed = reconstruct_image(kspace_reconstructed)
if (i + 1) % 10 == 0 or i == 0:
print(f"Iteration {i + 1}/{num_iters}")
return img_reconstructed
def main():
# 设置当前工作目录
current_dir = os.getcwd()
# 加载完整的k空间数据
kspace_path = os.path.join(current_dir, 'fid_20250418_163142.npy')
if not os.path.exists(kspace_path):
print(f"错误: 找不到文件 {kspace_path}")
return
try:
kspace_full = np.load(kspace_path)
print(f"成功加载k空间数据: {kspace_path}")
except Exception as e:
print(f"错误: 加载k空间数据时出错: {e}")
return
# 设置 GPM 参数
lam = 0.05 # 正则化参数,可以根据需要调整
num_iters = 10000 # 迭代次数
step_size = 0.05 # 步长,可以根据需要调整
tv_alpha = 0.1 # 总变分约束强度,可以根据需要调整
# 遍历当前目录下的所有.npy文件,排除'mrd_data.npy'
for filename in os.listdir(current_dir):
if filename.lower().endswith('.npy') and filename!= 'fid_20250418_163142.npy':
mask_path = os.path.join(current_dir, filename)
try:
mask = np.load(mask_path)
print(f"处理文件: {mask_path}")
except Exception as e:
print(f"错误: 加载文件 {mask_path} 时出错: {e}")
continue
# 检查kspace_full和mask的形状是否匹配
if kspace_full.shape!= mask.shape:
print(f"警告: 文件 {filename} 的形状与k空间数据不匹配,跳过。")
continue
# 采样k空间
kspace_sampled = kspace_full * mask
# 重建图像
try:
img_reconstructed = gpm_mri_reconstruction(kspace_sampled, mask, lam, num_iters, step_size, tv_alpha)
print(f"成功重建图像: {filename}")
except Exception as e:
print(f"错误: 重建文件 {filename} 时出错: {e}")
continue
# 构造保存的PNG文件名
base_name = os.path.splitext(filename)[0]
png_filename = f"{base_name}_gpm_reconstructed_fid_20250417_103329.png"
png_path = os.path.join(current_dir, png_filename)
plt.imshow(img_reconstructed, cmap='gray') # 设置为灰度图显示
plt.title('Reconstructed MRI Image')
plt.show()
plt.imsave(png_path, np.abs(img_reconstructed), cmap='gray')
if __name__ == "__main__":
main()
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import dct, idct
import os
import cv2
from scipy.fft import fft2, ifft2, fftshift, ifftshift
def fft2c(img):
"""Centered 2D FFT."""
return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(img)))
def ifft2c(kspace):
"""Centered 2D IFFT."""
return np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(kspace)))
def dct2(a):
"""二维离散余弦变换"""
return dct(dct(a.T, norm='ortho').T, norm='ortho')
def idct2(a):
"""二维离散余弦逆变换"""
return idct(idct(a.T, norm='ortho').T, norm='ortho')
def generate_sampling_mask(shape, sampling_rate):
"""生成随机采样掩码"""
num_samples = int(sampling_rate * shape[0] * shape[1])
mask = np.zeros(shape, dtype=np.float32)
indices = np.random.choice(shape[0] * shape[1], num_samples, replace=False)
mask.flat[indices] = 1
return mask
def soft_threshold(x, lam):
"""软阈值操作"""
return np.sign(x) * np.maximum(np.abs(x) - lam, 0)
def reconstruct_image(kspace_data):
im = fftshift(ifft2(kspace_data, (256, 256)), axes=0)
# 取模得到实值图像
magnitude_image = np.abs(im)
# 归一化图像
normalized_image = (magnitude_image - magnitude_image.min()) / (magnitude_image.max() - magnitude_image.min())
return normalized_image
def cg_mri_reconstruction(kspace_sampled, mask, num_iters=200):
# 对 kspace_sampled 进行去噪处理(这里使用中值滤波示例)
#kspace_sampled = np.abs(kspace_sampled) # 取模,因为中值滤波一般处理实值数据
#kspace_sampled = cv2.GaussianBlur(kspace_sampled.astype(np.float32), (3, 3), 0.1) # 减小标准差为 0.1
#kspace_sampled = kspace_sampled.astype(np.complex128) # 转换回复数类型
# 初始化重建图像
img_reconstructed = reconstruct_image(kspace_sampled)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title('Initial Reconstructed MRI Image')
plt.show()
plt.imsave('initial_reconstructed_image.png', np.abs(img_reconstructed), cmap='gray')
def A(x):
# 正向算子:从图像到采样 k 空间
kspace = fft2(x)
return kspace * mask
def At(y):
# 伴随算子:从采样 k 空间到图像
image = ifft2(y)
return image
# 初始残差
r = kspace_sampled - A(img_reconstructed)
p = At(r)
epsilon = 1e-10 # 一个很小的正数,用于避免除零错误
for i in range(num_iters):
Ap = A(p)
denominator_alpha = np.sum(np.conj(Ap) * Ap)
print(f"Iteration {i + 1}, denominator_alpha: {denominator_alpha}") # 添加打印语句
if np.abs(denominator_alpha) < epsilon:
denominator_alpha = epsilon
alpha = np.sum(np.conj(r) * r) / denominator_alpha
img_reconstructed = img_reconstructed + alpha * p
r_new = r - alpha * Ap
denominator_beta = np.sum(np.conj(r_new) * r_new) # 这里修正为使用新的残差计算分母
print(f"Iteration {i + 1}, denominator_beta: {denominator_beta}") # 添加打印语句
if np.abs(denominator_beta) < epsilon:
denominator_beta = epsilon
beta = np.sum(np.conj(r_new) * r_new) / denominator_beta
p = At(r_new) + beta * p
r = r_new
# 打印残差的范数,观察残差是否正常更新
print(f"Iteration {i + 1}, residual norm: {np.linalg.norm(r)}")
# 可视化中间结果
if (i + 1) % 100 == 0:
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title(f'Reconstructed MRI Image at Iteration {i + 1}')
plt.show()
final_img = np.abs(img_reconstructed)
return final_img
def admm_mri_reconstruction(kspace_sampled, mask, lam, rho=1.0, num_iters=100):
"""
使用交替方向乘子法进行 MRI 重建
:param kspace_sampled: 采样的 k 空间数据
:param mask: 采样掩码
:param lam: 正则化参数
:param rho: 惩罚参数
:param num_iters: 迭代次数
:return: 重建的图像
"""
img_reconstructed = reconstruct_image(kspace_sampled)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title('Initial Reconstructed MRI Image')
plt.show()
plt.imsave('initial_reconstructed_image.png', np.abs(img_reconstructed), cmap='gray')
# 初始重建(零填充)
#img_reconstructed = ifft2c(kspace_sampled)
z = dct2(img_reconstructed)
u = np.zeros_like(z)
for i in range(num_iters):
# 更新 x
kspace_x = kspace_sampled * mask + fft2c(ifft2c(idct2(z - u))) * (1 - mask)
img_reconstructed = ifft2c(kspace_x)
# 更新 z
sparse_coeff = dct2(img_reconstructed) + u
z = soft_threshold(sparse_coeff, lam / rho)
# 更新 u
u = u + (dct2(img_reconstructed) - z)
if (i + 1) % 10 == 0 or i == 0:
print(f"Iteration {i + 1}/{num_iters}")
return np.abs(img_reconstructed)
def ista_mri_reconstruction(kspace_sampled, mask, lam, num_iters=100, step_size=1.0):
"""
使用迭代软阈值算法ISTA进行MRI重建
:param kspace_sampled: 采样的k空间数据
:param mask: 采样掩码
:param lam: 正则化参数
:param num_iters: 迭代次数
:param step_size: 步长
:return: 重建的图像
"""
# 初始重建(零填充)
# img_reconstructed = ifft2c(kspace_sampled)
# img_reconstructed = np.abs(img_reconstructed)
img_reconstructed = reconstruct_image(kspace_sampled)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title('Initial Reconstructed MRI Image')
plt.show()
plt.imsave('initial_reconstructed_image.png', np.abs(img_reconstructed), cmap='gray')
for i in range(num_iters):
# 将当前图像转换到稀疏域
sparse_coeff = dct2(img_reconstructed)
# 软阈值操作
sparse_coeff = np.sign(sparse_coeff) * np.maximum(np.abs(sparse_coeff) - lam * step_size, 0)
# 将稀疏系数转换回图像域
img_temp = idct2(sparse_coeff)
# 数据一致性步骤
kspace_reconstructed = fft2c(img_temp)
kspace_reconstructed = kspace_sampled * mask + kspace_reconstructed * (1 - mask)
#img_reconstructed = np.abs(ifft2c(kspace_reconstructed))
img_reconstructed = reconstruct_image(kspace_reconstructed)
if (i + 1) % 10 == 0 or i == 0:
print(f"Iteration {i + 1}/{num_iters}")
return img_reconstructed
def main():
# 设置当前工作目录
current_dir = os.getcwd()
# 加载完整的k空间数据
kspace_path = os.path.join(current_dir, 'fid_20250418_163142.npy')
if not os.path.exists(kspace_path):
print(f"错误: 找不到文件 {kspace_path}")
return
try:
kspace_full = np.load(kspace_path)
print(f"成功加载k空间数据: {kspace_path}")
except Exception as e:
print(f"错误: 加载k空间数据时出错: {e}")
return
# 设置 ISTA 参数
lam = 0.1 # 正则化参数,可以根据需要调整
num_iters = 1000 # 迭代次数
step_size = 0.1 # 步长,可以根据需要调整
# 设置采样率
sampling_rate = 0.33 # 可以根据需要调整
# 生成采样掩码
mask1 = generate_sampling_mask(kspace_full.shape, sampling_rate)
# 采样k空间
# 共轭梯度法重建图像
# 遍历当前目录下的所有 .npy 文件,排除 'mrd_data.npy'
for filename in os.listdir(current_dir):
if filename.lower().endswith('.npy') and filename != 'fid_20250418_163142.npy':
mask_path = os.path.join(current_dir, filename)
try:
mask = np.load(mask_path)
print(f"处理文件: {mask_path}")
except Exception as e:
print(f"错误: 加载文件 {mask_path} 时出错: {e}")
continue
# 检查 kspace_full 和 mask 的形状是否匹配
if kspace_full.shape != mask.shape:
print(f"警告: 文件 {filename} 的形状与 k 空间数据不匹配,跳过。")
continue
kspace_sampled_test = kspace_full * mask1
img_reconstructed_test = reconstruct_image(kspace_sampled_test)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed_test), cmap='gray')
plt.title('test Reconstructed MRI Image')
plt.show()
plt.imsave('test_reconstructed_image.png', np.abs(img_reconstructed_test), cmap='gray')
# 采样 k 空间
kspace_sampled = kspace_full * mask
# 重建图像
try:
#img_reconstructed = admm_mri_reconstruction(kspace_sampled, mask, lam, rho=1.0, num_iters=200)
img_reconstructed =ista_mri_reconstruction(kspace_sampled, mask, lam, num_iters, step_size)
print(f"成功重建图像: {filename}")
except Exception as e:
print(f"错误: 重建文件 {filename} 时出错: {e}")
continue
# 构造保存的 PNG 文件名
base_name = os.path.splitext(filename)[0]
#png_filename = f"{base_name}_ista_reconstructed_fid_20250417_103329.png"
png_filename = f"{base_name}_ista_reconstructed_fid_20250417_103329.png"
png_path = os.path.join(current_dir, png_filename)
plt.imshow(img_reconstructed, cmap='gray') # 设置为灰度图显示
plt.title('Reconstructed MRI Image')
#plt.axis('off') # 取消坐标轴
# plt.tight_layout(pad=0)
plt.show()
#plt.savefig(png_path, dpi=300) # 保存为 PNG 文件
plt.imsave(png_path, np.abs(img_reconstructed), cmap='gray')
if __name__ == "__main__":
main()
import numpy as np
import matplotlib.pyplot as plt
import pywt
from scipy.fft import fft2, ifft2, fftshift, ifftshift
import os
def fft2c(img):
"""Centered 2D FFT."""
return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(img)))
def ifft2c(kspace):
"""Centered 2D IFFT."""
return np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(kspace)))
def soft_threshold(x, lam):
"""软阈值操作"""
return np.sign(x) * np.maximum(np.abs(x) - lam, 0)
def total_variation(x, alpha):
"""计算图像的总变分"""
dx = np.diff(x, axis=0)
dy = np.diff(x, axis=1)
return alpha * (np.sum(np.abs(dx)) + np.sum(np.abs(dy)))
def reconstruct_image(kspace_data):
im = fftshift(ifft2(kspace_data, (256, 256)), axes=0)
# 取模得到实值图像
magnitude_image = np.abs(im)
# 归一化图像
normalized_image = (magnitude_image - magnitude_image.min()) / (magnitude_image.max() - magnitude_image.min())
return normalized_image
def fista_mri_reconstruction(kspace_sampled, mask, lam, num_iters=2000, step_size=0.05, tv_alpha=0.05, wavelet='db4'):
"""
使用快速迭代软阈值算法FISTA进行MRI重建,并引入总变分约束
:param kspace_sampled: 采样的k空间数据
:param mask: 采样掩码
:param lam: 正则化参数
:param num_iters: 迭代次数
:param step_size: 步长
:param tv_alpha: 总变分约束强度
:param wavelet: 小波基名称,默认为'db4'
:return: 重建的图像
"""
# 初始重建(零填充)
img_reconstructed = reconstruct_image(kspace_sampled)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title('Initial Reconstructed MRI Image')
plt.show()
plt.imsave('initial_reconstructed_image.png', np.abs(img_reconstructed), cmap='gray')
y = img_reconstructed.copy()
t = 1
for i in range(num_iters):
# 将当前图像转换到稀疏域(使用离散小波变换 DWT)
coeffs = pywt.wavedec2(y, wavelet, level=3)
new_coeffs = []
for c in coeffs:
if isinstance(c, tuple):
c = tuple([soft_threshold(x, lam * step_size) for x in c])
else:
c = soft_threshold(c, lam * step_size)
new_coeffs.append(c)
# 将稀疏系数转换回图像域
img_temp = pywt.waverec2(new_coeffs, wavelet)
# 引入总变分约束
grad_tv = np.gradient(img_temp)
grad_tv = np.sqrt(grad_tv[0]**2 + grad_tv[1]**2)
img_temp = img_temp - step_size * tv_alpha * grad_tv
# 数据一致性步骤
kspace_reconstructed = fft2c(img_temp)
kspace_reconstructed = kspace_sampled * mask + kspace_reconstructed * (1 - mask)
img_new = reconstruct_image(kspace_reconstructed)
t_new = (1 + np.sqrt(1 + 4 * t ** 2)) / 2
y = img_new + ((t - 1) / t_new) * (img_new - img_reconstructed)
img_reconstructed = img_new
t = t_new
if (i + 1) % 10 == 0 or i == 0:
print(f"Iteration {i + 1}/{num_iters}")
return img_reconstructed
def main():
# 设置当前工作目录
current_dir = os.getcwd()
# 加载完整的k空间数据
kspace_path = os.path.join(current_dir, 'fid_20250418_163142.npy')
if not os.path.exists(kspace_path):
print(f"错误: 找不到文件 {kspace_path}")
return
try:
kspace_full = np.load(kspace_path)
print(f"成功加载k空间数据: {kspace_path}")
except Exception as e:
print(f"错误: 加载k空间数据时出错: {e}")
return
# 设置 FISTA 参数
lam = 0.05 # 正则化参数,可以根据需要调整
num_iters = 10000 # 迭代次数
step_size = 0.05 # 步长,可以根据需要调整
tv_alpha = 0.1 # 总变分约束强度,可以根据需要调整
# 定义要尝试的小波基列表
#wavelets = ['haar','sym4']
wavelets = ['haar']
# 遍历当前目录下的所有.npy文件,排除'mrd_data.npy'
for filename in os.listdir(current_dir):
if filename.lower().endswith('.npy') and filename!= 'fid_20250418_163142.npy':
mask_path = os.path.join(current_dir, filename)
try:
mask = np.load(mask_path)
print(f"处理文件: {mask_path}")
except Exception as e:
print(f"错误: 加载文件 {mask_path} 时出错: {e}")
continue
# 检查kspace_full和mask的形状是否匹配
if kspace_full.shape!= mask.shape:
print(f"警告: 文件 {filename} 的形状与k空间数据不匹配,跳过。")
continue
# 采样k空间
kspace_sampled = kspace_full * mask
for wavelet in wavelets:
# 重建图像
try:
img_reconstructed = fista_mri_reconstruction(kspace_sampled, mask, lam, num_iters, step_size, tv_alpha)
print(f"使用{wavelet}小波基成功重建图像: {filename}")
except Exception as e:
print(f"错误: 使用{wavelet}小波基重建文件 {filename} 时出错: {e}")
continue
# 构造保存的PNG文件名,包含小波基名称
base_name = os.path.splitext(filename)[0]
png_filename = f"{base_name}_{wavelet}_fista_reconstructed_fid_20250417_103329.png"
png_path = os.path.join(current_dir, png_filename)
plt.imshow(img_reconstructed, cmap='gray') # 设置为灰度图显示
plt.title(f'Reconstructed MRI Image with {wavelet} wavelet')
plt.show()
plt.imsave(png_path, np.abs(img_reconstructed), cmap='gray')
if __name__ == "__main__":
main()
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import dct, idct
import os
def fft2c(img):
"""Centered 2D FFT."""
return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(img)))
def ifft2c(kspace):
"""Centered 2D IFFT."""
return np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(kspace)))
def generate_sampling_mask(shape, sampling_rate):
"""生成随机采样掩码"""
num_samples = int(sampling_rate * shape[0] * shape[1])
mask = np.zeros(shape, dtype=np.float32)
indices = np.random.choice(shape[0] * shape[1], num_samples, replace=False)
mask.flat[indices] = 1
return mask
def dct2(a):
"""二维离散余弦变换"""
return dct(dct(a.T, norm='ortho').T, norm='ortho')
def idct2(a):
"""二维离散余弦逆变换"""
return idct(idct(a.T, norm='ortho').T, norm='ortho')
def soft_threshold(x, lam):
"""软阈值操作"""
return np.sign(x) * np.maximum(np.abs(x) - lam, 0)
def admm_mri_reconstruction(kspace_sampled, mask, lam, rho=1.0, num_iters=100):
"""
使用交替方向乘子法进行 MRI 重建
:param kspace_sampled: 采样的 k 空间数据
:param mask: 采样掩码
:param lam: 正则化参数
:param rho: 惩罚参数
:param num_iters: 迭代次数
:return: 重建的图像
"""
# 初始重建(零填充)
img_reconstructed = ifft2c(kspace_sampled)
z = dct2(img_reconstructed)
u = np.zeros_like(z)
for i in range(num_iters):
# 更新 x
kspace_x = kspace_sampled * mask + fft2c(ifft2c(idct2(z - u))) * (1 - mask)
img_reconstructed = ifft2c(kspace_x)
# 更新 z
sparse_coeff = dct2(img_reconstructed) + u
z = soft_threshold(sparse_coeff, lam / rho)
# 更新 u
u = u + (dct2(img_reconstructed) - z)
if (i + 1) % 10 == 0 or i == 0:
print(f"Iteration {i + 1}/{num_iters}")
return np.abs(img_reconstructed)
def main():
# 设置当前工作目录
current_dir = os.getcwd()
# 加载完整的 k 空间数据
kspace_path = os.path.join(current_dir, 'mrd_data1.npy')
if not os.path.exists(kspace_path):
print(f"错误: 找不到文件 {kspace_path}")
return
try:
kspace_full = np.load(kspace_path)
print(f"成功加载 k 空间数据: {kspace_path}")
except Exception as e:
print(f"错误: 加载 k 空间数据时出错: {e}")
return
# 设置 ADMM 参数
lam = 0.1 # 正则化参数,可以根据需要调整
rho = 1.0 # 惩罚参数
num_iters = 100 # 迭代次数
# 遍历当前目录下的所有 .npy 文件,排除 'mrd_data.npy'
for filename in os.listdir(current_dir):
if filename.lower().endswith('.npy') and filename != 'mrd_data.npy':
mask_path = os.path.join(current_dir, filename)
try:
mask = np.load(mask_path)
print(f"处理文件: {mask_path}")
except Exception as e:
print(f"错误: 加载文件 {mask_path} 时出错: {e}")
continue
# 检查 kspace_full 和 mask 的形状是否匹配
if kspace_full.shape != mask.shape:
print(f"警告: 文件 {filename} 的形状与 k 空间数据不匹配,跳过。")
continue
# 采样 k 空间
kspace_sampled = kspace_full * mask
# 重建图像
try:
img_reconstructed = admm_mri_reconstruction(kspace_sampled, mask, lam, rho, num_iters)
print(f"成功重建图像: {filename}")
except Exception as e:
print(f"错误: 使用 ADMM 重建文件 {filename} 时出错: {e}")
continue
# 构造保存的 PNG 文件名
base_name = os.path.splitext(filename)[0]
png_filename = f"{base_name}_ADMM_reconstructed.png"
png_path = os.path.join(current_dir, png_filename)
plt.imshow(img_reconstructed)
plt.axis('off') # 取消坐标轴
plt.tight_layout(pad=0)
plt.savefig(png_path, dpi=300) # 保存为 PNG 文件
if __name__ == "__main__":
main()
\ No newline at end of file
import numpy as np
import matplotlib.pyplot as plt
import pywt
from scipy.fft import fft2, ifft2, fftshift, ifftshift
import os
def fft2c(img):
"""Centered 2D FFT."""
return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(img)))
def ifft2c(kspace):
"""Centered 2D IFFT."""
return np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(kspace)))
def soft_threshold(x, lam):
"""软阈值操作"""
return np.sign(x) * np.maximum(np.abs(x) - lam, 0)
def total_variation(x, alpha):
"""计算图像的总变分"""
dx = np.diff(x, axis=0)
dy = np.diff(x, axis=1)
return alpha * (np.sum(np.abs(dx)) + np.sum(np.abs(dy)))
def reconstruct_image(kspace_data):
im = fftshift(ifft2(kspace_data, (256, 256)), axes=0)
# 取模得到实值图像
magnitude_image = np.abs(im)
# 归一化图像
normalized_image = (magnitude_image - magnitude_image.min()) / (magnitude_image.max() - magnitude_image.min())
return normalized_image
def split_bregman_mri_reconstruction(kspace_sampled, mask, lam, num_iters=2000, step_size=0.05, tv_alpha=0.05):
"""
使用分裂布雷格曼算法(Split Bregman)进行MRI重建,并引入总变分约束
:param kspace_sampled: 采样的k空间数据
:param mask: 采样掩码
:param lam: 正则化参数
:param num_iters: 迭代次数
:param step_size: 步长
:param tv_alpha: 总变分约束强度
:return: 重建的图像
"""
# 初始重建(零填充)
img_reconstructed = reconstruct_image(kspace_sampled)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title('Initial Reconstructed MRI Image')
plt.show()
plt.imsave('initial_reconstructed_image.png', np.abs(img_reconstructed), cmap='gray')
# 初始化布雷格曼变量
b1 = np.zeros_like(img_reconstructed)
b2 = np.zeros_like(img_reconstructed)
for i in range(num_iters):
# 数据一致性步骤
kspace_reconstructed = fft2c(img_reconstructed)
kspace_reconstructed = kspace_sampled * mask + kspace_reconstructed * (1 - mask)
img_temp = reconstruct_image(kspace_reconstructed)
# 计算总变分
grad_tv = np.gradient(img_temp)
grad_tv = np.sqrt(grad_tv[0] ** 2 + grad_tv[1] ** 2)
# 更新图像
img_reconstructed = img_temp - step_size * (tv_alpha * grad_tv + b1 + b2)
# 更新布雷格曼变量
b1 = b1 + step_size * (grad_tv - soft_threshold(img_reconstructed + b1, lam))
b2 = b2 + step_size * (grad_tv - soft_threshold(img_reconstructed + b2, lam))
if (i + 1) % 10 == 0 or i == 0:
print(f"Iteration {i + 1}/{num_iters}")
return img_reconstructed
def main():
# 设置当前工作目录
current_dir = os.getcwd()
# 加载完整的k空间数据
kspace_path = os.path.join(current_dir, 'fid_20250418_163142.npy')
if not os.path.exists(kspace_path):
print(f"错误: 找不到文件 {kspace_path}")
return
try:
kspace_full = np.load(kspace_path)
print(f"成功加载k空间数据: {kspace_path}")
except Exception as e:
print(f"错误: 加载k空间数据时出错: {e}")
return
# 设置分裂布雷格曼算法参数
lam = 0.05 # 正则化参数,可以根据需要调整
num_iters = 10000 # 迭代次数
step_size = 0.05 # 步长,可以根据需要调整
tv_alpha = 0.1 # 总变分约束强度,可以根据需要调整
# 遍历当前目录下的所有.npy文件,排除'mrd_data.npy'
for filename in os.listdir(current_dir):
if filename.lower().endswith('.npy') and filename!= 'fid_20250418_163142.npy':
mask_path = os.path.join(current_dir, filename)
try:
mask = np.load(mask_path)
print(f"处理文件: {mask_path}")
except Exception as e:
print(f"错误: 加载文件 {mask_path} 时出错: {e}")
continue
# 检查kspace_full和mask的形状是否匹配
if kspace_full.shape!= mask.shape:
print(f"警告: 文件 {filename} 的形状与k空间数据不匹配,跳过。")
continue
# 采样k空间
kspace_sampled = kspace_full * mask
# 重建图像
try:
img_reconstructed = split_bregman_mri_reconstruction(kspace_sampled, mask, lam, num_iters, step_size, tv_alpha)
print(f"成功重建图像: {filename}")
except Exception as e:
print(f"错误: 重建文件 {filename} 时出错: {e}")
continue
# 构造保存的PNG文件名
base_name = os.path.splitext(filename)[0]
png_filename = f"{base_name}_split_bregman_reconstructed_fid_20250417_103329.png"
png_path = os.path.join(current_dir, png_filename)
plt.imshow(img_reconstructed, cmap='gray') # 设置为灰度图显示
plt.title('Reconstructed MRI Image')
plt.show()
plt.imsave(png_path, np.abs(img_reconstructed), cmap='gray')
if __name__ == "__main__":
main()
import numpy as np
import matplotlib.pyplot as plt
import pywt
from scipy.fft import fft2, ifft2, fftshift, ifftshift
import os
def fft2c(img):
"""Centered 2D FFT."""
return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(img)))
def ifft2c(kspace):
"""Centered 2D IFFT."""
return np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(kspace)))
def soft_threshold(x, lam):
"""软阈值操作"""
return np.sign(x) * np.maximum(np.abs(x) - lam, 0)
def total_variation(x, alpha):
"""计算图像的总变分"""
dx = np.diff(x, axis=0)
dy = np.diff(x, axis=1)
return alpha * (np.sum(np.abs(dx)) + np.sum(np.abs(dy)))
def reconstruct_image(kspace_data):
im = fftshift(ifft2(kspace_data, (256, 256)), axes=0)
# 取模得到实值图像
magnitude_image = np.abs(im)
# 归一化图像
normalized_image = (magnitude_image - magnitude_image.min()) / (magnitude_image.max() - magnitude_image.min())
return normalized_image
def ista_mri_reconstruction(kspace_sampled, mask, lam, num_iters=2000, step_size=0.05, tv_alpha=0.05):
"""
使用迭代收缩阈值算法(ISTA)进行MRI重建,并引入总变分约束
:param kspace_sampled: 采样的k空间数据
:param mask: 采样掩码
:param lam: 正则化参数
:param num_iters: 迭代次数
:param step_size: 步长
:param tv_alpha: 总变分约束强度
:return: 重建的图像
"""
# 初始重建(零填充)
img_reconstructed = reconstruct_image(kspace_sampled)
# 显示初始化图像
plt.imshow(np.abs(img_reconstructed), cmap='gray')
plt.title('Initial Reconstructed MRI Image')
plt.show()
plt.imsave('initial_reconstructed_image.png', np.abs(img_reconstructed), cmap='gray')
for i in range(num_iters):
# 数据一致性步骤
kspace_reconstructed = fft2c(img_reconstructed)
kspace_reconstructed = kspace_sampled * mask + kspace_reconstructed * (1 - mask)
img_temp = reconstruct_image(kspace_reconstructed)
# 将当前图像转换到稀疏域(使用离散小波变换 DWT)
coeffs = pywt.wavedec2(img_temp, 'db4', level=3)
new_coeffs = []
for c in coeffs:
if isinstance(c, tuple):
c = tuple([soft_threshold(x, lam * step_size) for x in c])
else:
c = soft_threshold(c, lam * step_size)
new_coeffs.append(c)
# 将稀疏系数转换回图像域
img_reconstructed = pywt.waverec2(new_coeffs, 'db4')
# 引入总变分约束
grad_tv = np.gradient(img_reconstructed)
grad_tv = np.sqrt(grad_tv[0] ** 2 + grad_tv[1] ** 2)
img_reconstructed = img_reconstructed - step_size * tv_alpha * grad_tv
if (i + 1) % 10 == 0 or i == 0:
print(f"Iteration {i + 1}/{num_iters}")
return img_reconstructed
def main():
# 设置当前工作目录
current_dir = os.getcwd()
# 加载完整的k空间数据
kspace_path = os.path.join(current_dir, 'fid_20250418_163142.npy')
if not os.path.exists(kspace_path):
print(f"错误: 找不到文件 {kspace_path}")
return
try:
kspace_full = np.load(kspace_path)
print(f"成功加载k空间数据: {kspace_path}")
except Exception as e:
print(f"错误: 加载k空间数据时出错: {e}")
return
# 设置 ISTA 参数
lam = 0.05 # 正则化参数,可以根据需要调整
num_iters = 10000 # 迭代次数
step_size = 0.05 # 步长,可以根据需要调整
tv_alpha = 0.1 # 总变分约束强度,可以根据需要调整
# 遍历当前目录下的所有.npy文件,排除'mrd_data.npy'
for filename in os.listdir(current_dir):
if filename.lower().endswith('.npy') and filename!= 'fid_20250418_163142.npy':
mask_path = os.path.join(current_dir, filename)
try:
mask = np.load(mask_path)
print(f"处理文件: {mask_path}")
except Exception as e:
print(f"错误: 加载文件 {mask_path} 时出错: {e}")
continue
# 检查kspace_full和mask的形状是否匹配
if kspace_full.shape!= mask.shape:
print(f"警告: 文件 {filename} 的形状与k空间数据不匹配,跳过。")
continue
# 采样k空间
kspace_sampled = kspace_full * mask
# 重建图像
try:
img_reconstructed = ista_mri_reconstruction(kspace_sampled, mask, lam, num_iters, step_size, tv_alpha)
print(f"成功重建图像: {filename}")
except Exception as e:
print(f"错误: 重建文件 {filename} 时出错: {e}")
continue
# 构造保存的PNG文件名
base_name = os.path.splitext(filename)[0]
png_filename = f"{base_name}_ista_reconstructed_fid_20250417_103329.png"
png_path = os.path.join(current_dir, png_filename)
plt.imshow(img_reconstructed, cmap='gray') # 设置为灰度图显示
plt.title('Reconstructed MRI Image')
plt.show()
plt.imsave(png_path, np.abs(img_reconstructed), cmap='gray')
if __name__ == "__main__":
main()
'''
Author: zhuwanjie 2268677665@qq.com
Date: 2025-04-21 11:34:18
LastEditors: zhuwanjie 2268677665@qq.com
LastEditTime: 2025-04-30 09:56:59
FilePath: \unet-pytorch\demo.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
from scipy.fft import fft2, ifft2, fftshift, ifftshift
# 从 K 空间数据重建图像
def reconstruct_image(kspace_data):
print("kspace_data shape:", kspace_data.shape)
im = fftshift(ifft2(kspace_data, (256, 256)), axes=0) #
# 取模得到实值图像
magnitude_image = np.abs(im)
# 归一化图像
normalized_image = (magnitude_image - magnitude_image.min()) / (magnitude_image.max() - magnitude_image.min())
# 转换为 8 位无符号整数
uint8_image = (normalized_image * 255).astype(np.uint8)
# 转换为 RGB 图像
rgb_image = cv2.cvtColor(uint8_image, cv2.COLOR_GRAY2RGB)
return rgb_image
def saveImg(path, img):
fig = plt.figure(figsize=(img.shape[1] / 100, img.shape[0] / 100), dpi=130)
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.savefig(path, bbox_inches='tight', pad_inches=0, transparent=True)
plt.close(fig)
def process_kspace_folder(kspace_folder_path, output_folder_path):
if not os.path.exists(output_folder_path):
os.makedirs(output_folder_path)
file_names = [f for f in os.listdir(kspace_folder_path) if f.endswith('.npy')]
for file_name in file_names:
kspace_file_path = os.path.join(kspace_folder_path, file_name)
kspace_data = np.load(kspace_file_path)
# 重建图像
reconstructed_image = reconstruct_image(kspace_data)
# 保存重建后的图像
output_file_name = os.path.splitext(file_name)[0] + '_reconstructed.png'
output_file_path = os.path.join(output_folder_path, output_file_name)
saveImg(output_file_path, reconstructed_image)
if __name__ == "__main__":
kspace_folder_path = r'D:\Users\Desktop\fid' # 请替换为实际的k空间数据文件夹路径
output_folder_path = r'D:\Users\Desktop\img' # 请替换为实际的输出文件夹路径
process_kspace_folder(kspace_folder_path, output_folder_path)
import cv2
import os
import re
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)]
def images_to_video(image_folder, video_name, fps=24, target_width=640, target_height=480):
# 支持更多图片格式
supported_extensions = ('.png', '.jpg', '.jpeg', '.bmp')
images = [img for img in os.listdir(image_folder) if img.endswith(supported_extensions)]
images.sort(key=natural_sort_key)
if not images:
print("未找到图片文件。")
return
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(video_name, fourcc, fps, (target_width, target_height))
for image in images:
img_path = os.path.join(image_folder, image)
try:
frame = cv2.imread(img_path)
if frame is None:
print(f"无法读取图片: {img_path}")
continue
# 调整图片尺寸
resized_frame = cv2.resize(frame, (target_width, target_height))
video.write(resized_frame)
except Exception as e:
print(f"处理图片 {img_path} 时出错: {e}")
video.release()
print(f"视频 {video_name} 已生成。")
if __name__ == "__main__":
image_folder = r'D:\Users\Desktop\item\unet-pytorch\img' # 替换为实际的图片文件夹路径
video_name = 'output_video.mp4'
fps = 1
# 设置目标尺寸
target_width = 640
target_height = 640
images_to_video(image_folder, video_name, fps, target_width, target_height)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment