import cv2 import torch import matplotlib.pyplot as plt from skimage.segmentation import slic from matplotlib.patches import Rectangle # 定义超像素数目 n_segments = 25 # 加载输入图像 args = {"image": r"D:\Users\Administrator\PycharmProjects\pythonProject\heart_dataset\1_blur\img-00003-00007.jpg"} # load the image and apply SLIC and extract (approximately) # the supplied number of segments image = cv2.imread(args["image"]) # 使用SLIC算法进行超像素分割 segments = slic(image.transpose((1, 2, 0)), n_segments=n_segments) # 将超像素图像转换为掩膜 mask = torch.zeros_like(torch.from_numpy(image[0, :, :])) for i in range(n_segments): mask[segments == i] = i + 1 # 对掩膜进行处理,得到每个超像素块的区域 regions = [] for i in range(1, n_segments + 1): region = (mask == i).nonzero() if region.size(0) > 0: regions.append(region) # 绘制超像素块的区域 fig, ax = plt.subplots(1) ax.imshow(image.numpy().transpose((1, 2, 0))) for region in regions: x_min, y_min = region.min(dim=0)[0] x_max, y_max = region.max(dim=0)[0] rect = Rectangle((y_min, x_min), y_max - y_min, x_max - x_min, linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) plt.show(),上述代码出现问题: ax.imshow(image.numpy().transpose((1, 2, 0))) AttributeError: 'numpy.ndarray' object has no attribute 'numpy'
时间: 2024-03-08 08:46:55 浏览: 133
根据报错信息`AttributeError: 'numpy.ndarray' object has no attribute 'numpy'`,可以看出是因为在代码中使用了`image.numpy()`,而`numpy()`函数是tensor的方法,numpy数组没有该方法。
可以将以下代码:
```
ax.imshow(image.numpy().transpose((1, 2, 0)))
```
修改为:
```
ax.imshow(image.transpose((1, 2, 0)))
```
即可解决该问题。
阅读全文