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=100, recompute_seeds=True, plot_examples=True, enforce_connectivity=True) print("Time: {:.2f} s".format(time.time() - t1)) for segment_id in np.unique(segments): mask = segments == segment_id masked_image = img.copy() masked_image[~mask] = 0 cv2.imwrite(r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\result6\segment_{}.png'.format(segment_id), masked_image) 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\result6\maskslic.png')提取每个子块图像的位置和大小信息

时间: 2024-03-22 12:38:16 浏览: 23
可以使用 `regionprops` 函数从分割结果中提取每个子块的位置和大小信息。具体步骤如下: 1. 将分割结果转换为标签图像,其中每个子块的像素值为其对应的标签值。 2. 使用 `regionprops` 函数提取标签图像中每个区域的属性信息,包括区域的位置、大小、像素值等。 3. 遍历所有区域,获取其位置和大小信息。 下面是示例代码: ```python from skimage.measure import label, regionprops # 将分割结果转换为标签图像 label_img = label(segments) # 使用 regionprops 函数提取标签图像中每个区域的属性信息 props = regionprops(label_img) # 遍历所有区域,获取其位置和大小信息 for prop in props: # 获取区域的标签值、位置和大小信息 label_value = prop.label bbox = prop.bbox # (min_row, min_col, max_row, max_col) height = bbox[2] - bbox[0] width = bbox[3] - bbox[1] # 在原图上绘制该区域的边界框 cv2.rectangle(img, (bbox[1], bbox[0]), (bbox[3], bbox[2]), (0, 255, 0), 2) # 输出该区域的位置和大小信息 print("Label: {}, Position: ({}, {}), Size: {} x {}".format(label_value, bbox[1], bbox[0], width, height)) ``` 其中,`bbox` 表示区域的最小外接矩形,其格式为 `(min_row, min_col, max_row, max_col)`,分别表示矩形左上角和右下角的行列坐标。`height` 和 `width` 分别表示矩形的高度和宽度。在实际使用中,可以根据需求选择输出或保存这些信息。

相关推荐

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

elastic-ca证书

elastic-ca证书
recommend-type

源代码-ip封锁程序ASP通用版本.zip

源代码-ip封锁程序ASP通用版本.zip
recommend-type

tensorflow-gpu-2.9.0-cp39-cp39-win-amd64.whl

python
recommend-type

颗粒活性碳市场 - 2024-2032 年行业分析、市场规模、市场份额和预测.docx

颗粒活性碳市场,按原料、按应用、按最终用户、按阶段、按国家和地区划分 - 2024-2032 年行业分析、市场规模、市场份额和预测
recommend-type

STM32项目设计:基于stm32f1的智能门锁已测

最近假期比较闲,拿着之前剩下的模块做了一个小玩具, 先制定一下此次玩具的规划,也可以理解为简易项目书。 开发软件:keil 硬件选型:STM32F103C8T6、RFID读卡器、oled屏幕、按键模块、蓝牙通信模块、蜂鸣器、舵机; 上位机: 1.上位机可以对密码进行设置、重置 2.上位机可以接收密码输入错误的报警弹窗提示。 3.添加或删除ic卡用户信息。 下位机: 密码模式: 1.输入密码,密码正确即开锁,oled屏显示开锁成功 2.若输入错误,OLED显示开锁失败 3.连续三次输错密码,蜂鸣器则发出警报 4.保存密码至FLASH, 调电后不丢失 IC卡模式: 1.读取IC卡身份信息,若系统中有身份信息则开锁成功 2.IC身份错误,系统无身份识别信息,则蜂鸣器报警
recommend-type

中文翻译Introduction to Linear Algebra, 5th Edition 2.1节

中文翻译Introduction to Linear Algebra, 5th Edition 2.1节 线性代数的核心问题是求解方程组。这些方程都是线性的,即未知数仅与数相乘——我们绝不会 遇见 x 乘以 y。我们的第一个线性方程组较小。接下来你来看看它引申出多远: 两个方程 两个未知数 x − 2y = 1 3x + 2y = 11 (1) 我们一次从一个行开始。第一个方程 x − 2y = 1 得出了 xy 平面的一条直线。由于点 x = 1, y = 0 解 出该方程,因此它在这条直线上。因为 3 − 2 = 1,所以点 x = 3, y = 1 也在这条直线上。若我们选择 x = 101,那我们求出 y = 50。 这条特定直线的斜率是 12,是因为当 x 变化 2 时 y 增加 1。斜率在微积分中很重要,然而这是线 性代数! 图 2.1 将展示第一条直线 x − 2y = 1。此“行图”中的第二条直线来自第二个方程 3x + 2y = 11。你 不能错过两条线的交点 x = 3, y = 1。点 (3, 1) 位于两条线上并且解出两个方程。
recommend-type

管理建模和仿真的文件

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

识别MATLAB微分方程求解中的混沌行为:分析非线性方程混沌行为的实用技巧

![matlab求解微分方程](https://img-blog.csdnimg.cn/2021062810300367.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTQ3OTY3OA==,size_16,color_FFFFFF,t_70) # 1. MATLAB微分方程求解概述 微分方程是描述物理、工程和金融等领域中动态系统的数学模型。MATLAB提供了强大的工具来求解微分方程,包括内置求解器和自定义函数
recommend-type

physon如何做ERP系统

作为一个AI语言模型,我可以给您提供一些基本的建议和思路: 1.明确需求和目标:在开始开发ERP系统之前,需要明确您的业务需求和目标,了解您的业务流程、流程数据、员工角色和权限、财务管理等方面的要求,这样才能更好的设计和开发ERP系统。 2.选择技术框架和开发工具:选择合适的技术框架和开发工具是ERP系统开发的关键。选择一种流行的技术框架和工具可以提高开发效率和质量。 3.设计数据库:ERP系统需要一个功能强大的数据库来存储数据。设计数据库需要考虑数据的完整性、安全性和可扩展性。 4.设计系统架构:系统架构是ERP系统的骨架,需要考虑系统的可扩展性、可维护性和性能。 5.开发和测试:
recommend-type

zigbee-cluster-library-specification

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