t1 = time.time() # Note that compactness is defined differently because a grid is not used. Lower compactness for maskSLIC is equivalent segments = seg.slic(img, compactness=10, seed_type='nplace', mask=roi, n_segments=120, recompute_seeds=True, plot_examples=True, enforce_connectivity=True) print("Time: {:.2f} s".format(time.time() - t1)) plt.figure() plt.imshow(mark_boundaries(img, segments)) plt.contour(roi, contours=1, colors='red', linewidths=0.5) plt.axis('off') plt.savefig(r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result3\maskslic.png') 怎么保存每一块超像素图像 完整代码

时间: 2024-03-17 21:43:52 浏览: 17
完整代码如下: ``` import cv2 import numpy as np import matplotlib.pyplot as plt from skimage.segmentation import mark_boundaries import time # Load image img = cv2.imread('image.jpg') # Create binary mask h, w = img.shape[:2] roi = np.zeros((h, w), dtype=np.uint8) cv2.rectangle(roi, (100, 100), (w-100, h-100), 255, -1) # Apply maskSLIC t1 = time.time() segments = seg.slic(img, compactness=10, seed_type='nplace', mask=roi, n_segments=120, recompute_seeds=True, plot_examples=True, enforce_connectivity=True) print("Time: {:.2f} s".format(time.time() - t1)) # Save each segment as an individual file for segment_id in np.unique(segments): mask = segments == segment_id masked_image = img.copy() masked_image[~mask] = 0 cv2.imwrite('segment_{}.png'.format(segment_id), masked_image) # Show result plt.figure() plt.imshow(mark_boundaries(img, segments)) plt.contour(roi, contours=1, colors='red', linewidths=0.5) plt.axis('off') plt.savefig(r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result3\maskslic.png') ``` 请注意,此代码使用了一些未定义的变量,例如 `seg`。在使用此代码之前,请确保已经正确导入和定义了这些变量。

相关推荐

img = imread(r'I:\\18Breakageratecalculation\\mask-slic use\\maskSLIC-master\\1\\056.jpg') # The ROI is also stored as an image for viewing convenience # But the roi input input maskSLIC should be a binary image with the same spatial # Dimensions as the image (in this case 300x451) roi = imread(r'I:\\18Breakageratecalculation\\mask-slic use\\maskSLIC-master\\1\\0562.png') # The alpha channel is used to store the ROI in this case and is converted into a logical array of 0s and 1s roi = roi[:, :, 3] > 0 # Alternatively a mask could be created manually with for example a disk: # roi = np.zeros((img.shape[0], img.shape[1])) # a, b = 150, 150 # r = 100 # y,x = np.ogrid[-a:img.shape[0]-a, -b:img.shape[1]-b] # mask = x*x + y*y <= r*r # roi[mask] = 1 # ~~~~~~~~~~~~ Example 1: maskSLIC ~~~~~~~~~~~~~ t1 = time.time() # Note that compactness is defined differently because a grid is not used. Lower compactness for maskSLIC is equivalent segments = seg.slic(img, compactness=10, seed_type='nplace', mask=roi, n_segments=120, recompute_seeds=True, plot_examples=True, enforce_connectivity=True) print("Time: {:.2f} s".format(time.time() - t1)) plt.figure() plt.imshow(mark_boundaries(img, segments)) plt.contour(roi, contours=1, colors='red', linewidths=0.5) plt.axis('off') # ~~~~~~~~~~~ Example 2: SLIC ~~~~~~~~~~~~~~~~~ t1 = time.time() segments = seg.slic(img, compactness=10, seed_type='grid', n_segments=100, plot_examples=False, enforce_connectivity=True) # segments[roi==0] = -1 print("Time: {:.2f} s".format(time.time() - t1)) plt.figure() plt.imshow(mark_boundaries(img, segments)) plt.contour(roi, contours=1, colors='red', linewidths=1) plt.axis('off') plt.show() plt.show()怎么保存结果

