rom skimage.segmentation import slic, mark_boundaries import torchvision.transforms as transforms import numpy as np from PIL import Image import matplotlib.pyplot as plt # 加载图像 image = Image.open('3.jpg') # 转换为 PyTorch 张量 transform = transforms.ToTensor() img_tensor = transform(image).unsqueeze(0) # 将 PyTorch 张量转换为 Numpy 数组 img_np = img_tensor.numpy().transpose(0, 2, 3, 1)[0] # 使用 SLIC 算法生成超像素标记图 segments = slic(img_np, n_segments=60, compactness=10) # 可视化超像素索引映射 plt.imshow(segments, cmap='gray') plt.show() # 将超像素索引映射可视化 segment_img = mark_boundaries(img_np, segments) # 将 Numpy 数组转换为 PIL 图像 segment_img = Image.fromarray((segment_img * 255).astype(np.uint8)) # 保存超像素索引映射可视化 segment_img.save('segment_map.jpg') 将上述代码中引入超像素池化代码:import cv2 import numpy as np # 读取图像 img = cv2.imread('3.jpg') # 定义超像素分割器 num_segments = 60 # 超像素数目 slic = cv2.ximgproc.createSuperpixelSLIC(img, cv2.ximgproc.SLICO, num_segments) # 进行超像素分割 slic.iterate(10) # 获取超像素标签和数量 labels = slic.getLabels() num_label = slic.getNumberOfSuperpixels() # 对每个超像素进行池化操作,这里使用平均值池化 pooled = [] for i in range(num_label): mask = labels == i region = img[mask] pooled.append(region.mean(axis=0)) # 将池化后的特征图可视化 pooled = np.array(pooled, dtype=np.uint8) pooled_features = pooled.reshape(-1) pooled_img = cv2.resize(pooled_features, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_NEAREST) print(pooled_img.shape) cv2.imshow('Pooled Image', pooled_img) cv2.waitKey(0),并显示超像素池化后的特征图
时间: 2024-03-16 17:41:02 浏览: 16
以下是将超像素池化代码引入到原有代码中,并可视化超像素池化后的特征图的代码:
```python
rom skimage.segmentation import slic, mark_boundaries
import torchvision.transforms as transforms
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import cv2
# 加载图像
image = Image.open('3.jpg')
# 转换为 PyTorch 张量
transform = transforms.ToTensor()
img_tensor = transform(image).unsqueeze(0)
# 将 PyTorch 张量转换为 Numpy 数组
img_np = img_tensor.numpy().transpose(0, 2, 3, 1)[0]
# 使用 SLIC 算法生成超像素标记图
segments = slic(img_np, n_segments=60, compactness=10)
# 可视化超像素索引映射
plt.imshow(segments, cmap='gray')
plt.show()
# 将超像素索引映射可视化
segment_img = mark_boundaries(img_np, segments)
# 将 Numpy 数组转换为 PIL 图像
segment_img = Image.fromarray((segment_img * 255).astype(np.uint8))
# 保存超像素索引映射可视化
segment_img.save('segment_map.jpg')
# 进行超像素池化
num_segments = 60
slic = cv2.ximgproc.createSuperpixelSLIC(img_np, cv2.ximgproc.SLICO, num_segments)
slic.iterate(10)
labels = slic.getLabels()
num_label = slic.getNumberOfSuperpixels()
# 对每个超像素进行池化操作,这里使用平均值池化
pooled = []
for i in range(num_label):
mask = labels == i
region = img_np[mask]
pooled.append(region.mean(axis=0))
# 将池化后的特征图可视化
pooled = np.array(pooled, dtype=np.uint8)
pooled_features = pooled.reshape(-1)
pooled_img = cv2.resize(pooled_features, (img_np.shape[1], img_np.shape[0]), interpolation=cv2.INTER_NEAREST)
print(pooled_img.shape)
cv2.imshow('Pooled Image', pooled_img)
cv2.waitKey(0)
```
运行以上代码后,会将超像素索引映射可视化,并且显示超像素池化后的特征图,这里使用的是平均值池化。