如何使用python读取bin类型文件并另存为pt类型文件
时间: 2023-08-18 17:04:00 浏览: 109
要使用Python读取bin类型文件并另存为pt类型文件,可以使用以下代码:
```python
import numpy as np
import pickle
# 读取bin文件
with open('file.bin', 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
# 将数据保存为pt文件
with open('file.pt', 'wb') as f:
pickle.dump(data, f)
```
代码中,我们首先使用`numpy`库的`fromfile`函数读取bin文件,将其转换为numpy数组类型的数据。然后使用`pickle`库的`dump`函数将数据保存为pt文件。需要注意的是,pt文件只能序列化Python对象,所以我们需要将numpy数组转换为Python对象。
相关问题
对一组非图像的拓扑图(bin文件,格式为coo)进行训练,图一共有60000左右(即60000多个bin文件),使用VGAE和dgl,代码示例
首先需要安装DGL和PyTorch:
```python
pip install dgl-cu101
pip install torch
```
然后就可以开始编写代码了,下面是一个简单的示例:
```python
import dgl
from dgl.data.utils import load_graphs
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
# 定义模型
class VGAE(torch.nn.Module):
def __init__(self, in_feats, hidden_size, out_feats):
super(VGAE, self).__init__()
self.encoder = torch.nn.Sequential(
torch.nn.Linear(in_feats, hidden_size),
torch.nn.ReLU(),
torch.nn.Linear(hidden_size, out_feats * 2)
)
self.decoder = torch.nn.Linear(out_feats, in_feats)
def reparameterize(self, mu, logvar):
if self.training:
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return eps.mul(std).add_(mu)
else:
return mu
def forward(self, g, features):
h = self.encoder(features)
mu, logvar = torch.chunk(h, 2, dim=1)
z = self.reparameterize(mu, logvar)
reconstructed = self.decoder(z)
return reconstructed, mu, logvar
# 读取数据
graphs, _ = load_graphs("data.bin")
g = graphs[0]
features = g.ndata['feat']
# 定义模型和优化器
model = VGAE(in_feats=features.shape[1], hidden_size=128, out_feats=16)
optimizer = torch.optim.Adam(model.parameters())
# 定义训练函数
def train(model, optimizer, g, features):
model.train()
optimizer.zero_grad()
reconstructed, mu, logvar = model(g, features)
loss = F.mse_loss(reconstructed, features) + 0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())
loss.backward()
optimizer.step()
return loss.item()
# 训练模型
for epoch in range(100):
loss = train(model, optimizer, g, features)
print(f"Epoch {epoch}, loss {loss:.4f}")
# 保存模型
torch.save(model.state_dict(), "model.pt")
```
这段代码中,我们使用DGL读取了一个bin格式的拓扑图,然后定义了一个简单的VGAE模型。我们通过对重构误差和KL散度的加权求和来计算损失。最后,我们使用PyTorch的优化器来更新模型参数,进行训练。训练完成后可以将模型保存下来,以便以后使用。
#!/usr/bin/env python import rospy import cv2 import numpy as np from cv_bridge import CvBridge from sensor_msgs.msg import Image class TemplateMatcher: def __init__(self): self.bridge = CvBridge() self.template = cv2.imread('template.jpg', 0) # 读取你的模板图像 self.image_sub = rospy.Subscriber("/camera/image_raw", Image, self.image_callback) def image_callback(self, data): try: cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) gray_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) res = cv2.matchTemplate(gray_image, self.template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) w, h = self.template.shape[::-1] for pt in zip(*loc[::-1]): cv2.rectangle(cv_image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) cv2.imshow("Image window", cv_image) cv2.waitKey(3) def main(): rospy.init_node('template_matcher', anonymous=True) tm = TemplateMatcher() try: rospy.spin() except KeyboardInterrupt: print("Shutting down") cv2.destroyAllWindows() if __name__ == '__main__': main()
这是一个使用OpenCV在ROS中进行模板匹配的Python代码。它首先初始化一个`TemplateMatcher`类,该类包含一个订阅ROS图像话题的回调函数`image_callback`。然后,它读取一个模板图像并将其保存为灰度图像。每当接收到一个图像消息时,它将其转换为灰度图像,使用`cv2.matchTemplate`函数对其进行模板匹配,并使用`cv2.rectangle`函数在匹配位置处绘制矩形。最后,它显示图像并等待用户按下键盘上的任意键以关闭所有窗口。
阅读全文