import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms import skimage.segmentation as seg import numpy as np # 超参数 from PIL import Image num_superpixels = 1000 compactness = 10 sigma = 1 # 定义模型 class SuperpixelSegmentation(nn.Module): def init(self): super(SuperpixelSegmentation, self).init() self.convs = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(64, num_superpixels, kernel_size=1, stride=1) ) def forward(self, x): x = self.convs(x) return x # 加载图像 imgA = Image.open('1.png').convert('RGB') imgB = Image.open('2.jpg').convert('RGB') # 超像素分割 imgA_np = np.array(imgA) segments = seg.slic(imgA_np, n_segments=num_superpixels, compactness=compactness, sigma=sigma) segments = torch.from_numpy(segments).unsqueeze(0).unsqueeze(0).float() segments = F.interpolate(segments, size=(imgA.height, imgA.width), mode='nearest').long() # 应用超像素块范围到图像B imgB_np = np.array(imgB) for i in range(num_superpixels): mask = (segments == i) imgB_np[mask.expand(3, -1, -1)] = np.mean(imgB_np[mask.expand(3, -1, -1)], axis=1, keepdims=True) # 显示超像素分割图像 imgA_segments = np.zeros_like(imgA_np) for i in range(num_superpixels): mask = (segments == i) imgA_segments[mask.expand(3, -1, -1)] = np.random.randint(0, 255, size=(3,)) imgA_segments = Image.fromarray(imgA_segments.astype(np.uint8)) imgB_segments = Image.fromarray(imgB_np) # 显示图像 transforms.ToPILImage()(imgA).show() transforms.ToPILImage()(imgB).show() imgA_segments.show() imgB_segments.show()上述代码出现错误:RuntimeError: expand(CPUBoolType{[1, 1, 512, 512]}, size=[3, -1, -1]): the number of sizes provided (3) must be greater or equal to the number of dimensions in the tensor (4)

from 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 torch.nn as nn import torch # 定义超像素池化层 class SuperpixelPooling(nn.Module): def init(self, n_segments): super(SuperpixelPooling, self).init() self.n_segments = n_segments def forward(self, x): # 获取超像素标记图 segments = slic(x, n_segments=self.n_segments, compactness=10) # 将超像素标记图转换为张量 segments_tensor = torch.from_numpy(segments).unsqueeze(0).float() # 在超像素维度上进行最大池化 pooled = nn.AdaptiveMaxPool2d((self.n_segments, 1))(x * segments_tensor) # 压缩超像素维度 pooled = pooled.squeeze(3) # 返回池化后的特征图 return pooled # 加载图像 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) # 将超像素标记图转换为张量 segments_tensor = torch.from_numpy(segments).unsqueeze(0).float() # 将超像素索引映射可视化 plt.imshow(segments, cmap='gray') plt.show() # 将 Numpy 数组转换为 PIL 图像 segment_img = Image.fromarray((mark_boundaries(img_np, segments) * 255).astype(np.uint8)) # 保存超像素索引映射可视化 segment_img.save('segment_map.jpg') # 使用超像素池化层进行池化 pooling_layer = SuperpixelPooling(n_segments=60) pooled_tensor = pooling_layer(img_tensor) # 将超像素池化后的特征图可视化 plt.imshow(pooled_tensor.squeeze().numpy().transpose(1, 0), cmap='gray') plt.show() 上述代码出现问题: pooled = nn.AdaptiveMaxPool2d((self.n_segments, 1))(x * segments_tensor) RuntimeError: The size of tensor a (512) must match the size of tensor b (3) at non-singleton dimension 2,如何修改

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),并显示超像素池化后的特征图

from 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 torch.nn as nn import torch # 定义超像素池化层 class SuperpixelPooling(nn.Module): def init(self, n_segments): super(SuperpixelPooling, self).init() self.n_segments = n_segments def forward(self, x): # 使用 SLIC 算法生成超像素标记图 segments = slic(x.numpy().transpose(1, 2, 0), n_segments=self.n_segments, compactness=10) # 将超像素标记图转换为张量 segments_tensor = torch.from_numpy(segments).unsqueeze(0).unsqueeze(0) # 将张量 x 与超像素标记图张量 segments_tensor 进行逐元素相乘 pooled = x * segments_tensor.float() # 在超像素维度上进行最大池化 pooled = nn.AdaptiveMaxPool2d((self.n_segments, 1))(pooled) # 压缩超像素维度 pooled = pooled.squeeze(3) # 返回池化后的特征图 return pooled # 加载图像 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) # 将超像素标记图转换为张量 segments_tensor = torch.from_numpy(segments).unsqueeze(0).float() # 将超像素索引映射可视化 plt.imshow(segments, cmap='gray') plt.show() # 将 Numpy 数组转换为 PIL 图像 segment_img = Image.fromarray((mark_boundaries(img_np, segments) * 255).astype(np.uint8)) # 保存超像素索引映射可视化 segment_img.save('segment_map.jpg') # 使用超像素池化层进行池化 pooling_layer = SuperpixelPooling(n_segments=60) pooled_tensor = pooling_layer(img_tensor) # 将超像素池化后的特征图可视化 plt.imshow(pooled_tensor.squeeze().numpy().transpose(1, 0), cmap='gray') plt.show() ,上述代码出现问题:segments = slic(x.numpy().transpose(1, 2, 0), n_segments=self.n_segments, compactness=10) ValueError: axes don't match array,如何修改

