spikezoo 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- spikezoo/__init__.py +0 -0
- spikezoo/archs/__init__.py +0 -0
- spikezoo/datasets/__init__.py +68 -0
- spikezoo/datasets/base_dataset.py +157 -0
- spikezoo/datasets/realworld_dataset.py +25 -0
- spikezoo/datasets/reds_small_dataset.py +27 -0
- spikezoo/datasets/szdata_dataset.py +37 -0
- spikezoo/datasets/uhsr_dataset.py +38 -0
- spikezoo/metrics/__init__.py +96 -0
- spikezoo/models/__init__.py +37 -0
- spikezoo/models/base_model.py +177 -0
- spikezoo/models/bsf_model.py +90 -0
- spikezoo/models/spcsnet_model.py +19 -0
- spikezoo/models/spikeclip_model.py +32 -0
- spikezoo/models/spikeformer_model.py +50 -0
- spikezoo/models/spk2imgnet_model.py +51 -0
- spikezoo/models/ssir_model.py +22 -0
- spikezoo/models/ssml_model.py +18 -0
- spikezoo/models/stir_model.py +37 -0
- spikezoo/models/tfi_model.py +18 -0
- spikezoo/models/tfp_model.py +18 -0
- spikezoo/models/wgse_model.py +31 -0
- spikezoo/pipeline/__init__.py +4 -0
- spikezoo/pipeline/base_pipeline.py +267 -0
- spikezoo/pipeline/ensemble_pipeline.py +64 -0
- spikezoo/pipeline/train_pipeline.py +94 -0
- spikezoo/utils/__init__.py +3 -0
- spikezoo/utils/data_utils.py +52 -0
- spikezoo/utils/img_utils.py +72 -0
- spikezoo/utils/other_utils.py +59 -0
- spikezoo/utils/spike_utils.py +82 -0
- spikezoo-0.1.dist-info/LICENSE.txt +17 -0
- spikezoo-0.1.dist-info/METADATA +39 -0
- spikezoo-0.1.dist-info/RECORD +36 -0
- spikezoo-0.1.dist-info/WHEEL +5 -0
- spikezoo-0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,64 @@
|
|
1
|
+
import torch
|
2
|
+
from dataclasses import dataclass, field
|
3
|
+
import os
|
4
|
+
from spikezoo.utils.img_utils import tensor2npy, AverageMeter
|
5
|
+
from spikezoo.utils.spike_utils import load_vidar_dat
|
6
|
+
from spikezoo.metrics import cal_metric_pair, cal_metric_single
|
7
|
+
import numpy as np
|
8
|
+
import cv2
|
9
|
+
from pathlib import Path
|
10
|
+
from enum import Enum, auto
|
11
|
+
from typing import Literal
|
12
|
+
from spikezoo.metrics import metric_pair_names, metric_single_names, metric_all_names
|
13
|
+
from thop import profile
|
14
|
+
import time
|
15
|
+
from datetime import datetime
|
16
|
+
from spikezoo.utils import setup_logging, save_config
|
17
|
+
from tqdm import tqdm
|
18
|
+
from spikezoo.models import build_model_cfg, build_model_name, BaseModel, BaseModelConfig
|
19
|
+
from spikezoo.datasets import build_dataset_cfg, build_dataset_name, BaseDataset, BaseDatasetConfig, build_dataloader
|
20
|
+
from typing import Optional, Union, List
|
21
|
+
from spikezoo.pipeline.base_pipeline import Pipeline, PipelineConfig
|
22
|
+
|
23
|
+
|
24
|
+
@dataclass
|
25
|
+
class EnsemblePipelineConfig(PipelineConfig):
|
26
|
+
_mode: Literal["single_mode", "multi_mode", "train_mode"] = "multi_mode"
|
27
|
+
|
28
|
+
|
29
|
+
class EnsemblePipeline(Pipeline):
|
30
|
+
def __init__(
|
31
|
+
self,
|
32
|
+
cfg: PipelineConfig,
|
33
|
+
model_cfg_list: Union[List[str], List[BaseModelConfig]],
|
34
|
+
dataset_cfg: Union[str, BaseDatasetConfig],
|
35
|
+
):
|
36
|
+
self.cfg = cfg
|
37
|
+
self._setup_model_data(model_cfg_list,dataset_cfg)
|
38
|
+
self._setup_pipeline()
|
39
|
+
|
40
|
+
def _setup_model_data(self,model_cfg_list,dataset_cfg):
|
41
|
+
"""Model and Data setup."""
|
42
|
+
# model
|
43
|
+
self.model_list: List[BaseModel] = (
|
44
|
+
[build_model_name(name) for name in model_cfg_list] if isinstance(model_cfg_list[0],str) else [build_model_cfg(cfg) for cfg in model_cfg_list]
|
45
|
+
)
|
46
|
+
self.model_list = [model.eval() for model in self.model_list]
|
47
|
+
torch.set_grad_enabled(False)
|
48
|
+
# data
|
49
|
+
self.dataset: BaseDataset = build_dataset_name(dataset_cfg) if isinstance(dataset_cfg, str) else build_dataset_cfg(dataset_cfg)
|
50
|
+
self.dataloader = build_dataloader(self.dataset)
|
51
|
+
# device
|
52
|
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
53
|
+
|
54
|
+
def _spk2img(self, spike, img, save_folder):
|
55
|
+
for model in self.model_list:
|
56
|
+
self._spk2img_model(model, spike, img, save_folder)
|
57
|
+
|
58
|
+
def cal_params(self):
|
59
|
+
for model in self.model_list:
|
60
|
+
self._cal_prams_model(model)
|
61
|
+
|
62
|
+
def cal_metrics(self):
|
63
|
+
for model in self.model_list:
|
64
|
+
self._cal_metrics_model(model)
|
@@ -0,0 +1,94 @@
|
|
1
|
+
import torch
|
2
|
+
from dataclasses import dataclass
|
3
|
+
import os
|
4
|
+
from spikezoo.utils.img_utils import tensor2npy
|
5
|
+
import cv2
|
6
|
+
from pathlib import Path
|
7
|
+
from typing import Literal
|
8
|
+
from tqdm import tqdm
|
9
|
+
from spikezoo.models import build_model_cfg, build_model_name, BaseModel, BaseModelConfig
|
10
|
+
from spikezoo.datasets import build_dataset_cfg, build_dataset_name, BaseDataset, BaseDatasetConfig, build_dataloader
|
11
|
+
from typing import Union
|
12
|
+
from spikezoo.pipeline.base_pipeline import Pipeline, PipelineConfig
|
13
|
+
|
14
|
+
|
15
|
+
@dataclass
|
16
|
+
class TrainPipelineConfig(PipelineConfig):
|
17
|
+
bs_train: int = 4
|
18
|
+
epochs: int = 100
|
19
|
+
lr: float = 1e-3
|
20
|
+
num_workers: int = 4
|
21
|
+
pin_memory: bool = False
|
22
|
+
steps_per_save_imgs = 10
|
23
|
+
steps_per_cal_metrics = 10
|
24
|
+
_mode: Literal["single_mode", "multi_mode", "train_mode"] = "train_mode"
|
25
|
+
|
26
|
+
|
27
|
+
class TrainPipeline(Pipeline):
|
28
|
+
def __init__(
|
29
|
+
self,
|
30
|
+
cfg: TrainPipelineConfig,
|
31
|
+
model_cfg: Union[str, BaseModelConfig],
|
32
|
+
dataset_cfg: Union[str, BaseDatasetConfig],
|
33
|
+
):
|
34
|
+
self.cfg = cfg
|
35
|
+
self._setup_model_data(model_cfg, dataset_cfg)
|
36
|
+
self._setup_pipeline()
|
37
|
+
self.model.setup_training(cfg)
|
38
|
+
|
39
|
+
def _setup_model_data(self, model_cfg, dataset_cfg):
|
40
|
+
"""Model and Data setup."""
|
41
|
+
# model
|
42
|
+
self.model: BaseModel = build_model_name(model_cfg) if isinstance(model_cfg, str) else build_model_cfg(model_cfg)
|
43
|
+
self.model = self.model.train()
|
44
|
+
torch.set_grad_enabled(True)
|
45
|
+
# data
|
46
|
+
if isinstance(dataset_cfg, str):
|
47
|
+
self.train_dataset: BaseDataset = build_dataset_name(dataset_cfg, split="train")
|
48
|
+
self.dataset: BaseDataset = build_dataset_name(dataset_cfg, split="test")
|
49
|
+
else:
|
50
|
+
self.train_dataset: BaseDataset = build_dataset_cfg(dataset_cfg, split="train")
|
51
|
+
self.dataset: BaseDataset = build_dataset_cfg(dataset_cfg, split="test")
|
52
|
+
self.train_dataloader = build_dataloader(self.train_dataset, self.cfg)
|
53
|
+
self.dataloader = build_dataloader(self.dataset)
|
54
|
+
# device
|
55
|
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
56
|
+
|
57
|
+
def save_network(self, epoch):
|
58
|
+
"""Save the network."""
|
59
|
+
save_folder = self.save_folder / Path("ckpt")
|
60
|
+
os.makedirs(save_folder, exist_ok=True)
|
61
|
+
self.model.save_network(save_folder / f"{epoch:06d}.pth")
|
62
|
+
|
63
|
+
def save_visual(self, epoch):
|
64
|
+
"""Save the visual results."""
|
65
|
+
self.logger.info("Saving visual results...")
|
66
|
+
save_folder = self.save_folder / Path("imgs") / Path(f"{epoch:06d}")
|
67
|
+
os.makedirs(save_folder, exist_ok=True)
|
68
|
+
for batch_idx, batch in enumerate(tqdm(self.dataloader)):
|
69
|
+
if batch_idx % (len(self.dataloader) // 4) == 0:
|
70
|
+
continue
|
71
|
+
batch = self.model.feed_to_device(batch)
|
72
|
+
outputs = self.model.get_outputs_dict(batch)
|
73
|
+
visual_dict = self.model.get_visual_dict(batch, outputs)
|
74
|
+
# save
|
75
|
+
for key, img in visual_dict.items():
|
76
|
+
cv2.imwrite(str(save_folder / Path(f"{batch_idx:06d}_{key}.png")), tensor2npy(img))
|
77
|
+
|
78
|
+
def train(self):
|
79
|
+
"""Training code."""
|
80
|
+
self.logger.info("Start Training!")
|
81
|
+
for epoch in range(self.cfg.epochs):
|
82
|
+
# training
|
83
|
+
for batch_idx, batch in enumerate(tqdm(self.train_dataloader)):
|
84
|
+
batch = self.model.feed_to_device(batch)
|
85
|
+
outputs = self.model.get_outputs_dict(batch)
|
86
|
+
loss_dict, loss_values_dict = self.model.get_loss_dict(outputs, batch)
|
87
|
+
self.model.optimize_parameters(loss_dict)
|
88
|
+
self.model.update_learning_rate()
|
89
|
+
self.logger.info(f"EPOCH {epoch}/{self.cfg.epochs}: Train Loss: {loss_values_dict}")
|
90
|
+
# save visual results & evaluate metrics
|
91
|
+
if epoch % self.cfg.steps_per_save_imgs == 0 or epoch == self.cfg.epochs - 1:
|
92
|
+
self.save_visual(epoch)
|
93
|
+
if epoch % self.cfg.steps_per_cal_metrics == 0 or epoch == self.cfg.epochs - 1:
|
94
|
+
self.cal_metrics()
|
@@ -0,0 +1,52 @@
|
|
1
|
+
import queue as Queue
|
2
|
+
import threading
|
3
|
+
import torch
|
4
|
+
from torch.utils.data import DataLoader
|
5
|
+
import math
|
6
|
+
import random
|
7
|
+
|
8
|
+
class Augmentor:
|
9
|
+
def __init__(self, crop_size = (-1,-1)):
|
10
|
+
self.crop_size = crop_size
|
11
|
+
|
12
|
+
def augment(self, img, mode=0):
|
13
|
+
mode = mode - mode % 2 if self.use_rot == False else mode
|
14
|
+
if mode == 0:
|
15
|
+
return img
|
16
|
+
elif mode == 1:
|
17
|
+
return torch.flip(torch.rot90(img, 1, [1, 2]), [1]) # flipud + rot90(k=1)
|
18
|
+
elif mode == 2:
|
19
|
+
return torch.flip(img, [1]) # flipud
|
20
|
+
elif mode == 3:
|
21
|
+
return torch.rot90(img, 3, [1, 2]) # rot90(k=3)
|
22
|
+
elif mode == 4:
|
23
|
+
return torch.flip(torch.rot90(img, 2, [1, 2]), [1]) # flipud + rot90(k=2)
|
24
|
+
elif mode == 5:
|
25
|
+
return torch.rot90(img, 1, [1, 2]) # rot90(k=1)
|
26
|
+
elif mode == 6:
|
27
|
+
return torch.rot90(img, 2, [1, 2]) # rot90(k=2)
|
28
|
+
elif mode == 7:
|
29
|
+
return torch.flip(torch.rot90(img, 3, [1, 2]), [1]) # flipud + rot90(k=3)
|
30
|
+
|
31
|
+
def spatial_transform(self, spike, image):
|
32
|
+
mode = random.randint(0, 7)
|
33
|
+
spike_h = spike.shape[1]
|
34
|
+
spike_w = spike.shape[2]
|
35
|
+
# default mode
|
36
|
+
if self.crop_size != (-1,-1):
|
37
|
+
assert spike_h > self.crop_size[0] and spike_w > self.crop_size[1], f"ROI Size should be smaller than spike input size."
|
38
|
+
y0 = random.randint(0, spike_h - self.crop_size[0])
|
39
|
+
x0 = random.randint(0, spike_w - self.crop_size[1])
|
40
|
+
spike = spike[:,y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
|
41
|
+
image = image[:,y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
|
42
|
+
# rotation set
|
43
|
+
self.use_rot = True if image.shape[1] == image.shape[2] else False
|
44
|
+
# aug
|
45
|
+
spike = self.augment(spike, mode=mode)
|
46
|
+
image = self.augment(image, mode=mode)
|
47
|
+
return spike, image
|
48
|
+
|
49
|
+
def __call__(self, spike, image):
|
50
|
+
spike, image = self.spatial_transform(spike, image)
|
51
|
+
return spike, image
|
52
|
+
|
@@ -0,0 +1,72 @@
|
|
1
|
+
import numpy as np
|
2
|
+
import torch
|
3
|
+
import torch.nn as nn
|
4
|
+
from collections import OrderedDict
|
5
|
+
from torch.nn.parallel import DistributedDataParallel
|
6
|
+
|
7
|
+
|
8
|
+
def tensor2npy(tensor,normalize = False):
|
9
|
+
"""Convert the 0-1 torch float tensor to the 0-255 uint numpy array"""
|
10
|
+
if tensor.dim() == 4:
|
11
|
+
tensor = tensor[0,0]
|
12
|
+
tensor = tensor.clip(0, 1).detach().cpu().numpy()
|
13
|
+
if normalize == True:
|
14
|
+
tensor = (tensor - tensor.min()) / (tensor.max() - tensor.min())
|
15
|
+
tensor = 255 * tensor
|
16
|
+
return tensor.astype(np.uint8)
|
17
|
+
|
18
|
+
|
19
|
+
class AverageMeter(object):
|
20
|
+
"""Computes and stores the average and current value"""
|
21
|
+
|
22
|
+
def __init__(self):
|
23
|
+
self.reset()
|
24
|
+
|
25
|
+
def reset(self):
|
26
|
+
self.val = 0
|
27
|
+
self.avg = 0
|
28
|
+
self.sum = 0
|
29
|
+
self.count = 0
|
30
|
+
|
31
|
+
def update(self, val, n=1):
|
32
|
+
self.val = val
|
33
|
+
self.count += n
|
34
|
+
self.sum += val * n
|
35
|
+
self.avg = self.sum / self.count
|
36
|
+
|
37
|
+
def load_network(load_path, network, strict=False):
|
38
|
+
# network multi-gpu training
|
39
|
+
if isinstance(network, nn.DataParallel) or isinstance(network, DistributedDataParallel):
|
40
|
+
network = network.module
|
41
|
+
|
42
|
+
# load .pt or .pth
|
43
|
+
if load_path.endswith('.pt') == True:
|
44
|
+
load_net = torch.load(load_path)
|
45
|
+
if isinstance(load_net, nn.DataParallel) or isinstance(load_net, DistributedDataParallel):
|
46
|
+
load_net = load_net.module
|
47
|
+
|
48
|
+
if isinstance(load_net,nn.Module):
|
49
|
+
load_state = load_net.state_dict()
|
50
|
+
else:
|
51
|
+
load_state = load_net
|
52
|
+
elif load_path.endswith('.pth') == True:
|
53
|
+
load_state = torch.load(load_path)
|
54
|
+
|
55
|
+
# clean multi-gpu state
|
56
|
+
load_state_clean = OrderedDict()
|
57
|
+
for k, v in load_state.items():
|
58
|
+
if k.startswith('module.'):
|
59
|
+
load_state_clean[k[7:]] = v
|
60
|
+
else:
|
61
|
+
load_state_clean[k] = v
|
62
|
+
|
63
|
+
# load the model_weight
|
64
|
+
if 'model_state_dict' in load_state_clean.keys():
|
65
|
+
network.load_state_dict(load_state_clean['model_state_dict'], strict=strict)
|
66
|
+
elif 'model' in load_state_clean.keys():
|
67
|
+
network.load_state_dict(load_state_clean['model'], strict=strict)
|
68
|
+
else:
|
69
|
+
network.load_state_dict(load_state_clean, strict=strict)
|
70
|
+
return network
|
71
|
+
|
72
|
+
|
@@ -0,0 +1,59 @@
|
|
1
|
+
import logging
|
2
|
+
from dataclasses import dataclass, field, asdict
|
3
|
+
import requests
|
4
|
+
from tqdm import tqdm
|
5
|
+
import os
|
6
|
+
|
7
|
+
|
8
|
+
# log info
|
9
|
+
def setup_logging(log_file):
|
10
|
+
logger = logging.getLogger("training_logger")
|
11
|
+
logger.setLevel(logging.INFO)
|
12
|
+
logger.propagate = False
|
13
|
+
if logger.hasHandlers():
|
14
|
+
logger.handlers.clear()
|
15
|
+
file_handler = logging.FileHandler(log_file, mode="w") # 使用'w'模式打开文件
|
16
|
+
file_handler.setLevel(logging.INFO)
|
17
|
+
console_handler = logging.StreamHandler()
|
18
|
+
console_handler.setLevel(logging.INFO)
|
19
|
+
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M")
|
20
|
+
file_handler.setFormatter(formatter)
|
21
|
+
console_handler.setFormatter(formatter)
|
22
|
+
logger.addHandler(file_handler)
|
23
|
+
logger.addHandler(console_handler)
|
24
|
+
return logger
|
25
|
+
|
26
|
+
|
27
|
+
def save_config(cfg, filename, mode="w"):
|
28
|
+
"""Save the config file to the given filename."""
|
29
|
+
filename = str(filename)
|
30
|
+
with open(filename, mode) as file:
|
31
|
+
for key, value in asdict(cfg).items():
|
32
|
+
file.write(f"{key} = {value}\n")
|
33
|
+
file.write("\n")
|
34
|
+
|
35
|
+
|
36
|
+
def download_file(url, output_path):
|
37
|
+
headers = {
|
38
|
+
"sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
|
39
|
+
"sec-ch-ua-mobile": "?0",
|
40
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
|
41
|
+
}
|
42
|
+
try:
|
43
|
+
print(f"Ready to download the file from the {url} 😊😊😊.")
|
44
|
+
response = requests.head(url,headers=headers)
|
45
|
+
response.raise_for_status()
|
46
|
+
file_size = int(response.headers.get("Content-Length", 0))
|
47
|
+
response = requests.get(url, stream=True)
|
48
|
+
response.raise_for_status()
|
49
|
+
if response.status_code == 200:
|
50
|
+
with open(output_path, "wb") as file, tqdm(desc="Downloading", total=file_size, unit="B", unit_scale=True) as bar:
|
51
|
+
for chunk in response.iter_content(chunk_size=1024):
|
52
|
+
if chunk:
|
53
|
+
file.write(chunk)
|
54
|
+
bar.update(len(chunk))
|
55
|
+
print(f"Files downloaded successfully 🎉🎉🎉 and saved on {output_path}!")
|
56
|
+
else:
|
57
|
+
raise RuntimeError(f"Files fail to download 😔😔😔. Try downloading it from {url} and move it to {output_path}.")
|
58
|
+
except requests.exceptions.RequestException as e:
|
59
|
+
raise RuntimeError(f"Files fail to download 😔😔😔. Try downloading it from {url} and move it to {output_path}.")
|
@@ -0,0 +1,82 @@
|
|
1
|
+
import numpy as np
|
2
|
+
import torch
|
3
|
+
import torch.nn as nn
|
4
|
+
import os
|
5
|
+
|
6
|
+
def load_vidar_dat(filename, height, width, remove_head=False, out_type="float", out_format="array"):
|
7
|
+
"""Load the spike stream from the .dat file."""
|
8
|
+
# Spike decode
|
9
|
+
if isinstance(filename, str):
|
10
|
+
array = np.fromfile(filename, dtype=np.uint8)
|
11
|
+
elif isinstance(filename, (list, tuple)):
|
12
|
+
l = []
|
13
|
+
for name in filename:
|
14
|
+
a = np.fromfile(name, dtype=np.uint8)
|
15
|
+
l.append(a)
|
16
|
+
array = np.concatenate(l)
|
17
|
+
else:
|
18
|
+
raise NotImplementedError
|
19
|
+
len_per_frame = height * width // 8
|
20
|
+
framecnt = len(array) // len_per_frame
|
21
|
+
spikes = []
|
22
|
+
for i in range(framecnt):
|
23
|
+
compr_frame = array[i * len_per_frame : (i + 1) * len_per_frame]
|
24
|
+
blist = []
|
25
|
+
for b in range(8):
|
26
|
+
blist.append(np.right_shift(np.bitwise_and(compr_frame, np.left_shift(1, b)), b))
|
27
|
+
frame_ = np.stack(blist).transpose()
|
28
|
+
frame_ = np.flipud(frame_.reshape((height, width), order="C"))
|
29
|
+
spk = frame_.copy()[None]
|
30
|
+
spk = spk[:, :, :-16] if remove_head == True else spk
|
31
|
+
spikes.append(spk)
|
32
|
+
spikes = np.concatenate(spikes)
|
33
|
+
|
34
|
+
# Data type conversion
|
35
|
+
type_dict = {"float": np.float32, "int": np.uint8}
|
36
|
+
spikes = spikes.astype(type_dict[out_type])
|
37
|
+
|
38
|
+
# Output format conversion
|
39
|
+
format_dict = {"array": lambda x: x, "tensor": torch.from_numpy}
|
40
|
+
spikes = format_dict[out_format](spikes)
|
41
|
+
return spikes
|
42
|
+
|
43
|
+
def SpikeToRaw(save_path, SpikeSeq, filpud=True, delete_if_exists=True):
|
44
|
+
"""Save the spike sequence to the .dat file."""
|
45
|
+
if delete_if_exists:
|
46
|
+
if os.path.exists(save_path):
|
47
|
+
os.remove(save_path)
|
48
|
+
sfn, h, w = SpikeSeq.shape
|
49
|
+
remainder = int((h * w) % 8)
|
50
|
+
base = np.power(2, np.linspace(0, 7, 8))
|
51
|
+
fid = open(save_path, 'ab')
|
52
|
+
for img_id in range(sfn):
|
53
|
+
if filpud:
|
54
|
+
spike = np.flipud(SpikeSeq[img_id, :, :])
|
55
|
+
else:
|
56
|
+
spike = SpikeSeq[img_id, :, :]
|
57
|
+
if remainder == 0:
|
58
|
+
spike = spike.flatten()
|
59
|
+
else:
|
60
|
+
spike = np.concatenate([spike.flatten(), np.array([0]*(8-remainder))])
|
61
|
+
spike = spike.reshape([int(h*w/8), 8])
|
62
|
+
data = spike * base
|
63
|
+
data = np.sum(data, axis=1).astype(np.uint8)
|
64
|
+
fid.write(data.tobytes())
|
65
|
+
fid.close()
|
66
|
+
return
|
67
|
+
|
68
|
+
def video2spike_simulation(imgs, threshold=2.0):
|
69
|
+
"""Convert the images input to the spike stream."""
|
70
|
+
imgs = np.array(imgs)
|
71
|
+
T,H, W = imgs.shape
|
72
|
+
spike = np.zeros([T, H, W], np.uint8)
|
73
|
+
integral = np.random.random(size=([H,W])) * threshold
|
74
|
+
for t in range(0, T):
|
75
|
+
integral += imgs[t]
|
76
|
+
fire = (integral - threshold) >= 0
|
77
|
+
fire_pos = fire.nonzero()
|
78
|
+
integral[fire_pos] -= threshold
|
79
|
+
spike[t][fire_pos] = 1
|
80
|
+
return spike
|
81
|
+
|
82
|
+
|
@@ -0,0 +1,17 @@
|
|
1
|
+
MIT License
|
2
|
+
Copyright (c) 2018 YOUR NAME
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
5
|
+
in the Software without restriction, including without limitation the rights
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
8
|
+
furnished to do so, subject to the following conditions:
|
9
|
+
The above copyright notice and this permission notice shall be included in all
|
10
|
+
copies or substantial portions of the Software.
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
12
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
13
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
14
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
15
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
16
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
17
|
+
SOFTWARE.
|
@@ -0,0 +1,39 @@
|
|
1
|
+
Metadata-Version: 2.2
|
2
|
+
Name: spikezoo
|
3
|
+
Version: 0.1
|
4
|
+
Summary: A deep learning toolbox for spike-to-image models.
|
5
|
+
Home-page: https://github.com/chenkang455/Spike-Zoo
|
6
|
+
Author: Kang Chen
|
7
|
+
Author-email: mrchenkang@stu.pku.edu.cn
|
8
|
+
Requires-Python: >=3.7
|
9
|
+
Description-Content-Type: text/markdown
|
10
|
+
License-File: LICENSE.txt
|
11
|
+
Requires-Dist: torch
|
12
|
+
Requires-Dist: requests
|
13
|
+
Requires-Dist: numpy
|
14
|
+
Requires-Dist: tqdm
|
15
|
+
Requires-Dist: scikit-image
|
16
|
+
Requires-Dist: lpips
|
17
|
+
Requires-Dist: pyiqa
|
18
|
+
Requires-Dist: opencv-python
|
19
|
+
Requires-Dist: thop
|
20
|
+
Requires-Dist: pytorch-wavelets
|
21
|
+
Requires-Dist: pytz
|
22
|
+
Requires-Dist: PyWavelets
|
23
|
+
Requires-Dist: pandas
|
24
|
+
Requires-Dist: pillow
|
25
|
+
Requires-Dist: scikit-learn
|
26
|
+
Requires-Dist: scipy
|
27
|
+
Requires-Dist: spikingjelly
|
28
|
+
Requires-Dist: setuptools
|
29
|
+
Dynamic: author
|
30
|
+
Dynamic: author-email
|
31
|
+
Dynamic: description
|
32
|
+
Dynamic: description-content-type
|
33
|
+
Dynamic: home-page
|
34
|
+
Dynamic: requires-dist
|
35
|
+
Dynamic: requires-python
|
36
|
+
Dynamic: summary
|
37
|
+
|
38
|
+
⚡Spike-Zoo is the go-to library for state-of-the-art pretrained **spike-to-image** models for reconstructing the image from the given spike stream. Whether you're looking for a **simple inference** solution or **training** your own spike-to-image models, ⚡Spike-Zoo is a modular toolbox that supports both.
|
39
|
+
|
@@ -0,0 +1,36 @@
|
|
1
|
+
spikezoo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
2
|
+
spikezoo/archs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
3
|
+
spikezoo/datasets/__init__.py,sha256=bnskj7Bo0cWEk8XEBjOB2etTOjtsoReOxjezeZmYyTs,3274
|
4
|
+
spikezoo/datasets/base_dataset.py,sha256=oLBy8R_iZXloYZU-kcLyu680cSgs0J3KM62gAiHyL8E,5800
|
5
|
+
spikezoo/datasets/realworld_dataset.py,sha256=iqn9oYu56Ph2nsA2U5aesTjflNmfr3-6krHVXC49ByM,715
|
6
|
+
spikezoo/datasets/reds_small_dataset.py,sha256=nhX95iWAADlu65XCGsU8CosjLHvxzSgAumA4MDwaTUc,883
|
7
|
+
spikezoo/datasets/szdata_dataset.py,sha256=2zLLKj6PC2XUcmgUMUqKKiA_zQZdZx7hCsI8Ft-i4o8,1230
|
8
|
+
spikezoo/datasets/uhsr_dataset.py,sha256=cuQBEuOw0AFaxV-reLWqsS2KevKTYF2Pr8ak5dSlkbc,1166
|
9
|
+
spikezoo/metrics/__init__.py,sha256=C1sX1sx7-UAvuR-LemYejWB9fsvl786IqIKA6LSY1so,3250
|
10
|
+
spikezoo/models/__init__.py,sha256=ePC94bz7Yjvg_CQQSWCkb7J5E_Tc370408a9tkzDFDQ,1679
|
11
|
+
spikezoo/models/base_model.py,sha256=zqlYuAHPqhLjG86V9qaY7xNUYs7fL3UnvjNdlojOlM0,6766
|
12
|
+
spikezoo/models/bsf_model.py,sha256=KVKmukMfhr8hOIwIlWAKnCvDSHlXK2HJwjzP9bEGpNw,3523
|
13
|
+
spikezoo/models/spcsnet_model.py,sha256=kLzv-ASXZGnqEFx0jUBONBeRCrsnQ_omkQUYEnr6uJc,540
|
14
|
+
spikezoo/models/spikeclip_model.py,sha256=ltEbEb-TNyzHGWHgiOc6-701LSGvSHYiD1WXglwgOJM,1010
|
15
|
+
spikezoo/models/spikeformer_model.py,sha256=oNwmzWNdemJhjDWnPoJwlxUzKLAAu9YpE2J9iwEkEoA,1586
|
16
|
+
spikezoo/models/spk2imgnet_model.py,sha256=QknQeqLfZdU2MoToUsNqFvAGN0rN2-6wzOw6I4Xtqwc,1549
|
17
|
+
spikezoo/models/ssir_model.py,sha256=sVLZ_7BwBqloB3H94BuQfyhbepwS1FdoEtbIkrPqQkk,586
|
18
|
+
spikezoo/models/ssml_model.py,sha256=u_UohCL2Q_iRZ-I_udJiQ5_30_ZASKxhttDgJKLtZ6E,493
|
19
|
+
spikezoo/models/stir_model.py,sha256=fXFajxWs2P4OoAPGXGkwOGJCDslWqJ4wus4mfbvvH7w,1176
|
20
|
+
spikezoo/models/tfi_model.py,sha256=fLaBOz1f3c-wvA8bEYVfUNk9vgtbMhbS02-Xie294mg,536
|
21
|
+
spikezoo/models/tfp_model.py,sha256=khG15qA_32PEb3BaYHFo5BzXUaxh-Napl_0bwXIcGz8,535
|
22
|
+
spikezoo/models/wgse_model.py,sha256=9N1O_ucbdQ_lndLpWNjuhidyWKs8Ct8Wr-OWTYCVc44,860
|
23
|
+
spikezoo/pipeline/__init__.py,sha256=WPsukNR4cannwsghiukqNsWbWGH5DVPapR_Ly-WOU4Q,188
|
24
|
+
spikezoo/pipeline/base_pipeline.py,sha256=Lh00P5wzhPYJRCZryVYIREw5Wv9SN0xNKRGAf22rI_M,11993
|
25
|
+
spikezoo/pipeline/ensemble_pipeline.py,sha256=Aoi0lLcSDi9aJGIyHsjs45OYBqjDBDu97353IHLoUmw,2467
|
26
|
+
spikezoo/pipeline/train_pipeline.py,sha256=AseUJJYhZTIA83IFG4F6nRA6UBrMQ3p4gQaDalM8mA8,4060
|
27
|
+
spikezoo/utils/__init__.py,sha256=bYLlusAXwLCoY4s6nhVgviax9ioRA9aea8qgRmj2HpI,152
|
28
|
+
spikezoo/utils/data_utils.py,sha256=mk1xeyIb7o_E1J7Z6-gtPq-rpKiMTxAWSTcvvPvVku8,2033
|
29
|
+
spikezoo/utils/img_utils.py,sha256=0O9z58VzLxQEAuz-GGWCbpeHuHPOCpgBVjCBV9kf6sI,2257
|
30
|
+
spikezoo/utils/other_utils.py,sha256=Zy7_UM0AeppKh7u9EFL3hBj7IeQtMwqrSOXDqwBzT74,2539
|
31
|
+
spikezoo/utils/spike_utils.py,sha256=CJao2QuQkxEzOCGaf1UfeP0xFsrit5QhIT_uAsLk4PE,2830
|
32
|
+
spikezoo-0.1.dist-info/LICENSE.txt,sha256=ukEi8E0PKq1dQGTXHUflg3rppLymwAhr7il9x-0nPgg,1062
|
33
|
+
spikezoo-0.1.dist-info/METADATA,sha256=_OkXJ9Yq67P2XDVAJuF74UvSKTn8ga0cMlxoWCrKj0A,1230
|
34
|
+
spikezoo-0.1.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
35
|
+
spikezoo-0.1.dist-info/top_level.txt,sha256=xF2iuOstrACJh43NW4dsTwIdgKfXPXAb_Xzl3M1ricM,9
|
36
|
+
spikezoo-0.1.dist-info/RECORD,,
|
@@ -0,0 +1 @@
|
|
1
|
+
spikezoo
|