np.compress()函数

本文详细介绍了numpy.compress()函数的使用方法及其参数含义。通过具体示例展示了如何利用该函数根据布尔数组选择数组元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

numpy.compress()调用方法:

numpy.compress(condition, a, axis=None, out=None)

各个参数意义:
condition:一维布尔值数组。
a:类数组对象,需要抽取返回值的数组对象。
axis:从哪个坐标轴取元素
out:输出数组,(不推荐设置,否则可能会报错),推荐使用返回值获取最终的数组
返回值:返回满足条件的元素。
代码如下:

import numpy as np


class Debug:
    @staticmethod
    def mainProgram():
        array = np.array([[1, 2],
                          [3, 4],
                          [5, 6]])

        array1 = np.compress([0, 1, 1], array, axis=0)
        print('array1的值为: ')
        print(array1)


if __name__ == "__main__":
    main = Debug()
    main.mainProgram()
"""
array1的值为: 
[[3 4]
 [5 6]]
"""

我们可以看到,axis=0表示沿着y轴选取元素或者数组切片,这时我们设置的布尔数组是[0, 1, 1],所以此时只返回第一行和第二行的元素,即沿着y轴的第一个和第二个数组切片。对于这里为什么axis=0代表沿着y轴,可以查看numpy数组的坐标轴问题(超链接点击跳转)。

再看一个例子:

import numpy as np


class Debug:
    @staticmethod
    def mainProgram():
        array = np.array([[1, 2],
                          [3, 4],
                          [5, 6]])

        array1 = np.compress([0, 1], array, axis=0)
        print('array1的值为: ')
        print(array1)


if __name__ == "__main__":
    main = Debug()
    main.mainProgram()
"""
array1的值为: 
[[3 4]]
"""

我们可以看到。沿着y轴选取数组切片,但是此时的布尔数组只有两个值,因此默认第三个值为False,截断了,所以只返回第二行的数组切片,其中包含两个元素。

码字不易,如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~