from 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('img.png') # 转换为 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=100, compactness=10) # 可视化超像素标记图 segment_img = mark_boundaries(img_np, segments) # 将 Numpy 数组转换为 PIL 图像 segment_img = Image.fromarray((segment_img * 255).astype(np.uint8)) # 保存超像素标记图 segment_img.save('segments.jpg') n_segments = np.max(segments) + 1 # 初始化超像素块的区域 segment_regions = np.zeros((n_segments, img_np.shape[0], img_np.shape[1])) # 遍历每个超像素块 for i in range(n_segments): # 获取当前超像素块的掩码 mask = (segments == i) # 将当前超像素块的掩码赋值给超像素块的区域 segment_regions[i][mask] = 1 # 保存超像素块的区域 np.save('segment_regions.npy', segment_regions) # 加载超像素块的区域 segment_regions = np.load('segment_regions.npy') # 取出第一个超像素块的区域 segment_region = segment_regions[37] segment_region = (segment_region * 255).astype(np.uint8) # 显示超像素块的区域 plt.imshow(segment_region, cmap='gray') plt.show(),将上述代码修改成显示超像素索引映射可视化

from 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 torch.nn as nn import torch # 定义超像素池化层 class SuperpixelPooling(nn.Module): def init(self, n_segments): super(SuperpixelPooling, self).init() self.n_segments = n_segments def forward(self, x): # 使用 SLIC 算法生成超像素标记图 segments = slic(x.permute(0, 2, 3, 1).numpy(), n_segments=self.n_segments, compactness=10) # 将超像素标记图转换为张量 segments_tensor = torch.from_numpy(segments).unsqueeze(0).unsqueeze(0) # 将张量 x 与超像素标记图张量 segments_tensor 进行逐元素相乘 pooled = x * segments_tensor.float() # 在超像素维度上进行最大池化 pooled = nn.AdaptiveMaxPool2d((self.n_segments, 1))(pooled) # 压缩超像素维度 pooled = pooled.squeeze(3) # 返回池化后的特征图 return pooled # 加载图像 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) # 将超像素标记图转换为张量 segments_tensor = torch.from_numpy(segments).unsqueeze(0).float() # 将超像素索引映射可视化 plt.imshow(segments, cmap='gray') plt.show() # 将 Numpy 数组转换为 PIL 图像 segment_img = Image.fromarray((mark_boundaries(img_np, segments) * 255).astype(np.uint8)) # 保存超像素索引映射可视化 segment_img.save('segment_map.jpg') # 使用超像素池化层进行池化 pooling_layer = SuperpixelPooling(n_segments=60) pooled_tensor = pooling_layer(img_tensor) # 将超像素池化后的特征图可视化 plt.imshow(pooled_tensor.squeeze().numpy().transpose(1, 0), cmap='gray') plt.show() ,上述代码出现问题:RuntimeError: adaptive_max_pool2d(): Expected 3D or 4D tensor, but got: [1, 1, 3, 512, 512],如何修改

最新推荐

recommend-type

Python零基础30天速通(小白定制版)(完结)

