Convert between a PIL Image and a numpy array

Alternatively, to get a numpy array from an image use:

from PIL import Image
from numpy import array
img = Image.open("input.png")
arr = array(img)

And to get an image from a numpy array, use:

img = Image.fromarray(arr)
img.save("output.png")

 sample:

from PIL import Image
import numpy
im = Image.open("sample2.png")
np_im = numpy.array(im)
print np_im.shape
OUTPUT
(200, 400, 3)
np_im = np_im - 18
new_im = Image.fromarray(np_im)
new_im.save("numpy_altered_sample2.png")

im = Image.open("sample2.png") 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
报错 "numpy.AxisError: axis 1 is out of bounds for array of dimension 1" 是因为在代码的第 27 行使用了 `axis=(1,2)` 参数,但是 `features` 数组的维度不足以支持这个参数。 为了解决这个问题,可以使用以下代码将 `features` 变量的维度从 `(n, c, 1, 1)` 转换为 `(c, 1, 1)`: ```python # Reshape features to remove single-dimensional axes features = features.squeeze() if len(features.shape) == 3: features = features.unsqueeze(-1) if len(features.shape) == 2: features = features.unsqueeze(-1).unsqueeze(-1) ``` 这段代码会检查 `features` 数组的维度是否为 `(n, c, 1, 1)`,如果是,会先使用 `squeeze()` 方法删除所有大小为 1 的维度。如果删除后的维度为 `(c, 1, 1)`,则不需要进一步操作。否则,会使用 `unsqueeze()` 方法添加缺少的维度。 这样处理之后,就可以在第 27 行使用 `axis=(0,1)` 参数,而不会出现维度错误。 完整修改后的代码如下: ```python import torch import torch.nn as nn from torchvision import models, transforms from PIL import Image import numpy as np import matplotlib.pyplot as plt # Load pre-trained ResNet-18 model model = models.resnet18(pretrained=True) # Remove the fully connected layer from the model model = nn.Sequential(*list(model.children())[:-1]) # Set model to evaluation mode model.eval() # Define image transformation to match the pre-processing used during training transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # Load sample image img = Image.open('sample_image.jpg') # Apply transformation and convert to tensor img_tensor = transform(img).unsqueeze(0) # Pass image tensor through ResNet-18 to get feature maps with torch.no_grad(): features = model(img_tensor) # Reshape features to remove single-dimensional axes features = features.squeeze() if len(features.shape) == 3: features = features.unsqueeze(-1) if len(features.shape) == 2: features = features.unsqueeze(-1).unsqueeze(-1) # Calculate global average pooling of feature maps pooled_features = np.mean(features, axis=(1,2)) # Reshape pooled features to match spatial dimensions of feature maps pooled_features = np.repeat(pooled_features, features.shape[1]*features.shape[2]).reshape(features.shape) # Calculate importance of each feature map by comparing it to the global average heatmap = np.abs(features - pooled_features) # Normalize heatmap to range between 0 and 1 heatmap = (heatmap - np.min(heatmap)) / (np.max(heatmap) - np.min(heatmap)) # Plot heatmap on top of original image plt.imshow(img) plt.imshow(heatmap.sum(axis=0), alpha=0.5, cmap='jet') plt.axis('off') plt.show() ``` 希望能对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值