使用matlab编写一个脚本,读取一个文件夹中(可能包含若干子文件夹同样读取子文件夹)所有名称中同时包含"t1"‘t2’(包括大写)且包含"correct"的.mat文件。并使用下述方法进行反演(该方法采用python进行编写,需要转化为matlab),将反演得到的二维图像进行保存,保存格式为对应的.mat文件名称+反演结果.png。方法:def getT1T2Spectrum(_t_inv, _t_cpmg, _Z, T1, T2, alpha=2, cpmg_pts=100, fast=False): Z = np.zeros((_Z.shape[0], cpmg_pts)) #创建一个用于存储Z谱数据的零数组,大小为_Z数组的行数乘以cpmg_pts t = np.zeros((1, cpmg_pts)) #创建一个用于存储时间序列的零数组,大小为1 x cpmg_pts for i in range(_t_inv.shape[0]): t, Z[i], weights = compress(_t_cpmg, _Z[i], cpmg_pts) t = t.transpose() tau1 = _t_inv[:, np.newaxis] tau2 = t[:, np.newaxis] K1 = 1 - np.exp(-tau1 / T1) # SR # K1 = 1 - 2 * np.exp(-tau1 / T1) #IR K2 = np.exp(-tau2 / T2) S, res = flint(K1, K2, Z, alpha, fast=fast) return S def flint(K1, K2, Z, alpha, S=None, fast=False): maxiter = 100000 residuals = [] #用于存储每次迭代后的残差 if S is None: S = np.ones((K1.shape[1], K2.shape[1])) K1 = tsvd(K1) #11*100 K2 = tsvd(K2) #100*100 K1K1 = np.dot(K1.T, K1) K2K2 = np.dot(K2.T, K2) K1ZK2 = np.dot(np.dot(K1.T, Z), K2) # Lipschitz constant L = 2*(K1K1.trace()*K2K2.trace() + alpha) #Lipschitz 常数的一个估计,用于控制迭代步长 tZZ = np.dot(Z, Z.T).trace() # 计算残差的中间项 Y = S tt = 1 fac1 = (L - 2*alpha)/L fac2 = 2/L # 这2个fac的大小,对于是否收敛具有很大的影响,一般都要小于2/L lastres = np.inf # 用于内存占位符号,防止内存位数满了,因为残差的初始值特别大 for i in range(maxiter): term2 = K1ZK2 - np.dot(K1K1, np.dot(Y, K2K2)) Snew = np.clip(fac1*Y + fac2*term2, 0, None) ttnew = 0.5*(1 + np.sqrt(1 + 4*tt*tt)) trat = (tt - 1)/ttnew Y = Snew + trat*(Snew-S) #在每次迭代中,根据当前解 Y 和预先计算的常数 L,计算新的解 Snew。这里使用了 np.clip 函数将解限制在非负值范围内 tt = ttnew S = Snew if i%1000 == 0: # 每隔一定迭代次数计算一次残差 normS = alpha*np.linalg.norm(S)**2 residual = tZZ - 2*np.dot(S.T, K1ZK2).trace() + np.dot(S.T, np.dot(K1K1, np.dot(S, K2K2))).trace() + normS residuals.append(residual) #预处理后的数据矩阵和当前解 S 的内积项,以及正则化项 alpha 的贡献 res_diff_ratio = np.abs(residual - lastres)/residual #当前残差与上一次迭代的残差之间的相对变化率 lastres = residual # print(i, tt, trat, L, residual, res_diff_ratio) if res_diff_ratio < 1e-4 or (fast and res_diff_ratio < 1e-2): return S, np.array(residuals) raise Exception('Max iterations reached') def tsvd(A,truncation=0.1):########### u, s, v = np.linalg.svd(A, full_matrices=False) # compute SVD without 0 singular values S = np.diag(s) sr, sc = S.shape cnt = 0 for i in range(0, sc - 1): if S[i, i] > truncation: cnt+=1 return u[:,0:cnt].dot(S[0:cnt,0:cnt]).dot(v[0:cnt,:])
03-08
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d # 定义 BT2020 和普通显示器的三基色坐标 bt2020_primaries = np.array([[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]]) display_primaries = np.array([[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]]) # 定义转换损失函数 def color_loss_function(original_color, converted_color): return np.sqrt(np.sum((original_color - converted_color) ** 2)) # 颜色空间转换函数 def color_space_conversion(color, source_primaries, target_primaries): # 创建颜色变换矩阵 M = np.array([ [source_primaries[0][0], source_primaries[1][0], source_primaries[2][0]], [source_primaries[0][1], source_primaries[1][1], source_primaries[2][1]], [1.0, 1.0, 1.0] ]) M_inv = np.linalg.inv(M) # 将颜色坐标转换为 XYZ 空间 xyz = np.dot(M_inv, [color[0], color[1], 1.0]) # 创建目标颜色变换矩阵 M_target = np.array([ [target_primaries[0][0], target_primaries[1][0], target_primaries[2][0]], [target_primaries[0][1], target_primaries[1][1], target_primaries[2][1]], [1.0, 1.0, 1.0] ]) # 将 XYZ 转换为目标颜色空间的坐标 converted_color = np.dot(M_target, xyz) return converted_color[:2] # 返回 xy 坐标 # 模拟颜色转换和损失计算 original_color = np.array([0.3, 0.3]) # 示例原始颜色 converted_color = color_space_conversion(original_color, bt2020_primaries, display_primaries) loss = color_loss_function(original_color, converted_color) print(f"转换后的颜色: {converted_color}") print(f"颜色转换损失: {loss}") # 绘制 CIE1931 色彩空间(包括马蹄形曲线) # 使用更准确的 CIE1931 数据 def generate_cie1931_data(): # 使用现成的 CIE1931 马蹄形数据,这里使用一个近似的方法 # 实际应用中,应该使用标准的 CIE1931 数据文件 # 这里使用一个简化的公式来生成马蹄形曲线(仅用于演示) n = 1000 t = np.linspace(0, 2 * np.pi, n) x = np.zeros(n) y = np.zeros(n) # 马蹄形曲线的上半部分 for i in range(n // 2): angle = t[i] x[i] = 0.5 * (1 + np.cos(angle)) y[i] = 0.5 * (1 + np.sin(angle)) # 马蹄形曲线的下半部分(直线) for i in range(n // 2, n): x[i] = (i - n // 2) / (n // 2 - 1) * 0.75 + 0.05 y[i] = 0.0 return x, y # 使用更精确的 CIE1931 数据点生成马蹄形曲线 def generate_cie1931_standard_data(): # 使用标准的 CIE1931 xy 色度图数据(光谱轨迹和紫线) # 这里使用一个简化的数据集,实际应用中应使用完整的数据 wavelengths = np.linspace(380, 780, 400) x = np.array([0.0] * len(wavelengths)) y = np.array([0.0] * len(wavelengths)) # 这里应该填充实际的 CIE1931 数据 # 这个数据是示意性的,实际数据需要从标准或可靠资源获取 for i in range(len(wavelengths)): if wavelengths[i] < 440: x[i] = 0.38 + 0.18 * np.sin((wavelengths[i] - 440) / (400 - 440) * np.pi) y[i] = 0.38 - 0.22 * np.cos((wavelengths[i] - 440) / (400 - 440) * np.pi) elif wavelengths[i] < 500: x[i] = 0.22 + 0.16 * np.cos((wavelengths[i] - 440) / (500 - 440) * np.pi) y[i] = 0.38 - 0.16 * np.sin((wavelengths[i] - 440) / (500 - 440) * np.pi) elif wavelengths[i] < 560: x[i] = 0.22 - 0.16 * np.sin((wavelengths[i] - 500) / (560 - 500) * np.pi) y[i] = 0.22 + 0.16 * np.cos((wavelengths[i] - 500) / (560 - 500) * np.pi) elif wavelengths[i] < 620: x[i] = 0.38 - 0.18 * np.cos((wavelengths[i] - 560) / (620 - 560) * np.pi) y[i] = 0.22 + 0.18 * np.sin((wavelengths[i] - 560) / (620 - 560) * np.pi) else: x[i] = 0.38 + 0.18 * np.sin((wavelengths[i] - 620) / (780 - 620) * np.pi) y[i] = 0.38 - 0.22 * np.cos((wavelengths[i] - 620) / (780 - 620) * np.pi) return x, y x, y = generate_cie1931_standard_data() # 绘图 plt.figure(figsize=(10, 9)) plt.plot(bt2020_primaries[[0, 1, 2, 0], 0], bt2020_primaries[[0, 1, 2, 0], 1], 'orange', label='BT2020') plt.plot(display_primaries[[0, 1, 2, 0], 0], display_primaries[[0, 1, 2, 0], 1], 'red', label='普通显示器') plt.scatter(original_color[0], original_color[1], c='green', label='原始颜色') plt.scatter(converted_color[0], converted_color[1], c='yellow', label='转换后的颜色') # 绘制马蹄形曲线 plt.plot(x, y, 'black', label='CIE1931 马蹄形') # 设置坐标轴范围和网格 plt.xlim(-0.1, 0.8) plt.ylim(-0.1, 1.0) plt.grid(True) plt.legend() plt.xlabel('x') plt.ylabel('y') plt.title('CIE1931 色彩空间和颜色转换') plt.show()把马蹄形状改正确
最新发布
06-08
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勤奋的大熊猫

你的鼓励将是我写作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值