宣导片:开启Python进阶之路 30动漫番剧播放量影响因素分析1综合案例 29小红书卖货实力与用户分析1综合案例 28星巴克门店探索|Matplotlib实战 27詹姆斯哈登的制胜宝典1 Panads的使用 26一晚5万的酒店| Numpy的使用 25揭开数据分析的面纱1数据分析"三剑客"概述 24虎牙直播数据告诉你谁最火1案例篇 23我的音乐我做主1数据保存之csv和excel 22电竟| BeautifulSoup解析HTML 21对李焕英的评价1HTML基础 20我的美食我做主1爬虫介绍、requests请 19看我四十二变1内容提取和格式转换 18我的版权我做主1PDF就是这么帅 17婚礼策划师离不开你|亲爱的PPT 16运营部的烦恼1战胜Excel 15Up主的创作之路1 Python与word初次 14你的offer之选|邮件发送 13我的存在只为悦你1 Pillow图片处理 12你喜欢的电竟赛事大全1 Python的文件操作 11哈利波特的魔法棒|模块 10龙珠之赛亚人1面向对象基础 09大吉大利今晚吃鸡1特种兵的战场(项目案
recommend-type

20240519基本完整

20240519基本完整
recommend-type

MATLAB仿真项目-大数据源码-疲劳检测识别,可应用于疲劳驾驶监测,专注度检测等(高分期末大作业).rar

本项目提供了一个基于MATLAB的疲劳检测识别仿真系统,旨在帮助计算机相关专业的在校学生、老师和企业员工更好地学习和实践大数据与人工智能技术。该项目可应用于疲劳驾驶监测、专注度检测等领域,具有较高的实用价值。 项目源码已经过运行测试,确保OK,可作为课程设计、毕业设计的优质资源。此外,我们还为您提供了一些网络相关资源,以便您在学习过程中进行参考。这些资源将帮助您更好地理解项目的原理和应用。 本项目的源码适用于初学者,即使是编程基础较弱的同学也能快速上手。同时,源码结构清晰,易于理解和修改。您可以在这个基础上进行二次开发,实现更多有趣的功能。 请放心下载使用,我们为您提供了详细的文档说明,以便您更好地了解和使用该项目。希望这个项目能为您提供实质性的帮助,祝您在学习和工作中取得更好的成绩!
recommend-type

利用协同过滤算法,基于用户历史订单数据,对店铺的用户和商品进行推荐.zip

协同过滤算法(Collaborative Filtering)是一种经典的推荐算法,其基本原理是“协同大家的反馈、评价和意见,一起对海量的信息进行过滤,从中筛选出用户可能感兴趣的信息”。它主要依赖于用户和物品之间的行为关系进行推荐。 协同过滤算法主要分为两类: 基于物品的协同过滤算法:给用户推荐与他之前喜欢的物品相似的物品。 基于用户的协同过滤算法:给用户推荐与他兴趣相似的用户喜欢的物品。 协同过滤算法的优点包括: 无需事先对商品或用户进行分类或标注,适用于各种类型的数据。 算法简单易懂,容易实现和部署。 推荐结果准确性较高,能够为用户提供个性化的推荐服务。 然而,协同过滤算法也存在一些缺点: 对数据量和数据质量要求较高,需要大量的历史数据和较高的数据质量。 容易受到“冷启动”问题的影响,即对新用户或新商品的推荐效果较差。 存在“同质化”问题,即推荐结果容易出现重复或相似的情况。 协同过滤算法在多个场景中有广泛的应用,如电商推荐系统、社交网络推荐和视频推荐系统等。在这些场景中,协同过滤算法可以根据用户的历史行为数据,推荐与用户兴趣相似的商品、用户或内容,从而提高用户的购买转化率、活跃度和社交体验。 未来,协同过滤算法的发展方向可能是结合其他推荐算法形成混合推荐系统,以充分发挥各算法的优势。
recommend-type

用C#实现人工智能中的八数码问题,有界面效果,可以得出结果,也可以逐步求解.zip

用C#实现人工智能中的八数码问题,有界面效果,可以得出结果,也可以逐步求解.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解答下列问题:S—>S;T|T;T—>a 构造任意项目集规范族,构造LR(0)分析表,并分析a;a

对于这个文法,我们可以构造以下项目集规范族: I0: S -> .S S -> .T T -> .a I1: S -> S. [$ T -> T. [$ I2: S -> T. I3: S -> S.;S S -> S.;T T -> T.;a 其中,点(.)表示已经被扫描过的符号,;$表示输入串的结束符号。 根据项目集规范族,我们可以构造出LR(0)分析表: 状态 | a | $ ---- | - | - I0 | s3| I1 | |acc I2 | | 其中s3表示移进到状态3,acc表示接受。在分析字符串a;a时,我们可以按照以下步骤进行
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。