【numpy】矩阵和图片的相互转化

13 篇文章 1 订阅
from PIL import Image
import numpy as np

x=np.load("universal.npy")  # x.shape=m*n*3
x=(x-np.min(x))*255/np.max(x)

im=Image.fromarray(np.uint8(x))

im.show()
im.save('flag.jpg')
from PIL import Image
import numpy as np

im = Image.open(r'test.jpeg')			# im是Image对象
img = np.array(im)						# img是h×w×3的ndarray (0-255,RGB)
img = np.asarray(im)					# img是h×w×3的ndarray (0-255,RGB)
'''
https://github.com/numpy/numpy/blob/bcbed877f42ed6e9b01b2125134db4b6395f1d9d/numpy/core/numeric.py#L413-481
asarray<=>array(copy=false)
https://stackoverflow.com/questions/14415741/numpy-array-vs-asarray
'''

np.save('test.npy',img)
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个基于PCA的方法来计算矩阵A和B的协同效应指数的完整Python代码示例: ```python import numpy as np from sklearn.decomposition import PCA # 读入矩阵A和矩阵B的数据 matrix_a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matrix_b = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) # 将矩阵A和矩阵B的各个指标元素标准化 matrix_a_normalized = (matrix_a - matrix_a.mean(axis=0)) / matrix_a.std(axis=0) matrix_b_normalized = (matrix_b - matrix_b.mean(axis=0)) / matrix_b.std(axis=0) # 应用PCA分解得到矩阵A和矩阵B的主因子和对应的权重 pca_a = PCA(n_components=1) pca_b = PCA(n_components=1) pca_a.fit(matrix_a_normalized) pca_b.fit(matrix_b_normalized) weights_a = pca_a.components_.reshape(-1) weights_b = pca_b.components_.reshape(-1) # 将矩阵A和矩阵B转化为相同维度的矩阵 if matrix_a.shape[0] < matrix_b.shape[0]: matrix_b = matrix_b[:matrix_a.shape[0], :] elif matrix_a.shape[0] > matrix_b.shape[0]: matrix_a = matrix_a[:matrix_b.shape[0], :] # 计算矩阵A和矩阵B的协同效应指数 dot_product = np.dot(matrix_a.dot(weights_a), matrix_b.dot(weights_b)) denominator = np.sum(weights_a) + np.sum(weights_b) - dot_product synergy_index = dot_product / denominator if denominator != 0 else 0 # 打印协同效应指数 print("Synergy Index: ", synergy_index) ``` 在这个示例中,我们首先将矩阵A和矩阵B的各个指标元素标准化,然后应用PCA分解得到矩阵A和矩阵B的主因子和对应的权重。接着,我们将矩阵A和矩阵B转化为相同维度的矩阵,并计算了矩阵A和矩阵B相互作用协同发展所带来的协同效应指数,并避免了分母为零的情况。需要注意的是,在这个示例中,我们使用了scikit-learn中的PCA模块,如果您没有安装scikit-learn,需要先安装一下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值