keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
oopil/3D_medical_image_FSS
UNet_upperbound/models/encoder.py
.py
849
29
import pdb import torch import torch.nn as nn import torchvision from .vgg import Encoder_vgg # from torchsummary import summary if __name__ == '__main__': from nnutils import conv_unit else: from .nnutils import conv_unit class Encoder(nn.Module): def __init__(self, pretrained_path, device): super(Encoder, self).__init__() self.encoder_list = list(Encoder_vgg(in_channels=5, pretrained_path=pretrained_path).features.to(device)) self.conv1x1 = conv_unit(in_ch=512, out_ch=512, kernel_size=1, activation='relu').to(device) def forward(self, x): ft_list = [] out = x for model_i, model in enumerate(self.encoder_list): out = model(out) if model_i % 2 == 0: ft_list.append(out) out = self.conv1x1(out) return out, ft_list[:]
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/models/nnutils.py
.py
1,670
51
import torch import torch.nn as nn def conv_unit(in_ch, out_ch, kernel_size, stride = 1, padding = 0, activation = 'relu', batch_norm = True): seq_list = [] seq_list.append(nn.Conv2d(in_channels = in_ch, out_channels = out_ch, kernel_size = kernel_size, stride = stride, padding = padding)) if batch_norm: seq_list.append(nn.BatchNorm2d(num_features = out_ch)) if activation == 'relu': seq_list.append(nn.ReLU()) elif activation == 'sigmoid': seq_list.append(nn.Sigmoid()) return nn.Sequential(*seq_list) # class VOSBaseArch(nn.Module): # def __init__(self, initializer, encoder, convlstmcell, decoder, cost_fn, optimizer): # super(VOSBaseArch, self).__init__() # self.initializer = initializer # self.encoder = encoder # self.convlstmcell = convlstmcell # self.decoder = decoder # self.cost_fn = cost_fn # self.optimizer = optimizer # def forward(self, x, y, t): # yhat_list = [] # loss_list = [] # loss_per_video = 0.0 # print(x[:, 0, :, :, :].size(), y[:, 0, :, :, :].size()) # ci, hi = initializer(x[:, 0, :, :, :] + y[:, 0, :, :, :]) # for frame_id in range(1, x.size(1)): # xi = x[:, frame_id, :, :, :] # yi = y[:, frame_id, :, :, :] # xi = encoder(xi) # ci, hi = convlstmcell(xi, ci, hi) # yhati = decoder(hi) # yhat_list.append(yhati) # loss = cost_fn(yhati, yi) # loss_per_video += loss # loss_list.append(loss.item()) # return yhat_list, loss_list, loss_per_video
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/models/__init__.py
.py
0
0
null
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/models/vgg.py
.py
4,435
119
""" Encoder for few shot segmentation (VGG16) """ import torch import torch.nn as nn import pdb class Encoder_vgg(nn.Module): """ Encoder for few shot segmentation Args: in_channels: number of input channels pretrained_path: path of the model for initialization """ def __init__(self, in_channels=2, pretrained_path=None): super().__init__() self.pretrained_path = pretrained_path ## basic model features = nn.Sequential( self._make_layer(2, in_channels, 64), nn.MaxPool2d(kernel_size=3, stride=2, padding=1), self._make_layer(2, 64, 128), nn.MaxPool2d(kernel_size=3, stride=2, padding=1), self._make_layer(3, 128, 256), nn.MaxPool2d(kernel_size=3, stride=2, padding=1), self._make_layer(3, 256, 512), nn.MaxPool2d(kernel_size=3, stride=1, padding=1), self._make_layer(3, 512, 512, dilation=2, lastRelu=False), ) ## vgg16 model features1 = nn.Sequential( ## 5 pooling and 1 dilation self._make_layer(2, in_channels, 64), nn.MaxPool2d(kernel_size=2, stride=2), self._make_layer(2, 64, 128), nn.MaxPool2d(kernel_size=2, stride=2), self._make_layer(3, 128, 256), nn.MaxPool2d(kernel_size=2, stride=2), self._make_layer(3, 256, 512), nn.MaxPool2d(kernel_size=2, stride=2), ## no pooing self._make_layer(3, 512, 512, dilation=2), #, lastRelu=False # dilation 2 nn.MaxPool2d(kernel_size=2, stride=2), ) features2 = nn.Sequential( ## 4 pooling and 1 dilation self._make_layer(2, in_channels, 64), nn.MaxPool2d(kernel_size = 2, stride = 2), self._make_layer(2, 64, 128), nn.MaxPool2d(kernel_size = 2, stride = 2), self._make_layer(3, 128, 256), nn.MaxPool2d(kernel_size = 2, stride = 2), self._make_layer(3, 256, 512), # nn.MaxPool2d(kernel_size = 2, stride = 2), # self._make_layer(3, 512, 512, dilation=1, lastRelu=False), #, lastRelu=False # dilation 2 # nn.MaxPool2d(kernel_size=2, stride=2), nn.MaxPool2d(kernel_size = 1, stride = 1), # 1 for no pooling self._make_layer(3, 512, 512, dilation=2, lastRelu=False), #, lastRelu=False # dilation 2 ) # self.features = features1 self.features = features2 self._init_weights() def forward(self, x): return self.features(x) def _make_layer(self, n_convs, in_channels, out_channels, dilation=1, lastRelu=True): """ Make a (conv, relu) layer Args: n_convs: number of convolution layers in_channels: input channels out_channels: output channels """ layer = [] for i in range(n_convs): layer.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, dilation=dilation, padding=dilation)) ## add Batch normalization # layer.append(nn.BatchNorm2d(out_channels, momentum=1, affine=False)) if i != n_convs - 1 or lastRelu: layer.append(nn.ReLU(inplace=True)) in_channels = out_channels return nn.Sequential(*layer) def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): torch.nn.init.kaiming_normal_(m.weight, nonlinearity='relu') if self.pretrained_path is not None: # print("load pretrained model.") dic = torch.load(self.pretrained_path, map_location='cpu') keys = list(dic.keys()) new_dic = self.state_dict() new_keys = list(new_dic.keys()) ## remove variables for Batch normalization # print(new_keys) length = len(new_keys) for i in range(len(new_keys)): idx = length - 1 - i key = new_keys[idx] if "bias" in key or "weight" in key: pass else: new_keys.remove(key) for i in range(4,26): #26 new_dic[new_keys[i]] = dic[keys[i]] self.load_state_dict(new_dic)
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/dataloaders_medical/common.py
.py
6,690
210
""" Dataset classes for common uses """ import random import SimpleITK as sitk import numpy as np from PIL import Image from torch.utils.data import Dataset import torch import torchvision.transforms.functional as tr_F from skimage.exposure import equalize_hist import pdb def crop_resize(slice): x_size, y_size = np.shape(slice) slice = slice[40:x_size - 20, 50:y_size - 50] slice = resize(slice, (240, 240)) return slice def fill_empty_space(arr): arr[arr==0] = np.mean(arr) return arr def prostate_sample(img_arr, label_arr, isize): img = Image.fromarray(img_arr.astype(np.uint8)) label = Image.fromarray(label_arr.astype(np.uint8)) sample = { 'image':img, 'label':label, 'inst':label, 'scribble':label, } # pdb.set_trace() sample = resize(sample, (isize,isize)) sample = to_tensor_normalize(sample) return sample def prostate_mask(sample, isize): # pdb.set_trace() label = sample['label'] fg_mask = torch.where(label == 1, torch.ones_like(label), torch.zeros_like(label)) bg_mask = torch.ones_like(label) - fg_mask fg_mask = fg_mask.expand((1, isize, isize)) bg_mask = bg_mask.expand((1, isize, isize)) return {'fg_mask': fg_mask, 'bg_mask': bg_mask, } def get_support_sample(ipath, lpath, modal_index, mask_n, is_HE, shift=0): arr = read_npy(ipath, modal_index, is_HE) # pdb.set_trace() ## for debugging # arr = fill_empty_space(arr) arr_mask = read_sitk(lpath) ## for 2-way(binary) segmentation arr_mask = (arr_mask>0)*1.0 # arr_mask = (arr_mask == mask_n) * 1.0 cnt = np.sum(arr_mask, axis=(1, 2)) maxarg = np.argmax(cnt) slice = arr[maxarg+shift, :, :] slice = crop_resize(slice) # slice = normalize(slice) slice = convert3ch(slice) save_img(slice, "tmp_img.png") slice_mask = arr_mask[maxarg+shift, :, :]*255.0 slice_mask = crop_resize(slice_mask) # slice_mask = convert3ch(slice_mask) save_img(slice_mask, "tmp_label.png") sample = read_sample("tmp_img.png", "tmp_label.png") # sample = transforms(sample) sample = to_tensor_normalize(sample) return sample ## for 5 way segmentation # arr_mask = (arr_mask == mask_n)*1.0 # if mask_n == 2: # arr_mask = (arr_mask > 0)*1.0 # elif mask_n == 1: # arr_mask = (arr_mask == 1)*1.0 # elif mask_n == 4: # arr_mask = (arr_mask == 4)*1.0 + (arr_mask == 1)*1.0 # else: # raise("invalid mask_n") def getMask(sample, class_id=1, class_ids=[0, 1]): label = sample['label'] empty = sample['empty'] fg_mask = torch.where(label == class_id, torch.ones_like(label), torch.zeros_like(label)) brain_bg_mask = empty # bg_mask = torch.ones_like(label) - fg_mask - empty bg_mask = torch.ones_like(label) - fg_mask # brain_fg_mask = torch.ones_like(label) - empty brain_fg_mask = torch.ones_like(label) - empty - fg_mask fg_mask = fg_mask.expand((1, 240, 240)) bg_mask = bg_mask.expand((1, 240, 240)) brain_fg_mask = brain_fg_mask.expand((1, 240, 240)) brain_bg_mask = brain_bg_mask.expand((1, 240, 240)) return {'fg_mask': fg_mask, 'bg_mask': bg_mask, 'brain_fg_mask': brain_fg_mask, 'brain_bg_mask': brain_bg_mask,} def read_npy(path, modal_index, is_HE): arr = np.load(path)[modal_index] if is_HE: arr = equalize_hist(arr) arr = normalize(arr, type=0) return arr def convert3ch(slice, axis=2): slice = np.expand_dims(slice, axis=axis) slice = np.concatenate([slice, slice, slice], axis=axis) return slice def normalize(arr, type=0): # print(np.mean(arr*255.0), np.std(arr*255.0), np.amin(arr*255.0), np.amax(arr*255.0)) if type == 0: # min and max mini = np.amin(arr) arr -= mini maxi = np.amax(arr) arr_norm = arr/maxi elif type == 1: # stddev and mean mean = np.mean(arr) stddev = np.std(arr) arr_norm = (arr-mean)/stddev return arr_norm*255.0 def map_distribution(arr, tg_mean=0, tg_std=1, tg_min=0, tg_max=255): arr_nonzero = arr[np.nonzero(arr)] ## input arr range : (0,255) mean, std, mini, maxi = np.mean(arr_nonzero), np.std(arr_nonzero), np.amin(arr_nonzero), np.amax(arr_nonzero) Z = (arr - mean) / std ## map arr into standard var Z new_arr = Z*tg_std + tg_mean ## map Z into the target distribution print(np.mean(new_arr), np.std(new_arr), np.amin(new_arr), np.amax(new_arr)) new_arr = np.clip(new_arr, tg_min, tg_max) return new_arr def to_tensor_normalize(sample): img, label = sample['image'], sample['label'] inst, scribble = sample['inst'], sample['scribble'] ## map distribution # pdb.set_trace() # arr = np.array(img) # arr = map_distribution(arr, tg_mean=0.456, tg_std=0.224, tg_min=-10, tg_max=10) # img = Image.fromarray(arr.astype(dtype=np.uint8)) img = tr_F.to_tensor(img) empty = (img[0] == 0.0) * 1.0 img = tr_F.normalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) label = torch.Tensor(np.array(label)).long() img = img.expand((1, 3, 240, 240)) label = label/255.0 sample['empty'] = empty.long() sample['image'] = img sample['label'] = label sample['inst'] = inst sample['scribble'] = scribble return sample def read_sample(img_path, label_path): sample = {} sample['image'] = Image.open(img_path) sample['label'] = Image.open(label_path) sample['inst'] = Image.open(label_path) sample['scribble'] = Image.open(label_path) # Save the original image (without normalization) sample['original'] = Image.open(img_path) return sample def read_sitk(path): itk_img = sitk.ReadImage(path) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def save_sitk(arr, itk_ref, opath): sitk_oimg = sitk.GetImageFromArray(arr) sitk_oimg.CopyInformation(itk_ref) sitk.WriteImage(sitk_oimg, opath) def save_img(arr, path): im = Image.fromarray(arr.astype(np.uint8)) im.save(path) def load_img(path): arr = read_PIL(path) return to_tensor_normalize(arr) def load_seg(path): arr = read_PIL(path) arr = np.expand_dims(arr, axis=0) arr = tr_F.to_tensor(arr) return arr def read_PIL(path): im = Image.open(path) arr = np.array(im, dtype=np.float32) # arr = np.swapaxes(arr, 0, 2) return arr def resize(sample, size): img, label = sample['image'], sample['label'] img = tr_F.resize(img, size) label = tr_F.resize(label, size, interpolation=Image.NEAREST) sample['image'] = img sample['label'] = label return sample
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/dataloaders_medical/dataset.py
.py
9,037
259
import os import re import sys import json import math import random import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") # sys.path.append("../dataloaders_medical") from dataloaders_medical.common import * # from common import * import cv2 from cv2 import resize def prostate_img_process(img_arr, HE=False): if HE: img_arr = equalize_hist(img_arr) * 255.0 else: img_arr = normalize(img_arr, type=0) return img_arr def totensor(arr): tensor = torch.from_numpy(arr).float() return tensor def random_augment(s_imgs, s_labels, q_imgs, q_labels): ## do random rotation and flip k = random.sample([i for i in range(0, 4)], 1)[0] s_imgs = np.rot90(s_imgs, k, (3, 4)).copy() s_labels = np.rot90(s_labels, k, (3, 4)).copy() q_imgs = np.rot90(q_imgs, k, (2, 3)).copy() q_labels = np.rot90(q_labels, k, (2, 3)).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 3).copy() s_labels = np.flip(s_labels, 3).copy() q_imgs = np.flip(q_imgs, 2).copy() q_labels = np.flip(q_labels, 2).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 4).copy() s_labels = np.flip(s_labels, 4).copy() q_imgs = np.flip(q_imgs, 3).copy() q_labels = np.flip(q_labels, 3).copy() return s_imgs, s_labels, q_imgs, q_labels class Base_dataset(): def __init__(self, img_paths, label_paths, config): """ dataset constructor for training """ super().__init__() self.mode = config['mode'] self.length = config['n_iter'] # self.length = len(img_paths) self.valid_img_n = len(img_paths) self.size = config['size'] self.img_paths = img_paths self.label_paths = label_paths self.q_slice = config["q_slice"] self.n_shot = config["n_shot"] self.s_idx = config["s_idx"] self.is_train = True if str(self.__class__).split(".")[-1][:4]=="Test": self.is_train = False ## load file names in advance self.img_lists = [] self.slice_cnts = [] for img_path in self.img_paths: fnames = os.listdir(img_path) self.slice_cnts.append(len(fnames)) fnames = [int(e.split(".")[0]) for e in fnames] fnames.sort() fnames = [f"{e}.npy" for e in fnames] self.img_lists.append(fnames) ## remove ids if its slice number is less than max_slice number if self.is_train: remove_ids = [] for i, img_list in enumerate(self.img_lists): if len(img_list) < self.q_slice: remove_ids.append(i) print(self.is_train, self.__class__, self.valid_img_n," # of remove ids : ", len(remove_ids)) for id in reversed(remove_ids): self.img_paths.pop(id) self.label_paths.pop(id) self.img_lists.pop(id) self.valid_img_n -= 1 ## count the test counts for validation else: self.q_cnts = [] for img_list in self.img_lists: self.q_cnts.append(len(img_list)-self.q_slice+1) self.length = sum(self.q_cnts) print(f"# of data : {self.length}") def get_sample(self, s_img_paths_all, s_label_paths_all): seed = random.randrange(0,1000) # s_length = len(s_img_paths) s_imgs_all, s_labels_all = [],[] for s_idx, s_img_paths in enumerate(s_img_paths_all): s_label_paths = s_label_paths_all[s_idx] imgs, labels = [],[] for i in range(len(s_img_paths)): img_path, label_path = s_img_paths[i], s_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) s_imgs = np.stack(imgs,axis=0) s_labels = np.stack(labels,axis=0) s_imgs_all.append(s_imgs) s_labels_all.append(s_labels) s_imgs = np.stack(s_imgs_all,axis=0) s_labels = np.stack(s_labels_all,axis=0) sample = { "s_x":totensor(s_imgs), "s_y":totensor(s_labels), #.long() # "s_length":s_length, # "q_length":q_length, "s_fname":s_img_paths_all, } return sample def random_flip_z(self, q, s): if random.random() < 0.5: q.reverse() s.reverse() return q,s def getitem_train(self): ## choose support and target idx_space = [i for i in range(self.valid_img_n)] # print(idx_space, self.n_shot) subj_idxs = random.sample(idx_space, self.n_shot) s_subj_idxs = subj_idxs[:self.n_shot] s_subj_idx = s_subj_idxs[0] fnames = self.img_lists[s_subj_idx] idx_start = random.randrange(0,len(fnames)-self.q_slice) idxs = [n for n in range(idx_start, idx_start+self.q_slice)] s_img_paths_all, s_label_paths_all = [],[] s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] s_fnames = self.img_lists[s_subj_idx] s_fnames_selected = [s_fnames[idx] for idx in idxs] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) return self.get_sample(s_img_paths_all, s_label_paths_all) def getitme_test(self, idx): s_subj_idx, idx_start = self.get_test_subj_idx(idx) s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] fnames = self.img_lists[s_subj_idx] idxs = [n for n in range(idx_start, idx_start+self.q_slice)] s_img_paths_all, s_label_paths_all = [],[] s_fnames_selected = [fnames[idx] for idx in idxs] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) return self.get_sample(s_img_paths_all, s_label_paths_all) def get_len_train(self): return self.length def get_len_test(self): return self.length def get_val_subj_idx(self, idx): for subj_idx,cnt in enumerate(self.q_cnts): if idx < cnt: return subj_idx, idx*self.q_slice else: idx -= cnt print("get_val_subj_idx function is not working.") assert False def get_test_subj_idx(self, idx): # for subj_idx,cnt in enumerate(self.slice_cnts): for subj_idx,cnt in enumerate(self.q_cnts): if idx < cnt: return subj_idx, idx else: idx -= cnt print("get_test_subj_idx function is not working.") assert False def get_cnts(self): ## only for test loader return self.q_cnts # return self.slice_cnts def img_load(self, img_path, seed=0): img_arr = np.load(img_path) return img_arr class BaseLoader(Base_dataset): modal_i = [0] # there is only one modality label_i = 1.0 # there is only one label for each image class TrainLoader(BaseLoader): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class TestLoader(BaseLoader): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) def set_support_volume(self, s_img_paths, s_label_paths): ## set support img path and label path for validation and testing self.s_img_paths = [] self.s_label_paths = [] self.s_fnames_list = [] for i in range(len(s_img_paths)): s_fnames = os.listdir(s_img_paths[i]) s_fnames = [int(e.split(".")[0]) for e in s_fnames] s_fnames.sort() print(f'support img {i} path : {s_img_paths[i]} length : {len(s_fnames)}') self.s_img_paths.append(s_img_paths[i]) self.s_label_paths.append(s_label_paths[i]) self.s_fnames_list.append([f"{e}.npy" for e in s_fnames]) if __name__ == "__main__": pass # main()
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/dataloaders_medical/__init__.py
.py
0
0
null
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/dataloaders_medical/dataset_CT_ORG.py
.py
8,872
247
import os import re import sys import json import math import random import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") # sys.path.append("../dataloaders_medical") from dataloaders_medical.common import * # from common import * import cv2 from cv2 import resize def totensor(arr): tensor = torch.from_numpy(arr).float() return tensor def random_augment(s_imgs, s_labels, q_imgs, q_labels): ## do random rotation and flip k = random.sample([i for i in range(0, 4)], 1)[0] s_imgs = np.rot90(s_imgs, k, (3, 4)).copy() s_labels = np.rot90(s_labels, k, (3, 4)).copy() q_imgs = np.rot90(q_imgs, k, (2, 3)).copy() q_labels = np.rot90(q_labels, k, (2, 3)).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 3).copy() s_labels = np.flip(s_labels, 3).copy() q_imgs = np.flip(q_imgs, 2).copy() q_labels = np.flip(q_labels, 2).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 4).copy() s_labels = np.flip(s_labels, 4).copy() q_imgs = np.flip(q_imgs, 3).copy() q_labels = np.flip(q_labels, 3).copy() return s_imgs, s_labels, q_imgs, q_labels class Base_dataset_ctorg(): def __init__(self, img_paths, label_paths, config): """ dataset constructor for training """ super().__init__() self.mode = config['mode'] self.length = config['n_iter'] # self.length = len(img_paths) self.valid_img_n = len(img_paths) self.size = config['size'] self.img_paths = img_paths self.label_paths = label_paths self.q_slice = config["q_slice"] self.n_shot = config["n_shot"] self.s_idx = config["s_idx"] self.is_train = True train_criterion=str(self.__class__).split(".")[-1][:4] print(f"train_criterion : {train_criterion}") if train_criterion=="Test": self.is_train = False ## load file names in advance self.img_lists = [] for img_path in self.img_paths: fnames = os.listdir(img_path) fnames = [int(e.split(".")[0]) for e in fnames] fnames.sort() fnames = [f"{e}.npy" for e in fnames] self.img_lists.append(fnames) ## remove ids if its slice number is less than max_slice number if self.is_train: remove_ids = [] for i, img_list in enumerate(self.img_lists): if len(img_list) < self.q_slice: remove_ids.append(i) print(self.is_train, self.__class__, self.valid_img_n," # of remove ids : ", len(remove_ids)) for id in reversed(remove_ids): self.img_paths.pop(id) self.label_paths.pop(id) self.img_lists.pop(id) self.valid_img_n -= 1 ## count the test counts for validation else: self.q_cnts = [] for img_list in self.img_lists: self.q_cnts.append(len(img_list)-self.q_slice+1) self.length = sum(self.q_cnts) print(f"# of data : {self.length}") def get_sample(self, s_img_paths_all, s_label_paths_all): seed = random.randrange(0,1000) # s_length = len(s_img_paths) s_imgs_all, s_labels_all = [],[] for s_idx, s_img_paths in enumerate(s_img_paths_all): s_label_paths = s_label_paths_all[s_idx] imgs, labels = [],[] for i in range(len(s_img_paths)): img_path, label_path = s_img_paths[i], s_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) s_imgs = np.stack(imgs,axis=0) s_labels = np.stack(labels,axis=0) s_imgs_all.append(s_imgs) s_labels_all.append(s_labels) s_imgs = np.stack(s_imgs_all,axis=0) s_labels = np.stack(s_labels_all,axis=0) # align with other dataset s_imgs = np.flip(s_imgs, 3).copy() s_labels = np.flip(s_labels, 3).copy() sample = { "s_x":totensor(s_imgs), "s_y":totensor(s_labels), #.long() # "s_length":s_length, # "q_length":q_length, "s_fname":s_img_paths_all, } return sample def random_flip_z(self, q, s): if random.random() < 0.5: q.reverse() s.reverse() return q,s def getitem_train(self): ## choose support and target idx_space = [i for i in range(self.valid_img_n)] # print(idx_space, self.n_shot) subj_idxs = random.sample(idx_space, self.n_shot) s_subj_idxs = subj_idxs[:self.n_shot] s_subj_idx = s_subj_idxs[0] fnames = self.img_lists[s_subj_idx] idx_start = random.randrange(0,len(fnames)-self.q_slice) idxs = [n for n in range(idx_start, idx_start+self.q_slice)] s_img_paths_all, s_label_paths_all = [],[] s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] s_fnames = self.img_lists[s_subj_idx] s_fnames_selected = [s_fnames[idx] for idx in idxs] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) return self.get_sample(s_img_paths_all, s_label_paths_all) def getitme_test(self, idx): s_subj_idx, idx_start = self.get_test_subj_idx(idx) s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] fnames = self.img_lists[s_subj_idx] idxs = [n for n in range(idx_start, idx_start+self.q_slice)] s_img_paths_all, s_label_paths_all = [],[] s_fnames_selected = [fnames[idx] for idx in idxs] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) return self.get_sample(s_img_paths_all, s_label_paths_all) def get_len_train(self): return self.length def get_len_test(self): return self.length def get_test_subj_idx(self, idx): # for subj_idx,cnt in enumerate(self.slice_cnts): for subj_idx,cnt in enumerate(self.q_cnts): if idx < cnt: # print(subj_idx, idx, self.q_cnts[subj_idx], len(self.img_lists[subj_idx])) return subj_idx, idx else: idx -= cnt print("get_test_subj_idx function is not working.") assert False def get_cnts(self): ## only for test loader return self.q_cnts # return self.slice_cnts def img_load(self, img_path, seed=0): img_arr = np.load(img_path)+0.25 # print(img_arr) return img_arr def set_support_volume(self, s_img_paths, s_label_paths): ## set support img path and label path for validation and testing self.s_img_paths = [] self.s_label_paths = [] self.s_fnames_list = [] for i in range(len(s_img_paths)): s_fnames = os.listdir(s_img_paths[i]) s_fnames = [int(e.split(".")[0]) for e in s_fnames] s_fnames.sort() print(f'support img {i} path : {s_img_paths[i]} length : {len(s_fnames)}') self.s_img_paths.append(s_img_paths[i]) self.s_label_paths.append(s_label_paths[i]) self.s_fnames_list.append([f"{e}.npy" for e in s_fnames]) class BaseLoader_CTORG(Base_dataset_ctorg): modal_i = [0] # there is only one modality label_i = 1.0 # there is only one label for each image class TrainLoader_CTORG(BaseLoader_CTORG): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class TestLoader_CTORG(BaseLoader_CTORG): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) if __name__ == "__main__": pass # main()
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/dataloaders_medical/dataset_decathlon.py
.py
13,370
432
import os import re import sys import json import random import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") # sys.path.append("../dataloaders_medical") from dataloaders_medical.common import * # from common import * import cv2 from cv2 import resize def totensor(arr): tensor = torch.from_numpy(arr).float() # tensor = F.interpolate(tensor, size=size,mode=interp) return tensor def random_augment(s_imgs, s_labels, q_imgs, q_labels): ## do random rotation and flip k = random.sample([i for i in range(0, 4)], 1)[0] s_imgs = np.rot90(s_imgs, k, (3, 4)).copy() s_labels = np.rot90(s_labels, k, (3, 4)).copy() q_imgs = np.rot90(q_imgs, k, (2, 3)).copy() q_labels = np.rot90(q_labels, k, (2, 3)).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 3).copy() s_labels = np.flip(s_labels, 3).copy() q_imgs = np.flip(q_imgs, 2).copy() q_labels = np.flip(q_labels, 2).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 4).copy() s_labels = np.flip(s_labels, 4).copy() q_imgs = np.flip(q_imgs, 3).copy() q_labels = np.flip(q_labels, 3).copy() return s_imgs, s_labels, q_imgs, q_labels class Base_dataset(): def __init__(self, img_paths, label_paths, config): """ dataset constructor for training """ super().__init__() self.mode = config['mode'] self.length = config['n_iter'] # self.length = len(img_paths) self.valid_img_n = len(img_paths) self.size = config['size'] self.img_paths = img_paths self.label_paths = label_paths self.q_slice = config["q_slice"] self.n_shot = config["n_shot"] self.s_idx = config["s_idx"] self.is_train = True if str(self.__class__).split("_")[-1][:4]=="test": self.is_train = False ## load file names in advance self.img_lists = [] for img_path in self.img_paths: fnames = os.listdir(img_path) fnames = [int(e.split(".")[0]) for e in fnames] fnames.sort() fnames = [f"{e}.npy" for e in fnames] self.img_lists.append(fnames) ## remove ids if its slice number is less than max_slice number if self.is_train: remove_ids = [] for i, img_list in enumerate(self.img_lists): if len(img_list) < self.q_slice: remove_ids.append(i) print(self.is_train, self.__class__, self.valid_img_n," # of remove ids : ", len(remove_ids)) for id in reversed(remove_ids): self.img_paths.pop(id) self.label_paths.pop(id) self.img_lists.pop(id) self.valid_img_n -= 1 ## count the test counts for validation else: self.q_cnts = [] for img_list in self.img_lists: self.q_cnts.append(len(img_list)-self.q_slice+1) self.length = sum(self.q_cnts) print(f"# of data : {self.length}") def get_sample(self, s_img_paths_all, s_label_paths_all): seed = random.randrange(0,1000) # s_length = len(s_img_paths) s_imgs_all, s_labels_all = [],[] for s_idx, s_img_paths in enumerate(s_img_paths_all): s_label_paths = s_label_paths_all[s_idx] imgs, labels = [],[] for i in range(len(s_img_paths)): img_path, label_path = s_img_paths[i], s_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) s_imgs = np.stack(imgs,axis=0) s_labels = np.stack(labels,axis=0) s_imgs_all.append(s_imgs) s_labels_all.append(s_labels) s_imgs = np.stack(s_imgs_all,axis=0) s_labels = np.stack(s_labels_all,axis=0) s_imgs = np.flip(s_imgs, 4).copy() s_labels = np.flip(s_labels, 4).copy() sample = { "s_x":totensor(s_imgs), "s_y":totensor(s_labels), #.long() # "s_length":s_length, # "q_length":q_length, "s_fname":s_img_paths_all, } return sample def random_flip_z(self, q, s): if random.random() < 0.5: q.reverse() s.reverse() return q,s def getitem_train(self): ## choose support and target idx_space = [i for i in range(self.valid_img_n)] # print(idx_space, self.n_shot) subj_idxs = random.sample(idx_space, self.n_shot) s_subj_idxs = subj_idxs[:self.n_shot] s_subj_idx = s_subj_idxs[0] fnames = self.img_lists[s_subj_idx] idx_start = random.randrange(0,len(fnames)-self.q_slice) idxs = [n for n in range(idx_start, idx_start+self.q_slice)] s_img_paths_all, s_label_paths_all = [],[] s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] s_fnames = self.img_lists[s_subj_idx] s_fnames_selected = [s_fnames[idx] for idx in idxs] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) return self.get_sample(s_img_paths_all, s_label_paths_all) def getitme_test(self, idx): s_subj_idx, idx_start = self.get_test_subj_idx(idx) s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] fnames = self.img_lists[s_subj_idx] idxs = [n for n in range(idx_start, idx_start+self.q_slice)] s_img_paths_all, s_label_paths_all = [],[] s_fnames_selected = [fnames[idx] for idx in idxs] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) return self.get_sample(s_img_paths_all, s_label_paths_all) def get_len_train(self): return self.length def get_len_test(self): return self.length # def get_val_subj_idx(self, idx): # for subj_idx,cnt in enumerate(self.q_cnts): # if idx < cnt: # return subj_idx, idx*self.q_slice # else: # idx -= cnt # # print("get_val_subj_idx function is not working.") # assert False def get_test_subj_idx(self, idx): # for subj_idx,cnt in enumerate(self.slice_cnts): for subj_idx,cnt in enumerate(self.q_cnts): if idx < cnt: # print(subj_idx, idx, self.q_cnts[subj_idx], len(self.img_lists[subj_idx])) return subj_idx, idx else: idx -= cnt print("get_test_subj_idx function is not working.") assert False def get_cnts(self): ## only for test loader return self.q_cnts # return self.slice_cnts def img_load(self, img_path, seed=0): img_arr = np.load(img_path) # print(img_arr) return img_arr def set_support_volume(self, s_img_paths, s_label_paths): ## set support img path and label path for validation and testing self.s_img_paths = [] self.s_label_paths = [] self.s_fnames_list = [] for i in range(len(s_img_paths)): s_fnames = os.listdir(s_img_paths[i]) s_fnames = [int(e.split(".")[0]) for e in s_fnames] s_fnames.sort() print(f'support img {i} path : {s_img_paths[i]} length : {len(s_fnames)}') self.s_img_paths.append(s_img_paths[i]) self.s_label_paths.append(s_label_paths[i]) self.s_fnames_list.append([f"{e}.npy" for e in s_fnames]) class Spleen_Base(Base_dataset): modal_i = 0 label_i = 1.0 class Spleen_train(Spleen_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Spleen_test(Spleen_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Liver_Base(Base_dataset): modal_i = 0 # only 1 modality label_i = 1.0 # use both 1 : cancer / 2 : liver class Liver_train(Liver_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Liver_test(Liver_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Tumor_Base(Base_dataset): modal_i = [0, 1, 2, 3] # 4 modalities label_i = 3.0 # 1 : edema / 2 : non enhancing tumor / 3 : enhancing tumour def img_load(self, img_path, seed=0): modal_idx = seed%len(self.modal_i) img_arr = np.load(img_path) return img_arr[modal_idx] # synchronize with query img and other support img class Tumor_train(Tumor_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Tumor_test(Tumor_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Prostate_Base(Base_dataset): modality_n = 2 modal_i = 0 label_i = 2.0 def img_load(self, img_path, seed=0): img_arr = np.load(img_path) return img_arr[self.modal_i] class Prostate_train(Prostate_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Prostate_test(Prostate_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Hippo_Base(Base_dataset): modal_i = 0 label_i = 1.0 # use both 1.0 and 2.0 class Hippo_train(Hippo_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Hippo_test(Hippo_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Lung_Base(Base_dataset): modal_i = 0 # only 1 modality label_i = 1.0 # use both 1 : cancer class Lung_train(Lung_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Lung_test(Lung_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class HepaticVessel_Base(Base_dataset): modality_n = 1 # modal_i = 0 label_i = 1.0 # 1 for vessel, 2 for tumour # use only vessel class HepaticVessel_train(HepaticVessel_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class HepaticVessel_test(HepaticVessel_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Heart_Base(Base_dataset): modality_n = 1 # modal_i = 0 label_i = 1.0 # 1 for left atrium class Heart_train(Heart_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Heart_test(Heart_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Pancreas_Base(Base_dataset): modality_n = 1 # only 1 modality # modal_i = 0 label_i = 1.0 # 1 for pancreas, 2 for cancer # use all of them class Pancreas_train(Pancreas_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Pancreas_test(Pancreas_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Colon_Base(Base_dataset): modality_n = 1 # only 1 modality # modal_i = 0 label_i = 1.0 # 1 for colon cancer primaries # use 1.0 class Colon_train(Colon_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Colon_test(Colon_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) if __name__ == "__main__": pass # main()
Python
3D
oopil/3D_medical_image_FSS
UNet_upperbound/dataloaders_medical/prostate.py
.py
11,390
299
import sys import glob import json import re from glob import glob from util.utils import * from dataloaders_medical.dataset import * from dataloaders_medical.dataset_decathlon import * from dataloaders_medical.dataset_CT_ORG import * import numpy as np class MetaSliceData_train(): def __init__(self, datasets, iter_n = 100): super().__init__() self.datasets = datasets self.dataset_n = len(datasets) self.iter_n =iter_n def __len__(self): return self.iter_n def __getitem__(self, idx): dataset = random.sample(self.datasets, 1)[0] return dataset.__getitem__(idx) def metadata(): info = { "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training", "trg_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d", # 144 setting "trg_dir2" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_2", # 144 setting "trg_dir3" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_denoise", # "trg_dir" : "/home/soopil/Desktop/Dataset/MICCAI2015challenge/Abdomen/RawData/Training_2d", # desktop setting # "Tasks" : [i for i in range(1,14)], "Tasks" : [i for i in range(1,17+1)], "Organs" : ["background", "spleen", #1 "right kidney", #2 "left kidney", #3 "gallbladder", #4 "esophagus", #5 "liver", #6 "stomach", #7 "aorta", #8 "inferior vana cava", #9 "portal vein & splenic vein", #10 "pancreas", #11 "right adrenal gland", #12 "left adrenal gland", #13 "bladder", #14 "uturus", #15 "rectum", #16 "small bowel", #17 ], } return info def meta_data(_config): def path_collect(idx, option='train'): img_paths = glob(f"{meta['trg_dir2']}/{idx}/{option}/img/*") label_paths = glob(f"{meta['trg_dir2']}/{idx}/{option}/label/*") return img_paths, label_paths def spliter(idx): tr_imgs, tr_labels = path_collect(idx, 'train') val_imgs, val_labels = path_collect(idx, 'valid') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels target_task = _config['target'] meta = metadata() print(f"target dir : {meta['trg_dir']}") tasks = meta['Tasks'] tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = spliter(target_task) s_idx = _config['s_idx'] if _config['is_lowerbound']: tr_imgs = tr_imgs[s_idx:s_idx+1] if _config["internal_train"]: tr_dataset, val_dataset, ts_dataset = TrainLoader(tr_imgs, tr_labels, _config), \ TestLoader(val_imgs, val_labels, _config), \ TestLoader(ts_imgs, ts_labels, _config) else: tr_dataset, val_dataset, ts_dataset = external_trainset(_config,target_task) if _config["internal_test"]: pass else: # _, _, ts_dataset = external_trainset(_config,target_task) ts_dataset = external_testset(_config,target_task) return tr_dataset, val_dataset, ts_dataset def external_testset(_config, target_task): def decathlon_spliter(idx): def path_collect(idx, option='train'): tasks = ["Task01_BrainTumour", "Task02_Heart", "Task03_Liver", "Task04_Hippocampus", "Task05_Prostate", "Task06_Lung", "Task07_Pancreas", "Task08_HepaticVessel", "Task09_Spleen", "Task10_Colon", "Task11_Davis" ] src_path='/user/home2/soopil/Datasets/Decathlon_2d' img_paths = glob(f"{src_path}/{tasks[idx - 1]}/{option}/img/*") label_paths = glob(f"{src_path}/{tasks[idx - 1]}/{option}/label/*") return img_paths, label_paths tr_imgs, tr_labels = path_collect(idx, 'train') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, ts_imgs, ts_labels def CT_ORG_spliter(idx): def path_collect(idx, option='train'): Organs = ["background", "Liver", # 1 "Bladder", # 2 "Lung", # 3 "Kidney", # 4 "Bone", # 5 "Brain", # 6 ], src_path="/user/home2/soopil/Datasets/CT_ORG/Training_2d_align" img_paths = glob(f"{src_path}/{idx}/{option}/img/*") label_paths = glob(f"{src_path}/{idx}/{option}/label/*") return img_paths, label_paths tr_imgs, tr_labels = path_collect(idx, 'train') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, ts_imgs, ts_labels external = _config["external_test"] print(f"external testset : {external}") if external == "decathlon": if target_task == 1: # spleen target_idx_decath = 9 tr_imgs, tr_labels, ts_imgs, ts_labels = decathlon_spliter(target_idx_decath) ts_dataset = Spleen_test(ts_imgs, ts_labels, _config) elif target_task == 6: target_idx_decath = 3 tr_imgs, tr_labels, ts_imgs, ts_labels = decathlon_spliter(target_idx_decath) ts_dataset = Liver_test(ts_imgs, ts_labels, _config) else: print("There isn't according organ in Decathlon dataset.") assert False print(f"target index in external dataset : {target_idx_decath}") elif external == "CT_ORG": if target_task == 3: # kidney target_idx_ctorg = 4 tr_imgs, tr_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) ts_dataset = TestLoader_CTORG(ts_imgs, ts_labels, _config) elif target_task == 6: # liver target_idx_ctorg = 1 tr_imgs, tr_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) ts_dataset = TestLoader_CTORG(ts_imgs, ts_labels, _config) elif target_task == 14: # bladder target_idx_ctorg = 2 tr_imgs, tr_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) ts_dataset = TestLoader_CTORG(ts_imgs, ts_labels, _config) else: print("There isn't according organ in CT_ORG dataset.") assert False print(f"target index in external dataset : {target_idx_ctorg}") else: print("configuration of external dataset is wrong") assert False return ts_dataset def external_trainset(_config, target_task): def decathlon_spliter(idx): def path_collect(idx, option='train'): tasks = ["Task01_BrainTumour", "Task02_Heart", "Task03_Liver", "Task04_Hippocampus", "Task05_Prostate", "Task06_Lung", "Task07_Pancreas", "Task08_HepaticVessel", "Task09_Spleen", "Task10_Colon", "Task11_Davis" ] src_path='/user/home2/soopil/Datasets/Decathlon_2d' img_paths = glob(f"{src_path}/{tasks[idx - 1]}/{option}/img/*") label_paths = glob(f"{src_path}/{tasks[idx - 1]}/{option}/label/*") return img_paths, label_paths tr_imgs, tr_labels = path_collect(idx, 'train') val_imgs, val_labels = path_collect(idx, 'valid') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels def CT_ORG_spliter(idx): def path_collect(idx, option='train'): Organs = ["background", "Liver", # 1 "Bladder", # 2 "Lung", # 3 "Kidney", # 4 "Bone", # 5 "Brain", # 6 ], src_path="/user/home2/soopil/Datasets/CT_ORG/Training_2d_align" img_paths = glob(f"{src_path}/{idx}/{option}/img/*") label_paths = glob(f"{src_path}/{idx}/{option}/label/*") return img_paths, label_paths tr_imgs, tr_labels = path_collect(idx, 'train') val_imgs, val_labels = path_collect(idx, 'valid') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels external = _config["external_train"] print(f"external testset : {external}") is_lowerbound = _config["is_lowerbound"] s_idx = _config['s_idx'] if external == "decathlon": if target_task == 1: # spleen target_idx_decath = 9 tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = decathlon_spliter(target_idx_decath) if is_lowerbound: tr_imgs = tr_imgs[s_idx:s_idx + 1] tr_dataset = Spleen_train(tr_imgs, tr_labels, _config) val_dataset = Spleen_test(val_imgs, val_labels, _config) ts_dataset = Spleen_test(ts_imgs, ts_labels, _config) elif target_task == 6: target_idx_decath = 3 tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = decathlon_spliter(target_idx_decath) if is_lowerbound: tr_imgs = tr_imgs[s_idx:s_idx + 1] tr_dataset = Liver_train(tr_imgs, tr_labels, _config) val_dataset = Liver_test(val_imgs, val_labels, _config) ts_dataset = Liver_test(ts_imgs, ts_labels, _config) else: print("There isn't according organ in Decathlon dataset.") assert False print(f"target index in external dataset : {target_idx_decath}") elif external == "CT_ORG": if target_task == 3: # kidney target_idx_ctorg = 4 tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) elif target_task == 6: # liver target_idx_ctorg = 1 tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) elif target_task == 14: # bladder target_idx_ctorg = 2 tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) else: print(f"There isn't according organ in CT_ORG dataset. {target_task}") assert False if is_lowerbound: tr_imgs = tr_imgs[s_idx:s_idx + 1] print(f"target index in external dataset : {target_idx_ctorg}") tr_dataset = TrainLoader_CTORG(tr_imgs, tr_labels, _config) val_dataset = TestLoader_CTORG(val_imgs, val_labels, _config) ts_dataset = TestLoader_CTORG(ts_imgs, ts_labels, _config) else: print(f"configuration of external dataset is wrong {external}") assert False return tr_dataset, val_dataset, ts_dataset if __name__=="__main__": pass
Python
3D
oopil/3D_medical_image_FSS
process/cervix_2d_3way.py
.py
8,805
219
import os import sys from glob import glob import json import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") sys.path.append("../dataloaders_medical") from PIL import Image import SimpleITK as sitk import numpy as np import random import shutil import cv2 from cv2 import resize import json import pdb from sklearn.model_selection import train_test_split def metadata(): info = { "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Cervix/RawData/Training", # "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_denoise", # "trg_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Cervix/RawData/Training_2d_3way", "trg_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Cervix/RawData/Training_2d_3way_re", } return info def read_sitk(path): itk_img = sitk.ReadImage(path) # print(path, itk_img.GetSpacing()) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def normalize(arr, type=0): # print(np.mean(arr*255.0), np.std(arr*255.0), np.amin(arr*255.0), np.amax(arr*255.0)) if type == 0: # min and max mini = np.amin(arr) arr -= mini maxi = np.amax(arr) arr_norm = arr/maxi elif type == 1: # stddev and mean mean = np.mean(arr) stddev = np.std(arr) arr_norm = (arr-mean)/stddev elif type == 2: # CT configuration arr_norm = (arr+1024)/4096.0 arr_norm = np.clip(arr_norm, 0, 1) print("normalize", np.amax(arr), np.amin(arr) ,"=>", np.amax(arr_norm), np.amin(arr_norm)) elif type == 3: # CT configuration + mean, stddev alignment arr_norm = (arr+1024)/4096.0 arr_norm = np.clip(arr_norm, 0, 1) arr_norm = normalize(arr_norm, type=1) print("normalize", np.amax(arr), np.amin(arr) ,"=>", np.amax(arr_norm), np.amin(arr_norm)) return arr_norm def check_OOI(shape, center, hsize): [x, y] = shape [cx, cy] = center [nx, ny] = center if x < cx + hsize: nx = x - hsize elif cx - hsize < 0: nx = hsize if y < cy + hsize: ny = y - hsize elif cy - hsize < 0: ny = hsize return [nx, ny] def try_mkdirs(path): try: os.makedirs(path) return True except: return False def save(dir_path, img_slice, label_slice, label, option, subj, pos, input_size): try_mkdirs(f"{dir_path}/{label+13}/{option}/img_orig/{subj}") try_mkdirs(f"{dir_path}/{label+13}/{option}/label_orig/{subj}") opath = f"{dir_path}/{label+13}/{option}/img_orig/{subj}/{pos}.npy" np.save(opath, img_slice) opath = f"{dir_path}/{label+13}/{option}/label_orig/{subj}/{pos}.npy" np.save(opath, label_slice) # print(img_slice.shape) img_slice = resize(img_slice, dsize=input_size, interpolation=cv2.INTER_AREA) # print(img_slice.shape) label_slice = resize(label_slice, dsize=input_size, interpolation=cv2.INTER_NEAREST) print(img_slice.shape, label_slice.shape, end="\r") try_mkdirs(f"{dir_path}/{label+13}/{option}/img/{subj}") try_mkdirs(f"{dir_path}/{label+13}/{option}/label/{subj}") opath = f"{dir_path}/{label+13}/{option}/img/{subj}/{pos}.npy" np.save(opath, img_slice) opath = f"{dir_path}/{label+13}/{option}/label/{subj}/{pos}.npy" np.save(opath, label_slice) def meta_data(): meta = metadata() print("start data preprocessing ...") print("source directory : ",meta['src_dir']) ## check label info subjs = os.listdir(f"{meta['src_dir']}/label") subjs = [e[5:] for e in subjs] # label_paths = glob(f"{meta['src_dir']}/label/*") # for i, label_path in enumerate(label_paths): # label_arr = read_sitk(label_path) # print(i, label_path, label_arr.shape, len(np.unique(label_arr)), np.unique(label_arr)) ## split subjects into train, valid, test # print(subjs) # subj_n = len(subjs) # subjs_train_whole, subjs_test = train_test_split(subjs, test_size = 0.33, random_state = 0) # subjs_train, subjs_valid = train_test_split(subjs_train_whole, test_size = 0.25, random_state = 0) # # subj_split = { # "train":subjs_train, # "valid":subjs_valid, # "test":subjs_test, # } # print(len(subjs), "=> ", len(subjs_train), len(subjs_valid), len(subjs_test)) # with open("MICCAI2015_subj_split.json", "w") as json_file: # json.dump(subj_split, json_file) with open("cervix_subj_split.json", "r") as json_file: subj_split = json.load(json_file) print(subj_split) subjs_train = subj_split["train"] subjs_valid = subj_split["valid"] subjs_test = subj_split["test"] ## preprocess def process(meta, subjs, option): ## original setting hsizes = [256, # 0 background 128 - 32, # 1 bladder 128 - 32, # 2 uterus 128 - 32, # 3 rectum 128 - 32, # 4 small bowel ] out_size = (256,256) # margin = 20 # marginal pixels margins = [0, # 0 background 40, # 1 bladder 40, # 2 uterus 40, # 3 rectum 40, # 4 small bowel ] margin_z = 5 # marginal pixels in z axis out_size = (256,256) for i, subj_fname in enumerate(subjs): subj = subj_fname.split(".")[0] img_path = f"{meta['src_dir']}/img/{subj_fname}-Image.nii.gz" label_path = f"{meta['src_dir']}/label/{subj_fname}-Mask.nii.gz" assert os.path.exists(img_path) assert os.path.exists(label_path) img_arr = read_sitk(img_path) img_arr = normalize(img_arr, type=2) #1 label_arr = read_sitk(label_path) labels_unique = np.unique(label_arr).astype(dtype=np.int) labels_unique = np.delete(labels_unique, np.argwhere(labels_unique == 0)) for label in labels_unique: hsize = hsizes[label] a_label_arr = (label_arr==label)*1.0 whole_pos = np.array(np.nonzero(a_label_arr)) [med_x, med_y, med_z] = np.mean(whole_pos, axis=1) med_x, med_y, med_z = int(med_x), int(med_y), int(med_z) img_arr_organ = img_arr[:, med_y - hsize:med_y + hsize, med_z - hsize:med_z + hsize] label_arr_organ = label_arr[:, med_y - hsize:med_y + hsize, med_z - hsize:med_z + hsize] ## [z,x,y] order minis = np.min(whole_pos, axis=1) maxis = np.max(whole_pos, axis=1) ## z - axial trg_dir = f"{meta['trg_dir']}_z" is_pass = False for pos in range(minis[0]-margin_z, maxis[0]+margin_z): try: img_slice_z = img_arr[pos, minis[1]-margin:maxis[1]+margin, minis[2]-margin: maxis[2]+margin] label_slice_z = a_label_arr[pos, minis[1]-margin:maxis[1]+margin, minis[2]-margin:maxis[2]+margin] save(trg_dir, img_slice_z, label_slice_z, label, option, subj, pos, (256,256)) except: is_pass = True pass if is_pass: print("pass.") ## x - coronal? trg_dir = f"{meta['trg_dir']}_x" for pos in range(minis[1]-margin, maxis[1]+margin): img_slice_x = img_arr[minis[0]-margin_z:maxis[0]+margin_z, pos, minis[2]-margin: maxis[2]+margin] label_slice_x = a_label_arr[minis[0]-margin_z:maxis[0]+margin_z, pos, minis[2]-margin: maxis[2]+margin] save(trg_dir, img_slice_x, label_slice_x, label, option, subj, pos, (256,128)) ## y - sagittal? trg_dir = f"{meta['trg_dir']}_y" for pos in range(minis[2]-margin, maxis[2]+margin): img_slice_y = img_arr[minis[0]-margin_z:maxis[0]+margin_z, minis[1]-margin: maxis[1]+margin, pos] label_slice_y = a_label_arr[minis[0]-margin_z:maxis[0]+margin_z, minis[1]-margin: maxis[1]+margin, pos] save(trg_dir, img_slice_y, label_slice_y, label, option, subj, pos, (256,128)) # print(img_slice_z.shape, img_slice_x.shape, img_slice_y.shape) print(f"{i}/{len(subjs)} {subj} {label} {img_slice_z.shape} {img_slice_x.shape} {img_slice_y.shape}", end='\n') print("processing is done.") process(meta, subjs_train, option="train") process(meta, subjs_valid, option="valid") process(meta, subjs_test, option="test") if __name__ == "__main__": meta_data()
Python
3D
oopil/3D_medical_image_FSS
process/abdomen_2d_3way.py
.py
9,308
236
import os import sys from glob import glob import json import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") sys.path.append("../dataloaders_medical") from PIL import Image import SimpleITK as sitk import numpy as np import random import shutil import cv2 from cv2 import resize import json import pdb from sklearn.model_selection import train_test_split def metadata(): info = { "src_dir" : "/home/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training", # "src_dir" : "/home/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_denoise", # "trg_dir" : "/home/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_3way", "trg_dir" : "/home/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_3way_re", } return info def read_sitk(path): itk_img = sitk.ReadImage(path) # print(path, itk_img.GetSpacing()) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def normalize(arr, type=0): # print(np.mean(arr*255.0), np.std(arr*255.0), np.amin(arr*255.0), np.amax(arr*255.0)) if type == 0: # min and max mini = np.amin(arr) arr -= mini maxi = np.amax(arr) arr_norm = arr/maxi elif type == 1: # stddev and mean mean = np.mean(arr) stddev = np.std(arr) arr_norm = (arr-mean)/stddev elif type == 2: # CT configuration arr_norm = (arr+1024)/4096.0 arr_norm = np.clip(arr_norm, 0, 1) print("normalize", np.amax(arr), np.amin(arr) ,"=>", np.amax(arr_norm), np.amin(arr_norm)) elif type == 3: # CT configuration + mean, stddev alignment arr_norm = (arr+1024)/4096.0 arr_norm = np.clip(arr_norm, 0, 1) arr_norm = normalize(arr_norm, type=1) print("normalize", np.amax(arr), np.amin(arr) ,"=>", np.amax(arr_norm), np.amin(arr_norm)) return arr_norm def check_OOI(shape, center, hsize): [x, y] = shape [cx, cy] = center [nx, ny] = center if x < cx + hsize: nx = x - hsize elif cx - hsize < 0: nx = hsize if y < cy + hsize: ny = y - hsize elif cy - hsize < 0: ny = hsize return [nx, ny] def try_mkdirs(path): try: os.makedirs(path) return True except: return False def save(dir_path, img_slice, label_slice, label, option, subj, pos, input_size): try_mkdirs(f"{dir_path}/{label}/{option}/img_orig/{subj}") try_mkdirs(f"{dir_path}/{label}/{option}/label_orig/{subj}") opath = f"{dir_path}/{label}/{option}/img_orig/{subj}/{pos}.npy" np.save(opath, img_slice) opath = f"{dir_path}/{label}/{option}/label_orig/{subj}/{pos}.npy" np.save(opath, label_slice) img_slice = resize(img_slice, dsize=input_size, interpolation=cv2.INTER_AREA) label_slice = resize(label_slice, dsize=input_size, interpolation=cv2.INTER_NEAREST) try_mkdirs(f"{dir_path}/{label}/{option}/img/{subj}") try_mkdirs(f"{dir_path}/{label}/{option}/label/{subj}") opath = f"{dir_path}/{label}/{option}/img/{subj}/{pos}.npy" np.save(opath, img_slice) opath = f"{dir_path}/{label}/{option}/label/{subj}/{pos}.npy" np.save(opath, label_slice) def meta_data(): meta = metadata() print("start data preprocessing ...") print("source directory : ",meta['src_dir']) ## check label info subjs = os.listdir(f"{meta['src_dir']}/label") subjs = [e[5:] for e in subjs] # label_paths = glob(f"{meta['src_dir']}/label/*") # for i, label_path in enumerate(label_paths): # label_arr = read_sitk(label_path) # print(i, label_path, label_arr.shape, len(np.unique(label_arr)), np.unique(label_arr)) ## split subjects into train, valid, test # print(subjs) # subj_n = len(subjs) # subjs_train_whole, subjs_test = train_test_split(subjs, test_size = 0.33, random_state = 0) # subjs_train, subjs_valid = train_test_split(subjs_train_whole, test_size = 0.25, random_state = 0) # # subj_split = { # "train":subjs_train, # "valid":subjs_valid, # "test":subjs_test, # } # print(len(subjs), "=> ", len(subjs_train), len(subjs_valid), len(subjs_test)) # with open("MICCAI2015_subj_split.json", "w") as json_file: # json.dump(subj_split, json_file) with open("MICCAI2015_subj_split.json", "r") as json_file: subj_split = json.load(json_file) print(subj_split) subjs_train = subj_split["train"] subjs_valid = subj_split["valid"] subjs_test = subj_split["test"] ## preprocess def process(meta, subjs, option): ## original setting hsizes = [256, # 0 background 128 - 32, # 1 spleen 128 - 32, # 2 right kidney 128 - 32, # 3 left kidney 128 - 64, # 4 gallbladder 128 - 64, # 5 esophagus 256 - 64, # 6 liver 128 + 32, # 7 stomach 128 - 32, # 8 aorta ? 128 - 32, # 9 inferior vana cava 128 - 0, # 10 por-tal vein & splenic vein, 128 + 32, # 11 pancreas 128 - 32, # 12 right adrenal gland 128 - 32, # 13 left adrenal gland ] margin = 20 # marginal pixels margins = [0, # 1-1 20, # 2-1 30, # 3-1 30, # 4-1 30, # 5-1 30, # 6-1 20, # 7-1 30, # 8-1 30, # 9-1 30, # 10-1 30, # 11-1 30, # 12-1 30, # 13-1 30, # 14-1 ] margin_z = 5 # marginal pixels in z axis out_size = (256,256) for i, subj_fname in enumerate(subjs): subj = subj_fname.split(".")[0] img_path = f"{meta['src_dir']}/img/img{subj_fname}" label_path = f"{meta['src_dir']}/label/label{subj_fname}" assert os.path.exists(img_path) assert os.path.exists(label_path) img_arr = read_sitk(img_path) img_arr = normalize(img_arr, type=2) #1 label_arr = read_sitk(label_path) labels_unique = np.unique(label_arr).astype(dtype=np.int) labels_unique = np.delete(labels_unique, np.argwhere(labels_unique == 0)) for label in labels_unique: margin = margins[label] hsize = hsizes[label] a_label_arr = (label_arr==label)*1.0 whole_pos = np.array(np.nonzero(a_label_arr)) [med_x, med_y, med_z] = np.mean(whole_pos, axis=1) med_x, med_y, med_z = int(med_x), int(med_y), int(med_z) img_arr_organ = img_arr[:, med_y - hsize:med_y + hsize, med_z - hsize:med_z + hsize] label_arr_organ = label_arr[:, med_y - hsize:med_y + hsize, med_z - hsize:med_z + hsize] ## [z,x,y] order minis = np.min(whole_pos, axis=1) maxis = np.max(whole_pos, axis=1) ## z - axial trg_dir = f"{meta['trg_dir']}_z" is_pass = False for pos in range(minis[0]-margin_z, maxis[0]+margin_z): try: img_slice_z = img_arr[pos, minis[1]-margin:maxis[1]+margin, minis[2]-margin: maxis[2]+margin] label_slice_z = a_label_arr[pos, minis[1]-margin:maxis[1]+margin, minis[2]-margin:maxis[2]+margin] save(trg_dir, img_slice_z, label_slice_z, label, option, subj, pos, (256,256)) except: is_pass = True pass if is_pass: print("pass.") ## x - coronal? trg_dir = f"{meta['trg_dir']}_x" for pos in range(minis[1]-margin, maxis[1]+margin): img_slice_x = img_arr[minis[0]-margin_z:maxis[0]+margin_z, pos, minis[2]-margin: maxis[2]+margin] label_slice_x = a_label_arr[minis[0]-margin_z:maxis[0]+margin_z, pos, minis[2]-margin: maxis[2]+margin] save(trg_dir, img_slice_x, label_slice_x, label, option, subj, pos, (256, 128)) ## y - sagittal? trg_dir = f"{meta['trg_dir']}_y" for pos in range(minis[2]-margin, maxis[2]+margin): img_slice_y = img_arr[minis[0]-margin_z:maxis[0]+margin_z, minis[1]-margin: maxis[1]+margin, pos] label_slice_y = a_label_arr[minis[0]-margin_z:maxis[0]+margin_z, minis[1]-margin: maxis[1]+margin, pos] save(trg_dir, img_slice_y, label_slice_y, label, option, subj, pos, (256, 128)) # print(img_slice_z.shape, img_slice_x.shape, img_slice_y.shape) print(f"{i}/{len(subjs)} {subj} {label} {img_slice_z.shape} {img_slice_x.shape} {img_slice_y.shape}", end='\n') print("processing is done.") process(meta, subjs_train, option="train") process(meta, subjs_valid, option="valid") process(meta, subjs_test, option="test") if __name__ == "__main__": meta_data()
Python
3D
oopil/3D_medical_image_FSS
process/reg_train_v2.py
.py
3,259
99
import os import sys from glob import glob import json import numpy as np from PIL import Image import random import shutil import cv2 from cv2 import resize import json from sklearn.model_selection import train_test_split import SimpleITK as sitk def metadata(): info = { "src_dir" : "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_2", # "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_denoise", "trg_dir" : "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_2_reg_train_v2", } return info def read_sitk(path): itk_img = sitk.ReadImage(path) # print(path, itk_img.GetSpacing()) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def try_mkdirs(path): try: os.makedirs(path) return True except: return False def handle_idx(q_idx, q_n, s_n): """ choose slices for support indices :return: supp_idxs """ q_ratio = (q_idx)/(q_n-1) s_idx = round((s_n-1)*q_ratio) return s_idx def meta_data(): meta = metadata() print("start data preprocessing ...") print("source directory : ",meta['src_dir']) trg_dir_name="Training_2d_2_reg_train_v2" print("target directory : ",trg_dir_name) ## preprocess n_sample_per_organ = 2 src_dir = meta['src_dir'] organs = [1,3,6,14] cnt = 0 for organ in organs: subjs = glob(f"{src_dir}/{organ}/train/img/*") idx_space = [i for i in range(len(subjs))] for idx in range(n_sample_per_organ): mov_subj_idx, fix_subj_idx = random.sample(idx_space, 2) # print(mov_subj_idx, fix_subj_idx) mov_subj_dir = subjs[mov_subj_idx] fix_subj_dir = subjs[fix_subj_idx] print(mov_subj_dir) print(fix_subj_dir) mov_files = os.listdir(mov_subj_dir) fix_files = os.listdir(fix_subj_dir) for mov_file in mov_files: # mov_file = random.sample(mov_files, 1)[0] mov_file_idx = mov_files.index(mov_file) fix_file_idx = handle_idx(mov_file_idx, len(mov_files), len(fix_files)) fix_file = fix_files[fix_file_idx] print(mov_file, len(mov_files), len(fix_files), mov_file_idx, fix_file_idx) mov_file_path = f"{mov_subj_dir}/{mov_file}" fix_file_path = f"{fix_subj_dir}/{fix_file}" # print(mov_file_path) # print(fix_file_path) mov_split = mov_file_path.split("/") fix_split = fix_file_path.split("/") mov_split[-6] = trg_dir_name trg_dir = "/".join(mov_split[:-5]) mov_out = f"{trg_dir}/{cnt}/mov.npy" fix_out = f"{trg_dir}/{cnt}/fix.npy" try_mkdirs(f"{trg_dir}/{cnt}") shutil.copyfile(mov_file_path, mov_out) shutil.copyfile(fix_file_path, fix_out) cnt += 1 print(f"organ : {organ}, {idx}/{n_sample_per_organ}", end='\n') print(f"total cnt : {cnt}") print() if __name__ == "__main__": meta_data()
Python
3D
oopil/3D_medical_image_FSS
process/reg_train.py
.py
3,126
99
import os import sys from glob import glob import json import numpy as np from PIL import Image import random import shutil import cv2 from cv2 import resize import json from sklearn.model_selection import train_test_split import SimpleITK as sitk def metadata(): info = { "src_dir" : "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_2_reg", # "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_denoise", "trg_dir" : "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_2_reg_train", } return info def read_sitk(path): itk_img = sitk.ReadImage(path) # print(path, itk_img.GetSpacing()) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def try_mkdirs(path): try: os.makedirs(path) return True except: return False def handle_idx(q_idx, q_n, s_n): """ choose slices for support indices :return: supp_idxs """ q_ratio = (q_idx)/(q_n-1) s_idx = round((s_n-1)*q_ratio) return s_idx def meta_data(): meta = metadata() print("start data preprocessing ...") print("source directory : ",meta['src_dir']) ## preprocess n_sample_per_organ = 50 src_dir = meta['src_dir'] organs = [1,3,6,14] organ = organs[0] subjs = glob(f"{src_dir}/{organ}/train/img/*") idx_space = [i for i in range(len(subjs))] cnt = 0 for organ in organs: for idx in range(n_sample_per_organ): mov_subj_idx, fix_subj_idx = random.sample(idx_space, 2) # print(mov_subj_idx, fix_subj_idx) mov_subj_dir = subjs[mov_subj_idx] fix_subj_dir = subjs[fix_subj_idx] mov_files = os.listdir(mov_subj_dir) mov_files.sort() fix_files = os.listdir(fix_subj_dir) fix_files.sort() mov_file = random.sample(mov_files, 1)[0] mov_file_idx = mov_files.index(mov_file) fix_file_idx = handle_idx(mov_file_idx, len(mov_files), len(fix_files)) fix_file = fix_files[fix_file_idx] # print(mov_files) # print(fix_files) # print(mov_file, len(mov_files), len(fix_files), mov_file_idx, fix_file_idx) mov_file_path = f"{mov_subj_dir}/{mov_file}" fix_file_path = f"{fix_subj_dir}/{fix_file}" # print(mov_file_path) # print(fix_file_path) mov_split = mov_file_path.split("/") fix_split = fix_file_path.split("/") mov_split[-6] = "Training_2d_2_reg_train" trg_dir = "/".join(mov_split[:-5]) # print(trg_dir) mov_out = f"{trg_dir}/{cnt}/mov.npy" fix_out = f"{trg_dir}/{cnt}/fix.npy" try_mkdirs(f"{trg_dir}/{cnt}") shutil.copyfile(mov_file_path, mov_out) shutil.copyfile(fix_file_path, fix_out) cnt += 1 print(f"organ : {organ}, {idx}/{n_sample_per_organ}", end='\r') print() if __name__ == "__main__": meta_data()
Python
3D
oopil/3D_medical_image_FSS
process/__init__.py
.py
0
0
null
Python
3D
oopil/3D_medical_image_FSS
process/reg_train_nocrop.py
.py
3,125
99
import os import sys from glob import glob import json import numpy as np from PIL import Image import random import shutil import cv2 from cv2 import resize import json from sklearn.model_selection import train_test_split import SimpleITK as sitk def metadata(): info = { "src_dir" : "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_nocrop", # "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_denoise", "trg_dir" : "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_nocrop_reg", } return info def read_sitk(path): itk_img = sitk.ReadImage(path) # print(path, itk_img.GetSpacing()) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def try_mkdirs(path): try: os.makedirs(path) return True except: return False def handle_idx(q_idx, q_n, s_n): """ choose slices for support indices :return: supp_idxs """ q_ratio = (q_idx)/(q_n-1) s_idx = round((s_n-1)*q_ratio) return s_idx def meta_data(): meta = metadata() print("start data preprocessing ...") print("source directory : ",meta['src_dir']) ## preprocess n_sample_per_organ = 10 src_dir = meta['src_dir'] organs = [1,3,6,14] organ = organs[0] subjs = glob(f"{src_dir}/{organ}/train/img/*") idx_space = [i for i in range(len(subjs))] cnt = 0 for organ in organs: for idx in range(n_sample_per_organ): mov_subj_idx, fix_subj_idx = random.sample(idx_space, 2) # print(mov_subj_idx, fix_subj_idx) mov_subj_dir = subjs[mov_subj_idx] fix_subj_dir = subjs[fix_subj_idx] mov_files = os.listdir(mov_subj_dir) mov_files.sort() fix_files = os.listdir(fix_subj_dir) fix_files.sort() mov_file = random.sample(mov_files, 1)[0] mov_file_idx = mov_files.index(mov_file) fix_file_idx = handle_idx(mov_file_idx, len(mov_files), len(fix_files)) fix_file = fix_files[fix_file_idx] # print(mov_files) # print(fix_files) # print(mov_file, len(mov_files), len(fix_files), mov_file_idx, fix_file_idx) mov_file_path = f"{mov_subj_dir}/{mov_file}" fix_file_path = f"{fix_subj_dir}/{fix_file}" # print(mov_file_path) # print(fix_file_path) mov_split = mov_file_path.split("/") fix_split = fix_file_path.split("/") mov_split[-6] = "Training_2d_nocrop_reg" trg_dir = "/".join(mov_split[:-5]) # print(trg_dir) mov_out = f"{trg_dir}/{cnt}/mov.npy" fix_out = f"{trg_dir}/{cnt}/fix.npy" try_mkdirs(f"{trg_dir}/{cnt}") shutil.copyfile(mov_file_path, mov_out) shutil.copyfile(fix_file_path, fix_out) cnt += 1 print(f"organ : {organ}, {idx}/{n_sample_per_organ}", end='\r') print() if __name__ == "__main__": meta_data()
Python
3D
oopil/3D_medical_image_FSS
process/cervix_2d.py
.py
6,127
170
import os import sys from glob import glob import json import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") sys.path.append("../dataloaders_medical") from PIL import Image import SimpleITK as sitk import numpy as np import random import shutil import cv2 from cv2 import resize import json from sklearn.model_selection import train_test_split def metadata(): info = { "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Cervix/RawData/Training", "trg_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Cervix/RawData/Training_2d", "trg_dir4" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_nocrop", } return info def read_sitk(path): itk_img = sitk.ReadImage(path) # print(path, itk_img.GetSpacing()) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def normalize(arr, type=0): # print(np.mean(arr*255.0), np.std(arr*255.0), np.amin(arr*255.0), np.amax(arr*255.0)) if type == 0: # min and max mini = np.amin(arr) arr -= mini maxi = np.amax(arr) arr_norm = arr/maxi elif type == 1: # stddev and mean mean = np.mean(arr) stddev = np.std(arr) arr_norm = (arr-mean)/stddev elif type == 2: # CT configuration arr_norm = (arr+1024)/4096.0 arr_norm = np.clip(arr_norm, 0, 1) print("normalize", np.amax(arr), np.amin(arr) ,"=>", np.amax(arr_norm), np.amin(arr_norm)) return arr_norm def check_OOI(shape, center, hsize): [x, y] = shape [cx, cy] = center [nx, ny] = center if x < cx + hsize: nx = x - hsize elif cx - hsize < 0: nx = hsize if y < cy + hsize: ny = y - hsize elif cy - hsize < 0: ny = hsize return [nx, ny] def try_mkdirs(path): try: os.makedirs(path) return True except: return False def meta_data(): meta = metadata() print("start data preprocessing ...") print("source directory : ",meta['src_dir']) ## check label info subjs = os.listdir(f"{meta['src_dir']}/label") subjs = [e[:7] for e in subjs] # label_paths = glob(f"{meta['src_dir']}/label/*") # for i, label_path in enumerate(label_paths): # label_arr = read_sitk(label_path) # print(i, label_path, label_arr.shape, len(np.unique(label_arr)), np.unique(label_arr)) ## split subjects into train, valid, test print(subjs) subj_n = len(subjs) subjs_train_whole, subjs_test = train_test_split(subjs, test_size = 0.33, random_state = 0) subjs_train, subjs_valid = train_test_split(subjs_train_whole, test_size = 0.25, random_state = 0) subj_split = { "train":subjs_train, "valid":subjs_valid, "test":subjs_test, } print(len(subjs), "=> ", len(subjs_train), len(subjs_valid), len(subjs_test)) with open("cervix_subj_split.json", "w") as json_file: json.dump(subj_split, json_file) ## preprocess def process(meta, subjs, option): # hsize = 256 hsizes = [256, # 0 background 128 - 32, # 1 bladder 128 - 32, # 2 uterus 128 - 32, # 3 rectum 128 - 32, # 4 small bowel ] out_size = (256,256) for i, subj_fname in enumerate(subjs): subj = subj_fname.split(".")[0] img_path = f"{meta['src_dir']}/img/{subj_fname}-Image.nii.gz" label_path = f"{meta['src_dir']}/label/{subj_fname}-Mask.nii.gz" assert os.path.exists(img_path) assert os.path.exists(label_path) img_arr = read_sitk(img_path) img_arr = normalize(img_arr, type=2) #1 label_arr = read_sitk(label_path) labels_unique = np.unique(label_arr).astype(dtype=np.int) labels_unique = np.delete(labels_unique, np.argwhere(labels_unique == 0)) for label in labels_unique: hsize = hsizes[label] a_label_arr = (label_arr==label)*1.0 cnt = np.sum(a_label_arr, axis=(1, 2)) nonzero_pos = list(np.nonzero(cnt)[0]) whole_pos = np.array(np.nonzero(a_label_arr)) x, y, z = img_arr.shape [med_x, med_y, med_z] = np.mean(whole_pos, axis=1) med_x, med_y, med_z = int(med_x), int(med_y), int(med_z) is_crop = False # if np.amax([y, z]) > hsize*2: # is_crop = True [med_y, med_z] = check_OOI([y,z], [med_y, med_z], hsize) for pos in nonzero_pos: if is_crop: img_slice = img_arr[pos, med_y-hsize:med_y+hsize, med_z-hsize:med_z+hsize] label_slice = a_label_arr[pos, med_y-hsize:med_y+hsize, med_z-hsize:med_z+hsize] else: img_slice = img_arr[pos] label_slice = a_label_arr[pos] img_slice = resize(img_slice, dsize=out_size, interpolation=cv2.INTER_AREA) label_slice = resize(label_slice, dsize=out_size, interpolation=cv2.INTER_NEAREST) try_mkdirs(f"{meta['trg_dir4']}/{label+13}/{option}/img/{subj}") try_mkdirs(f"{meta['trg_dir4']}/{label+13}/{option}/label/{subj}") opath = f"{meta['trg_dir4']}/{label+13}/{option}/img/{subj}/{pos}.npy" np.save(opath, img_slice) opath = f"{meta['trg_dir4']}/{label+13}/{option}/label/{subj}/{pos}.npy" np.save(opath, label_slice) print(f"label {label}/{len(labels_unique)} {is_crop}", end="\r") print(f"{i}/{len(subjs)} {subj} {img_arr.shape} {img_slice.shape} {is_crop} {[med_y, med_z]}", end='\n') print("processing is done.") process(meta, subjs_train, option="train") process(meta, subjs_valid, option="valid") process(meta, subjs_test, option="test") if __name__ == "__main__": meta_data()
Python
3D
oopil/3D_medical_image_FSS
process/af_reg.py
.py
5,941
165
import sys import pdb import os import SimpleITK as sitk import numpy as np from skimage.io import imsave from glob import glob import psutil p = psutil.Process(os.getpid()) # p.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS) # for Windows p.nice(19) # for Linux def make_dir(path): if not os.path.exists(path): os.makedirs(path, exist_ok=True) return path cwd = os.path.dirname(os.path.abspath(__file__)) main_name = 'Affine_#1' data_path = cwd + '/data' result_img_path = make_dir(cwd + '/result/' + main_name+'-imgs') result_Tx_path = make_dir(cwd + '/result/' + main_name+'-Tx') def command_iteration(method) : print("{0:3} = {1:10.5f}".format(method.GetOptimizerIteration(), method.GetMetricValue())) #for Non-Rigid Body Registration def B_SPLINE(img1, img2, loss='MSE'): fixed = sitk.GetImageFromArray(img2) moving = sitk.GetImageFromArray(img1) transformDomainMeshSize=[8]*moving.GetDimension() tx = sitk.BSplineTransformInitializer(fixed, transformDomainMeshSize, order=3) R = sitk.ImageRegistrationMethod() if loss == 'MSE': R.SetMetricAsMeanSquares() elif loss == 'NCC': R.SetMetricAsCorrelation() elif loss == 'MI': R.SetMetricAsMattesMutualInformation() R.SetOptimizerAsLBFGSB(gradientConvergenceTolerance=1e-5, numberOfIterations=500, maximumNumberOfCorrections=5, maximumNumberOfFunctionEvaluations=1000, costFunctionConvergenceFactor=1e+7, # lowerBound=0.1, upperBound=100 ) R.SetInitialTransform(tx, True) R.SetInterpolator(sitk.sitkLinear) outTx = R.Execute(fixed, moving) print("-------") print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription())) print(" Iteration: {0}".format(R.GetOptimizerIteration())) print(" Metric value: {0}".format(R.GetMetricValue())) resampler = sitk.ResampleImageFilter() resampler.SetReferenceImage(fixed) resampler.SetInterpolator(sitk.sitkLinear) resampler.SetDefaultPixelValue(0) resampler.SetTransform(outTx) return resampler, outTx #for Rigid Body Registration def AFFINE(img1, img2, loss='MSE'): fixed = sitk.GetImageFromArray(img2) moving = sitk.GetImageFromArray(img1) R = sitk.ImageRegistrationMethod() if loss == 'MSE': R.SetMetricAsMeanSquares() elif loss == 'NCC': R.SetMetricAsCorrelation() elif loss == 'MI': R.SetMetricAsMattesMutualInformation() R.SetOptimizerAsRegularStepGradientDescent(learningRate=1e-2, minStep=1e-4, numberOfIterations=1500, gradientMagnitudeTolerance=1e-8) R.SetInitialTransform(sitk.AffineTransform(fixed.GetDimension())) R.SetInterpolator(sitk.sitkLinear) outTx = R.Execute(fixed, moving) print("-------") print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription())) print(" Iteration: {0}".format(R.GetOptimizerIteration())) print(" Metric value: {0}".format(R.GetMetricValue())) resampler = sitk.ResampleImageFilter() resampler.SetReferenceImage(fixed) resampler.SetInterpolator(sitk.sitkLinear) resampler.SetDefaultPixelValue(0) resampler.SetTransform(outTx) return resampler, outTx def run_resampler(resampler, img): return np.array(sitk.GetArrayFromImage(resampler.Execute(sitk.GetImageFromArray(img.astype(float))))) def rescale_0to1(img): img = img.astype(float) if np.max(img) > 2.0: img = img / 255. return img def float2int(x): return (x*255).astype(np.uint8) def read_data(p = data_path): src_dir = "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_2_reg_train_v2" subjs = glob(f"{src_dir}/*") # subjs.sort() mov_set = [f"{e}/mov.npy" for e in subjs] fix_set = [f"{e}/fix.npy" for e in subjs] name_set = [e.split("/")[-1] for e in subjs] return name_set, mov_set, fix_set if __name__ == '__main__': print('+--='*30) data_path = "" name_set, mov_set, fix_set = read_data(data_path) result_img_path = "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_2_reg_train_nonrigid" result_Tx_path = "/media/NAS/nas_187/soopil/data/MICCAI2015challenge/Abdomen/RawData/Training_2d_2_reg_train_nonrigid_Tx" make_dir(result_img_path) make_dir(result_Tx_path) for i in range(len(name_set)): moving = mov_set[i] fixed = fix_set[i] moving = np.load(moving) fixed = np.load(fixed) moving = rescale_0to1(moving) fixed = rescale_0to1(fixed) #for Rigid Body Registration # resampler, outTx = AFFINE(moving.astype(float), fixed.astype(float), loss = 'MSE')# loss = MSE / MI / NCC #for Non-Rigid Body Registration resampler, outTx = B_SPLINE(moving.astype(float), fixed.astype(float), loss = 'MSE')# loss = MSE / MI / NCC warp = run_resampler(resampler, moving) warp = rescale_0to1(warp) mov_fix = np.clip(np.stack([moving, fixed, moving], axis=2), 0, 1) warp_fix = np.clip(np.stack([warp, fixed, warp], axis=2), 0, 1) imsave(result_img_path + '/' + name_set[i] + '_mov.png', float2int(moving)) imsave(result_img_path + '/' + name_set[i] + '_fix.png', float2int(fixed)) imsave(result_img_path + '/' + name_set[i] + '_mov_fix.png', float2int(mov_fix)) imsave(result_img_path + '/' + name_set[i] + '_warp_fix.png', float2int(warp_fix)) imsave(result_img_path + '/' + name_set[i] + '_warp.png', float2int(warp)) sitk.WriteTransform(outTx, result_Tx_path + '/' + name_set[i]+'.txt') print(name_set[i])
Python
3D
oopil/3D_medical_image_FSS
process/abdomen_2d.py
.py
7,123
186
import os import sys from glob import glob import json import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") sys.path.append("../dataloaders_medical") from PIL import Image import SimpleITK as sitk import numpy as np import random import shutil import cv2 from cv2 import resize import json from sklearn.model_selection import train_test_split def metadata(): info = { "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training", # "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_denoise", "trg_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d", "trg_dir2" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_2", "trg_dir3" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_denoise", "trg_dir4" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_nocrop", } return info def read_sitk(path): itk_img = sitk.ReadImage(path) # print(path, itk_img.GetSpacing()) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def normalize(arr, type=0): # print(np.mean(arr*255.0), np.std(arr*255.0), np.amin(arr*255.0), np.amax(arr*255.0)) if type == 0: # min and max mini = np.amin(arr) arr -= mini maxi = np.amax(arr) arr_norm = arr/maxi elif type == 1: # stddev and mean mean = np.mean(arr) stddev = np.std(arr) arr_norm = (arr-mean)/stddev elif type == 2: # CT configuration arr_norm = (arr+1024)/4096.0 arr_norm = np.clip(arr_norm, 0, 1) print("normalize", np.amax(arr), np.amin(arr) ,"=>", np.amax(arr_norm), np.amin(arr_norm)) elif type == 3: # CT configuration + mean, stddev alignment arr_norm = (arr+1024)/4096.0 arr_norm = np.clip(arr_norm, 0, 1) arr_norm = normalize(arr_norm, type=1) print("normalize", np.amax(arr), np.amin(arr) ,"=>", np.amax(arr_norm), np.amin(arr_norm)) return arr_norm def check_OOI(shape, center, hsize): [x, y] = shape [cx, cy] = center [nx, ny] = center if x < cx + hsize: nx = x - hsize elif cx - hsize < 0: nx = hsize if y < cy + hsize: ny = y - hsize elif cy - hsize < 0: ny = hsize return [nx, ny] def try_mkdirs(path): try: os.makedirs(path) return True except: return False def meta_data(): meta = metadata() print("start data preprocessing ...") print("source directory : ",meta['src_dir']) ## check label info subjs = os.listdir(f"{meta['src_dir']}/label") subjs = [e[5:] for e in subjs] # label_paths = glob(f"{meta['src_dir']}/label/*") # for i, label_path in enumerate(label_paths): # label_arr = read_sitk(label_path) # print(i, label_path, label_arr.shape, len(np.unique(label_arr)), np.unique(label_arr)) ## split subjects into train, valid, test print(subjs) subj_n = len(subjs) subjs_train_whole, subjs_test = train_test_split(subjs, test_size = 0.33, random_state = 0) subjs_train, subjs_valid = train_test_split(subjs_train_whole, test_size = 0.25, random_state = 0) subj_split = { "train":subjs_train, "valid":subjs_valid, "test":subjs_test, } print(len(subjs), "=> ", len(subjs_train), len(subjs_valid), len(subjs_test)) with open("MICCAI2015_subj_split.json", "w") as json_file: json.dump(subj_split, json_file) ## preprocess def process(meta, subjs, option): # hsize = 256 hsizes = [256, # 0 background 128 - 32, # 1 spleen 128 - 32, # 2 right kidney 128 - 32, # 3 left kidney 128 - 64, # 4 gallbladder 128 - 64, # 5 esophagus 256 - 64, # 6 liver 128 + 32, # 7 stomach 128 - 32, # 8 aorta ? 128 - 32, # 9 inferior vana cava 128 - 0, # 10 por-tal vein & splenic vein, 128 + 32, # 11 pancreas 128 - 32, # 12 right adrenal gland 128 - 32, # 13 left adrenal gland ] out_size = (256,256) for i, subj_fname in enumerate(subjs): subj = subj_fname.split(".")[0] img_path = f"{meta['src_dir']}/img/img{subj_fname}" label_path = f"{meta['src_dir']}/label/label{subj_fname}" assert os.path.exists(img_path) assert os.path.exists(label_path) img_arr = read_sitk(img_path) img_arr = normalize(img_arr, type=2) #1 label_arr = read_sitk(label_path) labels_unique = np.unique(label_arr).astype(dtype=np.int) labels_unique = np.delete(labels_unique, np.argwhere(labels_unique == 0)) for label in labels_unique: hsize = hsizes[label] a_label_arr = (label_arr==label)*1.0 cnt = np.sum(a_label_arr, axis=(1, 2)) nonzero_pos = list(np.nonzero(cnt)[0]) whole_pos = np.array(np.nonzero(a_label_arr)) x, y, z = img_arr.shape [med_x, med_y, med_z] = np.mean(whole_pos, axis=1) med_x, med_y, med_z = int(med_x), int(med_y), int(med_z) is_crop = False if np.amax([y, z]) > hsize*2: is_crop = True [med_y, med_z] = check_OOI([y,z], [med_y, med_z], hsize) for pos in nonzero_pos: if is_crop: img_slice = img_arr[pos, med_y-hsize:med_y+hsize, med_z-hsize:med_z+hsize] label_slice = a_label_arr[pos, med_y-hsize:med_y+hsize, med_z-hsize:med_z+hsize] else: img_slice = img_arr[pos] label_slice = a_label_arr[pos] img_slice = resize(img_slice, dsize=out_size, interpolation=cv2.INTER_AREA) label_slice = resize(label_slice, dsize=out_size, interpolation=cv2.INTER_NEAREST) try_mkdirs(f"{meta['trg_dir4']}/{label}/{option}/img/{subj}") try_mkdirs(f"{meta['trg_dir4']}/{label}/{option}/label/{subj}") opath = f"{meta['trg_dir4']}/{label}/{option}/img/{subj}/{pos}.npy" np.save(opath, img_slice) opath = f"{meta['trg_dir4']}/{label}/{option}/label/{subj}/{pos}.npy" np.save(opath, label_slice) print(f"label {label}/{len(labels_unique)} {is_crop}", end="\r") print(f"{i}/{len(subjs)} {subj} {img_arr.shape} {img_slice.shape} {is_crop} {[med_y, med_z]}", end='\n') print("processing is done.") process(meta, subjs_train, option="train") process(meta, subjs_valid, option="valid") process(meta, subjs_test, option="test") if __name__ == "__main__": meta_data()
Python
3D
oopil/3D_medical_image_FSS
process/separate_label.py
.py
1,835
59
import os import sys from glob import glob import json import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") sys.path.append("../dataloaders_medical") import SimpleITK as sitk import numpy as np from skimage.segmentation import slic def read_sitk(path): itk_img = sitk.ReadImage(path) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float64) return arr, itk_img def try_mkdirs(path): try: os.makedirs(path) return True except: return False def save_sitk(arr, itk_ref, opath): sitk_oimg = sitk.GetImageFromArray(arr) sitk_oimg.CopyInformation(itk_ref) sitk.WriteImage(sitk_oimg, opath) def main(): # src_path = '/home/soopil/Desktop/Dataset/MICCAI2015challenge/Abdomen/RawData/Training/label' src_path = '/home/soopil/Desktop/Dataset/MICCAI2015challenge/Cervix/RawData/Training/label' # src_path = '/home/soopil/Desktop/Dataset/CT_ORG/Training/label' src_parts = src_path.split('/') trg_path = '/'.join(src_parts[:-2]) trg_path = os.path.join(trg_path, 'separate_label') try_mkdirs(trg_path) print(f"src_path : {src_path}") print(f"trg_path : {trg_path}") fnames = os.listdir(src_path) fnames.sort() for fname in reversed(fnames): print(fname) fpath = os.path.join(src_path, fname) fn = fname.split(".")[0] arr_orig, itk = read_sitk(fpath) ## dtype = np.int64 labels = list(np.unique(arr_orig)) labels.remove(0) for label in labels: fname = fn + f"_{str(int(label))}"+".nii.gz" opath = os.path.join(trg_path, fname) arr = (arr_orig==label)*(label+13)*1.0 print(label, type(label), np.unique(arr)) save_sitk(arr, itk, opath) if __name__ == "__main__": main()
Python
3D
oopil/3D_medical_image_FSS
process/figure_kidney.py
.py
1,802
64
import os import sys from glob import glob import json import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") sys.path.append("../dataloaders_medical") import SimpleITK as sitk import numpy as np from skimage.segmentation import slic def read_sitk(path): itk_img = sitk.ReadImage(path) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float64) return arr, itk_img def normalize(arr, type=0): # print(np.mean(arr*255.0), np.std(arr*255.0), np.amin(arr*255.0), np.amax(arr*255.0)) if type == 0: # min and max mini = np.amin(arr) arr -= mini maxi = np.amax(arr) arr_norm = arr/maxi elif type == 1: # stddev and mean mean = np.mean(arr) stddev = np.std(arr) arr_norm = (arr-mean)/stddev return arr_norm def try_mkdirs(path): try: os.makedirs(path) return True except: return False def save_sitk(arr, itk_ref, opath): sitk_oimg = sitk.GetImageFromArray(arr) sitk_oimg.CopyInformation(itk_ref) sitk.WriteImage(sitk_oimg, opath) def main(): src_path = '/home/soopil/Desktop/Dataset/MICCAI2015challenge/Abdomen/RawData/Training/label' # src_path = '/home/soopil/Desktop/Dataset/CT_ORG/Training/label' src_parts = src_path.split('/') trg_path = '/'.join(src_parts[:-2]) trg_path = os.path.join(trg_path, 'kidney_only') try_mkdirs(trg_path) print(f"src_path : {src_path}") print(f"trg_path : {trg_path}") fnames = os.listdir(src_path) fnames.sort() for fname in fnames: print(fname) fpath = os.path.join(src_path, fname) opath = os.path.join(trg_path, fname) arr, itk = read_sitk(fpath) ## dtype = np.int64 arr = (arr == 3) *1.0 save_sitk(arr, itk, opath) if __name__ == "__main__": main()
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/train_multishot.py
.py
6,585
168
"""Training Script""" import os import shutil import numpy as np import pdb import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim from torch.utils.data import DataLoader from torch.optim.lr_scheduler import MultiStepLR import torch.backends.cudnn as cudnn from torchvision.utils import make_grid from tensorboardX import SummaryWriter from config import ex from util.utils import set_seed, CLASS_LABELS, date from dataloaders_medical.prostate import * # from models.fewshot import FewShotSeg from settings import Settings import few_shot_segmentor as fs from torch.optim import lr_scheduler from nn_common_modules import losses def overlay_color(img, mask, label, scale=50): """ :param img: [1, 256, 256] :param mask: [1, 256, 256] :param label: [1, 256, 256] :return: """ # pdb.set_trace() scale = np.mean(img.cpu().numpy()) mask = mask[0] label = label[0] zeros = torch.zeros_like(mask) zeros = [zeros for _ in range(3)] zeros[0] = mask mask = torch.stack(zeros,dim=0) zeros[1] = label label = torch.stack(zeros,dim=0) img_3ch = torch.cat([img,img,img],dim=0) masked = img_3ch+mask.float()*scale+label.float()*scale return [masked] @ex.automain def main(_run, _config, _log): settings = Settings() common_params, data_params, net_params, train_params, eval_params = settings['COMMON'], settings['DATA'], settings[ 'NETWORK'], settings['TRAINING'], settings['EVAL'] if _run.observers: os.makedirs(f'{_run.observers[0].dir}/snapshots', exist_ok=True) for source_file, _ in _run.experiment_info['sources']: os.makedirs(os.path.dirname(f'{_run.observers[0].dir}/source/{source_file}'), exist_ok=True) _run.observers[0].save_file(source_file, f'source/{source_file}') shutil.rmtree(f'{_run.observers[0].basedir}/_sources') set_seed(_config['seed']) cudnn.enabled = True cudnn.benchmark = True torch.cuda.set_device(device=_config['gpu_id']) torch.set_num_threads(1) _log.info('###### Load data ######') data_name = _config['dataset'] if data_name == 'BCV': make_data = meta_data else: print(f"data name : {data_name}") raise ValueError('Wrong config for dataset!') tr_dataset, val_dataset, ts_dataset = make_data(_config) trainloader = DataLoader( dataset=tr_dataset, batch_size=_config['batch_size'], shuffle=True, num_workers=_config['n_work'], pin_memory=False, #True load data while training gpu drop_last=True ) _log.info('###### Create model ######') model = fs.FewShotSegmentorDoubleSDnet(net_params).cuda() model.train() _log.info('###### Set optimizer ######') optim = torch.optim.Adam optim_args = {"lr": train_params['learning_rate'], "weight_decay": train_params['optim_weight_decay'],} # "momentum": train_params['momentum']} optim_c = optim(list(model.conditioner.parameters()), **optim_args) optim_s = optim(list(model.segmentor.parameters()), **optim_args) scheduler_s = lr_scheduler.StepLR(optim_s, step_size=100, gamma=0.1) scheduler_c = lr_scheduler.StepLR(optim_c, step_size=100, gamma=0.1) criterion = losses.DiceLoss() if _config['record']: ## tensorboard visualization _log.info('###### define tensorboard writer #####') _log.info(f'##### board/train_{_config["board"]}_{date()}') writer = SummaryWriter(f'board/train_{_config["board"]}_{date()}') iter_print = _config["iter_print"] iter_n_train = len(trainloader) _log.info('###### Training ######') for i_epoch in range(_config['n_steps']): epoch_loss = 0 for i_iter, sample_batched in enumerate(trainloader): # Prepare input s_x = sample_batched['s_x'].cuda() # [B, Support, slice_num=1, 1, 256, 256] X = s_x.squeeze(2) # [B, Support, 1, 256, 256] s_y = sample_batched['s_y'].cuda() # [B, Support, slice_num, 1, 256, 256] Y = s_y.squeeze(2) # [B, Support, 1, 256, 256] Y = Y.squeeze(2) # [B, Support, 256, 256] q_x = sample_batched['q_x'].cuda() # [B, slice_num, 1, 256, 256] query_input = q_x.squeeze(1) # [B, 1, 256, 256] q_y = sample_batched['q_y'].cuda() # [B, slice_num, 1, 256, 256] y2 = q_y.squeeze(1) # [B, 1, 256, 256] y2 = y2.squeeze(1) # [B, 256, 256] y2 = y2.type(torch.LongTensor).cuda() entire_weights = [] for shot_id in range(_config["n_shot"]): input1 = X[:, shot_id, ...] # use 1 shot at first y1 = Y[:, shot_id, ...] # use 1 shot at first condition_input = torch.cat((input1, y1.unsqueeze(1)), dim=1) weights = model.conditioner(condition_input) # 2, 10, [B, channel=1, w, h] entire_weights.append(weights) # pdb.set_trace() avg_weights=[[],[None, None, None, None]] for i in range(9): weight_cat = torch.cat([weights[0][i] for weights in entire_weights],dim=1) avg_weight = torch.mean(weight_cat,dim=1,keepdim=True) avg_weights[0].append(avg_weight) avg_weights[0].append(None) output = model.segmentor(query_input, avg_weights) loss = criterion(F.softmax(output, dim=1), y2) optim_s.zero_grad() optim_c.zero_grad() loss.backward() optim_s.step() optim_c.step() epoch_loss += loss if iter_print: print(f"train, iter:{i_iter}/{iter_n_train}, iter_loss:{loss}", end='\r') scheduler_c.step() scheduler_s.step() print(f'step {i_epoch+1}: loss: {epoch_loss} ') if _config['record']: batch_i = 0 frames = [] query_pred = output.argmax(dim=1) query_pred = query_pred.unsqueeze(1) frames += overlay_color(q_x[batch_i,0], query_pred[batch_i].float(), q_y[batch_i,0]) # frames += overlay_color(s_xi[batch_i], blank, s_yi[batch_i], scale=_config['scale']) visual = make_grid(frames, normalize=True, nrow=2) writer.add_image("train/visual", visual, i_epoch) save_fname = f'{_run.observers[0].dir}/snapshots/last.pth' torch.save(model.state_dict(),save_fname)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/settings.py
.py
747
29
import ast import configparser from collections.abc import Mapping class Settings(Mapping): def __init__(self, setting_file='settings.ini'): config = configparser.ConfigParser() config.read(setting_file) self.settings_dict = _parse_values(config) def __getitem__(self, key): return self.settings_dict[key] def __len__(self): return len(self.settings_dict) def __iter__(self): return self.settings_dict.items() def _parse_values(config): config_parsed = {} for section in config.sections(): config_parsed[section] = {} for key, value in config[section].items(): config_parsed[section][key] = ast.literal_eval(value) return config_parsed
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/test_multishot.py
.py
7,443
199
"""Evaluation Script""" import os import shutil import pdb import tqdm import numpy as np import torch import torch.optim import torch.nn as nn from torch.utils.data import DataLoader import torch.backends.cudnn as cudnn from torchvision.utils import make_grid from util.utils import set_seed, CLASS_LABELS, get_bbox, date from config import ex from tensorboardX import SummaryWriter from dataloaders_medical.prostate import * from settings import Settings import few_shot_segmentor as fs def overlay_color(img, mask, label, scale=50): """ :param img: [1, 256, 256] :param mask: [1, 256, 256] :param label: [1, 256, 256] :return: """ # pdb.set_trace() scale = np.mean(img.cpu().numpy()) mask = mask[0] label = label[0] zeros = torch.zeros_like(mask) zeros = [zeros for _ in range(3)] zeros[0] = mask mask = torch.stack(zeros,dim=0) zeros[1] = label label = torch.stack(zeros,dim=0) img_3ch = torch.cat([img,img,img],dim=0) masked = img_3ch+mask.float()*scale+label.float()*scale return [masked] @ex.automain def main(_run, _config, _log): for source_file, _ in _run.experiment_info['sources']: os.makedirs(os.path.dirname(f'{_run.observers[0].dir}/source/{source_file}'), exist_ok=True) _run.observers[0].save_file(source_file, f'source/{source_file}') shutil.rmtree(f'{_run.observers[0].basedir}/_sources') set_seed(_config['seed']) cudnn.enabled = True cudnn.benchmark = True torch.cuda.set_device(device=_config['gpu_id']) torch.set_num_threads(1) settings = Settings() common_params, data_params, net_params, train_params, eval_params = settings['COMMON'], settings['DATA'], settings[ 'NETWORK'], settings['TRAINING'], settings['EVAL'] _log.info('###### Create model ######') model = fs.FewShotSegmentorDoubleSDnet(net_params).cuda() # model = nn.DataParallel(model.cuda(), device_ids=[_config['gpu_id'],]) if not _config['notrain']: model.load_state_dict(torch.load(_config['snapshot'], map_location='cpu')) model.eval() _log.info('###### Load data ######') data_name = _config['dataset'] make_data = meta_data max_label = 1 tr_dataset, val_dataset, ts_dataset = make_data(_config) testloader = DataLoader( dataset=ts_dataset, batch_size=1, shuffle=False, # num_workers=_config['n_work'], pin_memory=False, # True drop_last=False ) if _config['record']: _log.info('###### define tensorboard writer #####') board_name = f'board/test_{_config["board"]}_{date()}' writer = SummaryWriter(board_name) _log.info('###### Testing begins ######') # metric = Metric(max_label=max_label, n_runs=_config['n_runs']) img_cnt = 0 # length = len(all_samples) length = len(testloader) img_lists = [] pred_lists = [] label_lists = [] saves = {} for subj_idx in range(len(ts_dataset.get_cnts())): saves[subj_idx] = [] with torch.no_grad(): loss_valid = 0 batch_i = 0 # use only 1 batch size for testing for i, sample_test in enumerate(testloader): # even for upward, down for downward subj_idx, idx = ts_dataset.get_test_subj_idx(i) img_list = [] pred_list = [] label_list = [] preds = [] s_x = sample_test['s_x'].cuda() # [B, Support, slice_num=1, 1, 256, 256] X = s_x.squeeze(2) # [B, Support, 1, 256, 256] s_y = sample_test['s_y'].cuda() # [B, Support, slice_num, 1, 256, 256] Y = s_y.squeeze(2) # [B, Support, 1, 256, 256] Y = Y.squeeze(2) # [B, Support, 256, 256] q_x = sample_test['q_x'].cuda() # [B, slice_num, 1, 256, 256] query_input = q_x.squeeze(1) # [B, 1, 256, 256] q_y = sample_test['q_y'].cuda() # [B, slice_num, 1, 256, 256] y2 = q_y.squeeze(1) # [B, 1, 256, 256] y2 = y2.squeeze(1) # [B, 256, 256] y2 = y2.type(torch.LongTensor).cuda() entire_weights = [] for shot_id in range(_config["n_shot"]): input1 = X[:, shot_id, ...] # use 1 shot at first y1 = Y[:, shot_id, ...] # use 1 shot at first condition_input = torch.cat((input1, y1.unsqueeze(1)), dim=1) weights = model.conditioner(condition_input) # 2, 10, [B, channel=1, w, h] entire_weights.append(weights) # pdb.set_trace() avg_weights=[[],[None, None, None, None]] for k in range(9): weight_cat = torch.cat([weights[0][k] for weights in entire_weights],dim=1) avg_weight = torch.mean(weight_cat,dim=1,keepdim=True) avg_weights[0].append(avg_weight) avg_weights[0].append(None) output = model.segmentor(query_input, avg_weights) q_yhat = output.argmax(dim=1) q_yhat = q_yhat.unsqueeze(1) preds.append(q_yhat) img_list.append(q_x[batch_i,0].cpu().numpy()) pred_list.append(q_yhat[batch_i].cpu().numpy()) label_list.append(q_y[batch_i,0].cpu().numpy()) saves[subj_idx].append([subj_idx, idx, img_list, pred_list, label_list]) print(f"test, iter:{i}/{length} - {subj_idx}/{idx} \t\t", end='\r') img_lists.append(img_list) pred_lists.append(pred_list) label_lists.append(label_list) print("start computing dice similarities ... total ", len(saves)) dice_similarities = [] for subj_idx in range(len(saves)): imgs, preds, labels = [], [], [] save_subj = saves[subj_idx] for i in range(len(save_subj)): # print(len(save_subj), len(save_subj)-q_slice_n+1, q_slice_n, i) subj_idx, idx, img_list, pred_list, label_list = save_subj[i] # print(subj_idx, idx, is_reverse, len(img_list)) # print(i, is_reverse, is_reverse_next, is_flip) for j in range(len(img_list)): imgs.append(img_list[j]) preds.append(pred_list[j]) labels.append(label_list[j]) # pdb.set_trace() img_arr = np.concatenate(imgs, axis=0) pred_arr = np.concatenate(preds, axis=0) label_arr = np.concatenate(labels, axis=0) # pdb.set_trace() # print(ts_dataset.slice_cnts[subj_idx] , len(imgs)) # pdb.set_trace() dice = np.sum([label_arr * pred_arr]) * 2.0 / (np.sum(pred_arr) + np.sum(label_arr)) dice_similarities.append(dice) print(f"computing dice scores {subj_idx}/{10}", end='\n') if _config['record']: frames = [] for frame_id in range(0, len(save_subj)): frames += overlay_color(torch.tensor(imgs[frame_id]), torch.tensor(preds[frame_id]).float(), torch.tensor(labels[frame_id])) visual = make_grid(frames, normalize=True, nrow=5) writer.add_image(f"test/{subj_idx}", visual, i) writer.add_scalar(f'dice_score/{i}', dice) print(f"test result \n n : {len(dice_similarities)}, mean dice score : \ {np.mean(dice_similarities)} \n dice similarities : {dice_similarities}") if _config['record']: writer.add_scalar(f'dice_score/mean', np.mean(dice_similarities))
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/train_background.sh
.sh
1,270
27
# this code require gpu_id when running mkdir runs/log declare -a gpu_list gpu_list=(0 1 2 3) #gpu_list=(4 5 6 7) j=$2 idx=0 for organ in 1 3 6 14 do echo "" echo "==================================================================" gpu=${gpu_list[$idx]} #gpu=0 echo "python train_multishot.py with mode=train target=${organ} record=False board=ID${j}_dice_adam_${organ}_1shot_8ch n_shot=1 gpu_id=$gpu iter_print=False n_steps=100 >> runs/log/train_ID${j}_dice_adam_${organ}_1shot_8ch.txt &" python train_multishot.py with mode=train target=${organ} record=False board=ID${j}_dice_adam_${organ}_1shot_8ch n_shot=1 gpu_id=$gpu iter_print=False n_steps=100 >> runs/log/train_ID${j}_dice_adam_${organ}_1shot_8ch.txt & #echo "------------------------------------------------------------------" #echo "python test.py with snapshot=runs/PANet_BCV_align_sets_0_1way_5shot_train/${j}/snapshots/lowest.pth gpu_id=$gpu record=False target=${organ} board=ID${j}_${organ}_5shot s_idx=0 n_shot=1" #python test.py with snapshot=runs/PANet_BCV_align_sets_0_1way_5shot_train/${j}/snapshots/lowest.pth gpu_id=$gpu record=False target=${organ} board=ID${j}_${organ}_5shot s_idx=0 n_shot=1 sleep 30 j=$(($j+1)) idx=$(($idx+1)) done exit 0
Shell
3D
oopil/3D_medical_image_FSS
FSS_SE/solver.py
.py
13,862
320
import glob import os import pdb import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import lr_scheduler import utils.common_utils as common_utils from nn_common_modules import losses # from nn_additional_losses import losses from utils.data_utils import split_batch from utils.log_utils import LogWriter CHECKPOINT_DIR = 'checkpoints' CHECKPOINT_EXTENSION = 'pth.tar' class Solver(object): def __init__(self, model, exp_name, device, num_class, optim=torch.optim.SGD, optim_args={}, loss_func=losses.DiceLoss(), model_name='OneShotSegmentor', labels=None, num_epochs=10, log_nth=5, lr_scheduler_step_size=5, lr_scheduler_gamma=0.5, use_last_checkpoint=True, exp_dir='experiments', log_dir='logs'): self.device = device self.model = model self.model_name = model_name self.labels = labels self.num_epochs = num_epochs if torch.cuda.is_available(): self.loss_func = loss_func.cuda(device) else: self.loss_func = loss_func self.optim_c = optim( [{'params': model.conditioner.parameters(), 'lr': 1e-3, 'momentum': 0.99, 'weight_decay': 0.0001} ], **optim_args) self.optim_s = optim( [{'params': model.segmentor.parameters(), 'lr': 1e-3, 'momentum': 0.99, 'weight_decay': 0.0001} ], **optim_args) self.scheduler_s = lr_scheduler.StepLR(self.optim_s, step_size=10, gamma=0.1) self.scheduler_c = lr_scheduler.StepLR(self.optim_c, step_size=10, gamma=0.001) exp_dir_path = os.path.join(exp_dir, exp_name) common_utils.create_if_not(exp_dir_path) common_utils.create_if_not(os.path.join(exp_dir_path, CHECKPOINT_DIR)) self.exp_dir_path = exp_dir_path self.log_nth = log_nth self.logWriter = LogWriter( num_class, log_dir, exp_name, use_last_checkpoint, labels) self.use_last_checkpoint = use_last_checkpoint self.start_epoch = 1 self.start_iteration = 1 self.best_ds_mean = 0 self.best_ds_mean_epoch = 0 if use_last_checkpoint: self.load_checkpoint() def train(self, train_loader, test_loader): """ Train a given model with the provided data. Inputs: - train_loader: train data in torch.utils.data.DataLoader - val_loader: val data in torch.utils.data.DataLoader """ model, optim_c, optim_s, scheduler_c, scheduler_s = self.model, self.optim_c, self.optim_s, self.scheduler_c, self.scheduler_s data_loader = { 'train': train_loader, 'val': test_loader } if torch.cuda.is_available(): torch.cuda.empty_cache() model.cuda(self.device) self.logWriter.log('START TRAINING. : model name = %s, device = %s' % ( self.model_name, torch.cuda.get_device_name(self.device))) current_iteration = self.start_iteration warm_up_epoch = 15 val_old = 0 change_model = False current_model = 'seg' for epoch in range(self.start_epoch, self.num_epochs + 1): self.logWriter.log( 'train', "\n==== Epoch [ %d / %d ] START ====" % (epoch, self.num_epochs)) if epoch > warm_up_epoch: if current_model == 'seg': self.logWriter.log("Optimizing Segmentor") optim = optim_s elif current_model == 'con': optim = optim_c self.logWriter.log("Optimizing Conditioner") for phase in ['train', 'val']: self.logWriter.log("<<<= Phase: %s =>>>" % phase) loss_arr = [] input_img_list = [] y_list = [] out_list = [] condition_input_img_list = [] condition_y_list = [] if phase == 'train': model.train() scheduler_c.step() scheduler_s.step() else: model.eval() for i_batch, sampled_batch in enumerate(data_loader[phase]): s_x = sampled_batch['s_x'] # [B, Support, slice_num=1, 1, 256, 256] X = s_x.squeeze(2) # [B, Support, 1, 256, 256] s_y = sampled_batch['s_y'] # [B, Support, slice_num, 1, 256, 256] Y = s_y.squeeze(2) # [B, Support, 1, 256, 256] Y = Y.squeeze(2) # [B, Support, 256, 256] q_x = sampled_batch['q_x'] # [B, slice_num, 1, 256, 256] q_x = q_x.squeeze(1) # [B, 1, 256, 256] q_y = sampled_batch['q_y'] # [B, slice_num, 1, 256, 256] q_y = q_y.squeeze(1) # [B, 1, 256, 256] q_y = q_y.squeeze(1) # [B, 256, 256] input1 = X[:,0,...] # use 1 shot at first y1 = Y[:,0,...] query_input = q_x input2 = q_x condition_input = torch.cat((input1, y1.unsqueeze(1)), dim=1) y2 = q_y y1 = y1.type(torch.LongTensor) y2 = y2.type(torch.LongTensor) # X = sampled_batch[0].type(torch.FloatTensor) # y = sampled_batch[1].type(torch.LongTensor) # w = sampled_batch[2].type(torch.FloatTensor) # query_label = data_loader[phase].batch_sampler.query_label # input1, input2, y1, y2 = split_batch( # X, y, int(query_label)) # condition_input = torch.cat( # (input1, y1.unsqueeze(1)), dim=1) # query_input = input2 # y1 = y1.type(torch.LongTensor) if model.is_cuda: condition_input, query_input, y2, y1 = condition_input.cuda(self.device, non_blocking=True), query_input.cuda(self.device, non_blocking=True), y2.cuda(self.device, non_blocking=True), y1.cuda(self.device, non_blocking=True) # pdb.set_trace() weights = model.conditioner(condition_input) output = model.segmentor(query_input, weights) loss = self.loss_func(F.softmax(output, dim=1), y2) optim_s.zero_grad() optim_c.zero_grad() loss.backward() if phase == 'train': if epoch <= warm_up_epoch: optim_s.step() optim_c.step() elif epoch > warm_up_epoch and change_model: optim.step() if i_batch % self.log_nth == 0: self.logWriter.loss_per_iter( loss.item(), i_batch, current_iteration) current_iteration += 1 # # loss_arr.append(loss.item()) # # _, batch_output = torch.max( # F.softmax(output, dim=1), dim=1) # # out_list.append(batch_output.cpu()) # input_img_list.append(input2.cpu()) # y_list.append(y2.cpu()) # condition_input_img_list.append(input1.cpu()) # condition_y_list.append(y1) # del X, Y, output, batch_output, loss, input1, input2, y2 # torch.cuda.empty_cache() if phase == 'val': if i_batch != len(data_loader[phase]) - 1: # print("#", end='', flush=True) pass else: print("100%", flush=True) if phase == 'train': self.logWriter.log('saving checkpoint ....') self.save_checkpoint({ 'epoch': epoch + 1, 'start_iteration': current_iteration + 1, 'arch': self.model_name, 'state_dict': model.state_dict(), 'optimizer_c': optim_c.state_dict(), 'scheduler_c': scheduler_c.state_dict(), 'optimizer_s': optim_s.state_dict(), 'best_ds_mean_epoch': self.best_ds_mean_epoch, 'scheduler_s': scheduler_s.state_dict() }, os.path.join(self.exp_dir_path, CHECKPOINT_DIR, 'checkpoint_epoch_' + str(epoch) + '.' + CHECKPOINT_EXTENSION)) # with torch.no_grad(): # input_img_arr = torch.cat(input_img_list) # y_arr = torch.cat(y_list) # out_arr = torch.cat(out_list) # condition_input_img_arr = torch.cat( # condition_input_img_list) # condition_y_arr = torch.cat(condition_y_list) # # current_loss = self.logWriter.loss_per_epoch( # loss_arr, phase, epoch) # if phase == 'val': # if epoch > warm_up_epoch: # self.logWriter.log( # "Diff : " + str(current_loss - val_old)) # change_model = (current_loss - val_old) > 0.001 # # if change_model and current_model == 'seg': # self.logWriter.log("Setting to con") # current_model = 'con' # elif change_model and current_model == 'con': # self.logWriter.log("Setting to seg") # current_model = 'seg' # val_old = current_loss # index = np.random.choice(len(out_arr), 3, replace=False) # self.logWriter.image_per_epoch(out_arr[index], y_arr[index], phase, epoch, additional_image=( # input_img_arr[index], condition_input_img_arr[index], condition_y_arr[index])) # ds_mean = self.logWriter.dice_score_per_epoch( # phase, out_arr, y_arr, epoch) # if phase == 'val': # if ds_mean > self.best_ds_mean: # self.best_ds_mean = ds_mean # self.best_ds_mean_epoch = epoch self.logWriter.log( "==== Epoch [" + str(epoch) + " / " + str(self.num_epochs) + "] DONE ====") self.logWriter.log('FINISH.') self.logWriter.close() def save_checkpoint(self, state, filename): torch.save(state, filename) def save_best_model(self, path): """ Save model with its parameters to the given path. Conventionally the path should end with "*.model". Inputs: - path: path string """ print('Saving model... %s' % path) print("Best Epoch... " + str(self.best_ds_mean_epoch)) self.load_checkpoint(self.best_ds_mean_epoch) torch.save(self.model, path) def load_checkpoint(self, epoch=None): if epoch is not None: checkpoint_path = os.path.join(self.exp_dir_path, CHECKPOINT_DIR, 'checkpoint_epoch_' + str(epoch) + '.' + CHECKPOINT_EXTENSION) self._load_checkpoint_file(checkpoint_path) else: all_files_path = os.path.join( self.exp_dir_path, CHECKPOINT_DIR, '*.' + CHECKPOINT_EXTENSION) list_of_files = glob.glob(all_files_path) if len(list_of_files) > 0: checkpoint_path = max(list_of_files, key=os.path.getctime) self._load_checkpoint_file(checkpoint_path) else: self.logWriter.log( "=> no checkpoint found at '{}' folder".format(os.path.join(self.exp_dir_path, CHECKPOINT_DIR))) def _load_checkpoint_file(self, file_path): self.logWriter.log("=> loading checkpoint '{}'".format(file_path)) checkpoint = torch.load(file_path) self.start_epoch = checkpoint['epoch'] self.start_iteration = checkpoint['start_iteration'] self.best_ds_mean_epoch = checkpoint['best_ds_mean_epoch'] self.model.load_state_dict(checkpoint['state_dict']) self.optim_c.load_state_dict(checkpoint['optimizer_c']) self.optim_s.load_state_dict(checkpoint['optimizer_s']) for state in self.optim_c.state.values(): for k, v in state.items(): if torch.is_tensor(v): state[k] = v.to(self.device) for state in self.optim_s.state.values(): for k, v in state.items(): if torch.is_tensor(v): state[k] = v.to(self.device) self.scheduler_c.load_state_dict(checkpoint['scheduler_c']) self.scheduler_s.load_state_dict(checkpoint['scheduler_s']) self.logWriter.log("=> loaded checkpoint '{}' (epoch {})".format( file_path, checkpoint['epoch']))
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/few_shot_segmentor.py
.py
10,170
277
"""Few-Shot_learning Segmentation""" import pdb import numpy as np import torch import torch.nn as nn from nn_common_modules import modules as sm from utils.data_utils import split_batch # import torch.nn.functional as F from squeeze_and_excitation import squeeze_and_excitation as se class SDnetConditioner(nn.Module): """ A conditional branch of few shot learning regressing the parameters for the segmentor """ def __init__(self, params): super(SDnetConditioner, self).__init__() se_block_type = se.SELayer.SSE params['num_channels'] = 2 params['num_filters'] = 16 self.encode1 = sm.SDnetEncoderBlock(params) self.squeeze_conv_e1 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) params['num_channels'] = 16 self.encode2 = sm.SDnetEncoderBlock(params) self.squeeze_conv_e2 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) self.encode3 = sm.SDnetEncoderBlock(params) self.squeeze_conv_e3 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) self.encode4 = sm.SDnetEncoderBlock(params) self.squeeze_conv_e4 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) self.bottleneck = sm.GenericBlock(params) self.squeeze_conv_bn = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) params['num_channels'] = 16 self.decode1 = sm.SDnetDecoderBlock(params) self.squeeze_conv_d1 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) self.decode2 = sm.SDnetDecoderBlock(params) self.squeeze_conv_d2 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) self.decode3 = sm.SDnetDecoderBlock(params) self.squeeze_conv_d3 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) self.decode4 = sm.SDnetDecoderBlock(params) self.squeeze_conv_d4 = nn.Conv2d(in_channels=params['num_filters'], out_channels=1, kernel_size=(1, 1), padding=(0, 0), stride=1) params['num_channels'] = 16 self.classifier = sm.ClassifierBlock(params) self.sigmoid = nn.Sigmoid() # self._init_weights() def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): torch.nn.init.kaiming_normal_(m.weight, nonlinearity='relu') def forward(self, input): e1, _, ind1 = self.encode1(input) e_w1 = self.sigmoid(self.squeeze_conv_e1(e1)) e2, out2, ind2 = self.encode2(e1) e_w2 = self.sigmoid(self.squeeze_conv_e2(e2)) e3, _, ind3 = self.encode3(e2) e_w3 = self.sigmoid(self.squeeze_conv_e3(e3)) e4, _, ind4 = self.encode3(e3) e_w4 = self.sigmoid(self.squeeze_conv_e4(e4)) bn = self.bottleneck(e4) bn_w4 = self.sigmoid(self.squeeze_conv_bn(bn)) d4 = self.decode4(bn, None, ind4) d_w4 = self.sigmoid(self.squeeze_conv_d4(d4)) d3 = self.decode3(d4, None, ind3) d_w3 = self.sigmoid(self.squeeze_conv_d3(d3)) d2 = self.decode2(d3, None, ind2) d_w2 = self.sigmoid(self.squeeze_conv_d2(d2)) d1 = self.decode1(d2, None, ind1) d_w1 = self.sigmoid(self.squeeze_conv_d1(d1)) space_weights = (e_w1, e_w2, e_w3, e_w4, bn_w4, d_w4, d_w3, d_w2, d_w1, None) channel_weights = (None, None, None, None) return space_weights, channel_weights class SDnetSegmentor(nn.Module): """ Segmentor Code param ={ 'num_channels':1, 'num_filters':64, 'kernel_h':5, 'kernel_w':5, 'stride_conv':1, 'pool':2, 'stride_pool':2, 'num_classes':1 'se_block': True, 'drop_out':0 } """ def __init__(self, params): super(SDnetSegmentor, self).__init__() params['num_channels'] = 1 params['num_filters'] = 64 self.encode1 = sm.SDnetEncoderBlock(params) params['num_channels'] = 64 self.encode2 = sm.SDnetEncoderBlock(params) self.encode3 = sm.SDnetEncoderBlock(params) self.encode4 = sm.SDnetEncoderBlock(params) self.bottleneck = sm.GenericBlock(params) self.decode1 = sm.SDnetDecoderBlock(params) self.decode2 = sm.SDnetDecoderBlock(params) self.decode3 = sm.SDnetDecoderBlock(params) params['num_channels'] = 64#128 self.decode4 = sm.SDnetDecoderBlock(params) params['num_channels'] = 64 self.classifier = sm.ClassifierBlock(params) self.soft_max = nn.Softmax2d() # self._init_weights() def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): torch.nn.init.kaiming_normal_(m.weight, nonlinearity='relu') def forward(self, inpt, weights=None): space_weights, channel_weights = weights e_w1, e_w2, e_w3, e_w4, bn_w, d_w4, d_w3, d_w2, d_w1, cls_w = space_weights if space_weights is not None else ( None, None, None, None, None, None, None, None, None, None) e_c1, e_c2, d_c1, d_c2 = channel_weights e1, _, ind1 = self.encode1(inpt) if e_w1 is not None: e1 = torch.mul(e1, e_w1) e2, _, ind2 = self.encode2(e1) if e_w2 is not None: e2 = torch.mul(e2, e_w2) e3, _, ind3 = self.encode3(e2) if e_w3 is not None: e3 = torch.mul(e3, e_w3) e4, out4, ind4 = self.encode4(e3) if e_w4 is not None: e4 = torch.mul(e4, e_w4) bn = self.bottleneck(e4) if bn_w is not None: bn = torch.mul(bn, bn_w) d4 = self.decode4(bn, None, ind4) if d_w4 is not None: d4 = torch.mul(d4, d_w4) d3 = self.decode3(d4, None, ind3) if d_w3 is not None: d3 = torch.mul(d3, d_w3) d2 = self.decode2(d3, None, ind2) if d_w2 is not None: d2 = torch.mul(d2, d_w2) d1 = self.decode1(d2, None, ind1) if d_w1 is not None: d1 = torch.mul(d1, d_w1) logit = self.classifier.forward(d1) if cls_w is not None: logit = torch.mul(logit, cls_w) logit = self.soft_max(logit) return logit class FewShotSegmentorDoubleSDnet(nn.Module): ''' Class Combining Conditioner and Segmentor for few shot learning ''' def __init__(self, params): super(FewShotSegmentorDoubleSDnet, self).__init__() self.conditioner = SDnetConditioner(params) self.segmentor = SDnetSegmentor(params) def forward(self, input1, input2): weights = self.conditioner(input1) segment = self.segmentor(input2, weights) return segment def enable_test_dropout(self): attr_dict = self.__dict__['_modules'] for i in range(1, 5): encode_block, decode_block = attr_dict['encode' + str(i)], attr_dict['decode' + str(i)] encode_block.drop_out = encode_block.drop_out.apply( nn.Module.train) decode_block.drop_out = decode_block.drop_out.apply( nn.Module.train) @property def is_cuda(self): """ Check if model parameters are allocated on the GPU. """ return next(self.parameters()).is_cuda def save(self, path): """ Save model with its parameters to the given path. Conventionally the path should end with "*.model". Inputs: - path: path string """ print('Saving model... %s' % path) torch.save(self, path) def predict(self, X, y, query_label, device=0, enable_dropout=False): """ Predicts the outout after the model is trained. Inputs: - X: Volume to be predicted """ self.eval() input1, input2, y2 = split_batch(X, y, query_label) input1, input2, y2 = to_cuda(input1, device), to_cuda( input2, device), to_cuda(y2, device) if enable_dropout: self.enable_test_dropout() with torch.no_grad(): out = self.forward(input1, input2) idx = out > 0.5 idx = idx.data.cpu().numpy() prediction = np.squeeze(idx) del X, out, idx return prediction def to_cuda(X, device): if type(X) is np.ndarray: X = torch.tensor(X, requires_grad=False).type( torch.FloatTensor).cuda(device, non_blocking=True) elif type(X) is torch.Tensor and not X.is_cuda: X = X.type(torch.FloatTensor).cuda(device, non_blocking=True) return X
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/Finetuning.ipynb
.ipynb
5,772
165
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import utils.data_utils as du\n", "from utils.evaluator import binarize_label\n", "import torch\n", "import matplotlib.pyplot as plt\n", "import torch.nn.functional as F\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loading dataset\nTrain size: 2576\nTest size: 304\n" ] } ], "source": [ "data_dir = \"/home/deeplearning/Abhijit/nas_drive/Abhijit/WholeBody/CT_ce/Data/Visceral\"\n", "label_dir = \"/home/deeplearning/Abhijit/nas_drive/Abhijit/WholeBody/CT_ce/Data/Visceral\"\n", "\n", "\n", "support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0],\n", " orientation=orientation,\n", " remap_config=remap_config)\n", "support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :,\n", " :]\n", "support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), \\\n", " torch.tensor(support_labelmap).type(torch.LongTensor)\n", "\n", "support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label)\n", "\n", "support_slice_indexes = np.round(np.linspace(0, len(support_volume) - 1, Num_support + 1)).astype(int)\n", "support_slice_indexes += (len(support_volume) // Num_support) // 2\n", "support_slice_indexes = support_slice_indexes[:-1]\n" ] }, { "cell_type": "code", "execution_count": 283, "metadata": { "collapsed": false }, "outputs": [], "source": [ "class_label = 7\n", "fold = '2'\n", "\n", "X, y = train_data.X, train_data.y\n", "y = (y == class_label)\n", "y = y.astype(np.float32)\n", "\n", "batch_size, _, _ = y.shape\n", "\n", "slice_with_class = np.sum(y.reshape(batch_size, -1), axis=1) > 10\n", "X = X[slice_with_class]\n", "y = y[slice_with_class]\n", "\n", "query_slice = np.random.randint(0, len(X))\n", "support_slice = np.random.randint(0, len(X))\n", "\n", "\n", "no_skip_model = torch.load('saved_models/sne_position_all_type_spatial_fold'+fold+'.pth.tar')\n", "# skip_model = torch.load('saved_models/sne_position_all_type_spatial_skipconn_baseline_fold'+fold+'.pth.tar')\n", "\n", "no_skip_model.cuda()\n", "no_skip_model.eval()\n", "# skip_model.cuda()\n", "# skip_model.eval()\n", "\n", "query_input = torch.tensor(X[query_slice])\n", "query_gt = torch.tensor(y[query_slice])\n", "\n", "support_input = torch.tensor(X[support_slice])\n", "support_gt = torch.tensor(y[support_slice])\n", "\n", "support_gt = support_gt.unsqueeze(0)\n", "\n", "condition_input = torch.cat((support_input, support_gt), dim=0)\n", "\n", "query_input = query_input.unsqueeze(0)\n", "condition_input = condition_input.unsqueeze(0)\n", "\n", "query_input = query_input.cuda()\n", "condition_input = condition_input.cuda()\n", "\n", "weights = no_skip_model.conditioner(condition_input)\n", "out = no_skip_model.segmentor(query_input, weights)\n", "\n", "_, segmentation_no_chhapa = torch.max(F.softmax(out, dim=1), dim=1)\n", "\n", "# weights = skip_model.conditioner(condition_input)\n", "# out = skip_model.segmentor(query_input, weights)\n", "\n", "# _, segmentation_chhapa = torch.max(F.softmax(out, dim=1), dim=1)\n", "\n", "ncols = 5\n", "fig, ax = plt.subplots(nrows=1, ncols=ncols, figsize=(20, 10), squeeze=False)\n", "\n", "ax[0][0].imshow(torch.squeeze(query_input), cmap='gray', vmin=0, vmax=1)\n", "ax[0][0].set_title(\"Query Input\", fontsize=10, color=\"blue\")\n", "ax[0][0].axis('off')\n", "ax[0][1].imshow(torch.squeeze(query_gt), cmap='gray', vmin=0, vmax=1)\n", "ax[0][1].set_title(\"Query GT\", fontsize=10, color=\"blue\")\n", "ax[0][1].axis('off')\n", "ax[0][2].imshow(torch.squeeze(segmentation_no_chhapa), cmap='gray', vmin=0, vmax=1)\n", "ax[0][2].set_title(\"No Chhapa\", fontsize=10, color=\"blue\")\n", "ax[0][2].axis('off')\n", "# ax[0][3].imshow(torch.squeeze(segmentation_chhapa), cmap='gray', vmin=0, vmax=1)\n", "# ax[0][3].set_title(\"Chhapa\", fontsize=10, color=\"blue\")\n", "# ax[0][3].axis('off')\n", "ax[0][3].imshow(torch.squeeze(support_input), cmap='gray', vmin=0, vmax=1)\n", "ax[0][3].set_title(\"Support Input\", fontsize=10, color=\"blue\")\n", "ax[0][3].axis('off')\n", "ax[0][4].imshow(torch.squeeze(support_gt), cmap='gray', vmin=0, vmax=1)\n", "ax[0][4].set_title(\"Support GT\", fontsize=10, color=\"blue\")\n", "ax[0][4].axis('off')\n", "\n", "fig.set_tight_layout(True)\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
oopil/3D_medical_image_FSS
FSS_SE/config.py
.py
4,196
154
"""Experiment Configuration""" import os import re import glob import itertools import sacred from sacred import Experiment from sacred.observers import FileStorageObserver from sacred.utils import apply_backspaces_and_linefeeds sacred.SETTINGS['CONFIG']['READ_ONLY_CONFIG'] = False sacred.SETTINGS.CAPTURE_MODE = 'no' ex = Experiment('PANet') ex.captured_out_filter = apply_backspaces_and_linefeeds source_folders = ['.', './dataloaders', './models', './util'] sources_to_save = list(itertools.chain.from_iterable( [glob.glob(f'{folder}/*.py') for folder in source_folders])) for source_file in sources_to_save: ex.add_source_file(source_file) @ex.config def cfg(): """Default configurations""" server="144" #202 size=256 input_size = (size, size) seed = 1234 cuda_visable = '0, 1, 2, 3, 4, 5, 6, 7' gpu_id = 0 n_shot = 1 mode = 'test' # 'train' or 'test' target = 1 s_idx=0 add_target=False record=False dataset = 'BCV' # 'VOC' or 'COCO' board = "try" iter_print=True external_test = "None" # "decathlon" # "CT_ORG" if external_test == "None": internal_test = True else: internal_test = False if mode == 'train': n_steps = 300 # 30000 n_iter= 1000 label_sets = 0 batch_size = 5 lr_milestones = [10000, 20000, 50000] # lr_milestones = [10000, 20000, 30000] align_loss_scaler = 1 ignore_label = 255 print_interval = 100 #100 save_pred_every = 500 n_work=1 model = { 'align': True, # 'align': False, } task = { 'n_ways': 1, 'n_shots': n_shot, 'n_queries': 1, } optim = { 'lr': 1e-3, 'momentum': 0.9, 'weight_decay': 0.0005, } elif mode == 'test': save_sample = False save_name = "" notrain = False snapshot = './runs/PANet_VOC_sets_0_1way_1shot_[train]/1/snapshots/30000.pth' n_runs = 5 n_iter = 1 n_steps = 1000 batch_size = 1 scribble_dilation = 0 bbox = False scribble = False # Set model config from the snapshot string model = {} for key in ['align',]: model[key] = key in snapshot # Set label_sets from the snapshot string label_sets = int(snapshot.split('_sets_')[1][0]) # Set task config from the snapshot string task = { 'n_ways': 1, 'n_shots': n_shot, 'n_queries': 1, } # task = { # 'n_ways': int(re.search("[0-9]+way", snapshot).group(0)[:-3]), # 'n_shots': int(re.search("[0-9]+shot", snapshot).group(0)[:-4]), # 'n_queries': 1, # } else: raise ValueError('Wrong configuration for "mode" !') exp_str = '_'.join( [dataset,] + [key for key, value in model.items() if value] + [f'sets_{label_sets}', f'{task["n_ways"]}way_{task["n_shots"]}shot_{mode}']) path = { 'log_dir': './runs', 'init_path': './../../pretrained_model/vgg16-397923af.pth', 'VOC':{'data_dir': '../../data/Pascal/VOCdevkit/VOC2012/', 'data_split': 'trainaug',}, 'COCO':{'data_dir': '../../data/COCO/', 'data_split': 'train',}, } data_srcs = { "144":"/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_2", "202":"/data2/soopil/MICCAI2015challenge/Abdomen/RawData/Training_2d_2", } data_src = data_srcs[str(server)] @ex.config_hook def add_observer(config, command_name, logger): """A hook fucntion to add observer""" exp_name = f'{ex.path}_{config["exp_str"]}' if config['mode'] == 'test': if config['notrain']: exp_name += '_notrain' if config['scribble']: exp_name += '_scribble' if config['bbox']: exp_name += '_bbox' observer = FileStorageObserver.create(os.path.join(config['path']['log_dir'], exp_name)) ex.observers.append(observer) return config
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/run.py
.py
6,709
186
import argparse import os import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import MultiStepLR import torch.backends.cudnn as cudnn from dataloaders_medical.prostate import * import few_shot_segmentor as fs import utils.evaluator as eu from settings import Settings from solver import Solver from utils.data_utils import get_imdb_dataset from utils.log_utils import LogWriter from utils.shot_batch_sampler import OneShotBatchSampler, get_lab_list torch.set_default_tensor_type('torch.FloatTensor') def load_data(data_params): print("Loading dataset") train_data, test_data = get_imdb_dataset(data_params) print("Train size: %i" % len(train_data)) print("Test size: %i" % len(test_data)) return train_data, test_data class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x def train(train_params, common_params, data_params, net_params): _config= { "size":256, "n_shot": 1, "mode": 'test', # 'train' or 'test', "target": 1, "s_idx":0, "add_target":False, "record":False, "dataset": 'BCV', # 'VOC' or 'COCO', "board": "try", "n_steps": 50000, # 30000, "n_iter": train_params['iterations'],#5000, "label_sets": 0, "batch_size": 5, "lr_milestones": [10000, 20000, 50000], # "lr_milestones": [10000, 20000, 30000], "align_loss_scaler": 1, "ignore_label": 255, "n_work": 1, "task": { 'n_ways': 1, 'n_shots': 1, 'n_queries': 1, }, "data_src" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_2", } make_data = meta_data tr_dataset, val_dataset, ts_dataset = make_data(_config) trainloader = DataLoader( dataset=tr_dataset, batch_size=_config['batch_size'], shuffle=True, num_workers=_config['n_work'], pin_memory=False, #True load data while training gpu drop_last=True ) validationloader = DataLoader( dataset=val_dataset, batch_size=1, shuffle=True, num_workers=_config['n_work'], pin_memory=False,#True drop_last=False ) model_prefix = 'BCV_try'#'sne_position_all_type_channel_' folds = ['fold1', 'fold2', 'fold3', 'fold4'] fold="fold1" final_model_path = os.path.join( common_params['save_model_dir'], model_prefix + fold + '.pth.tar') few_shot_model = fs.FewShotSegmentorDoubleSDnet(net_params) solver = Solver(few_shot_model, device=common_params['device'], num_class=net_params['num_class'], optim_args={"lr": train_params['learning_rate'], "weight_decay": train_params['optim_weight_decay'], "momentum": train_params['momentum']}, model_name=common_params['model_name'], exp_name=train_params['exp_name'], labels=data_params['labels'], log_nth=train_params['log_nth'], num_epochs=train_params['num_epochs'], lr_scheduler_step_size=train_params['lr_scheduler_step_size'], lr_scheduler_gamma=train_params['lr_scheduler_gamma'], use_last_checkpoint=train_params['use_last_checkpoint'], log_dir=common_params['log_dir'], exp_dir=common_params['exp_dir']) solver.train(trainloader, validationloader) solver.save_best_model(final_model_path) print("final model saved @ " + str(final_model_path)) def evaluate(eval_params, net_params, data_params, common_params, train_params): eval_model_path = eval_params['eval_model_path'] num_classes = net_params['num_class'] labels = data_params['labels'] data_dir = eval_params['data_dir'] query_txt_file = eval_params['query_txt_file'] support_txt_file = eval_params['support_txt_file'] remap_config = eval_params['remap_config'] device = common_params['device'] log_dir = common_params['log_dir'] exp_dir = common_params['exp_dir'] exp_name = train_params['exp_name'] save_predictions_dir = eval_params['save_predictions_dir'] orientation = eval_params['orientation'] logWriter = LogWriter(num_classes, log_dir, exp_name, labels=labels) folds = ['fold1', 'fold2', 'fold3', 'fold4'] for fold in folds: prediction_path = os.path.join(exp_dir, exp_name) prediction_path = prediction_path + "_" + fold prediction_path = os.path.join(prediction_path, save_predictions_dir) eval_model_path = os.path.join( 'saved_models', eval_model_path + '_' + fold + '.pth.tar') query_labels = get_lab_list('val', fold) num_classes = len(fold) avg_dice_score = eu.evaluate_dice_score(eval_model_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation, prediction_path, device, logWriter, fold=fold) logWriter.log(avg_dice_score) logWriter.close() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--mode', '-m', required=True, help='run mode, valid values are train and eval') parser.add_argument('--device', '-d', required=False, help='device to run on') args = parser.parse_args() settings = Settings() common_params, data_params, net_params, train_params, eval_params = settings['COMMON'], settings['DATA'], settings[ 'NETWORK'], settings['TRAINING'], settings['EVAL'] if args.device is not None: common_params['device'] = args.device if args.mode == 'train': train(train_params, common_params, data_params, net_params) elif args.mode == 'eval': evaluate(eval_params, net_params, data_params, common_params, train_params) else: raise ValueError( 'Invalid value for mode. only support values are train and eval')
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/evaluator_hack.py
.py
37,255
705
import os import nibabel as nib import numpy as np import torch import utils.common_utils as common_utils import utils.data_utils as du import torch.nn.functional as F import shot_batch_sampler as SB def dice_score_binary(vol_output, ground_truth, no_samples=10, phase='train'): ground_truth = ground_truth.type(torch.FloatTensor) vol_output = vol_output.type(torch.FloatTensor) if phase == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] inter = 2 * torch.sum(torch.mul(ground_truth, vol_output)) union = torch.sum(ground_truth) + torch.sum(vol_output) + 0.0001 return torch.div(inter, union) def dice_confusion_matrix(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_cm = torch.zeros(num_classes, num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() for j in range(num_classes): Pred = (vol_output == j).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_cm[i, j] = 2 * torch.div(inter, union) avg_dice = torch.mean(torch.diagflat(dice_cm)) return avg_dice, dice_cm def get_range(volume): batch, _, _ = volume.size() slice_with_class = torch.sum(volume.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) return range_index def dice_score_perclass(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_perclass = torch.zeros(num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() Pred = (vol_output == i).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_perclass[i] = (2 * torch.div(inter, union)) return dice_perclass def binarize_label(volume, groud_truth, class_label): groud_truth = (groud_truth == class_label).type(torch.FloatTensor) batch, _, _ = groud_truth.size() slice_with_class = torch.sum(groud_truth.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) groud_truth = groud_truth[slice_with_class] volume = volume[slice_with_class] condition_input = torch.cat((volume, groud_truth.unsqueeze(1)), dim=1) return condition_input, range_index.cpu().numpy() def evaluate_dice_score(model_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model_path) batch_size = 20 Num_support = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model = torch.load(model_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model.cuda(device) model.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] # # support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], # orientation=orientation, # remap_config=remap_config) # # support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] # # support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), torch.tensor( # support_labelmap).type(torch.LongTensor) # support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) # support_volume = support_volume[range_index[0]: range_index[1]] # Loading support support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], orientation=orientation, remap_config=remap_config) support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), \ torch.tensor(support_labelmap).type(torch.LongTensor) support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) slice_gap_support = int(np.ceil(len(support_volume) / Num_support)) support_slice_indexes = [i for i in range(0, len(support_volume), slice_gap_support)] if len(support_slice_indexes) < Num_support: support_slice_indexes.append(len(support_volume) - 1) for vol_idx, file_path in enumerate(query_file_paths): query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, remap_config=remap_config) query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), \ torch.tensor(query_labelmap).type(torch.LongTensor) query_labelmap = query_labelmap == query_label range_query = get_range(query_labelmap) query_volume = query_volume[range_query[0]: range_query[1] + 1] query_labelmap = query_labelmap[range_query[0]: range_query[1] + 1] slice_gap_query = int(np.ceil((len(query_volume) / Num_support))) query_slice_indexes = [i for i in range(0, len(query_volume), slice_gap_query)] if len(query_slice_indexes) < Num_support: query_slice_indexes.append(len(query_volume) - 1) volume_prediction = [] # for i in range(0, len(query_volume), batch_size): support_current_slice = 0 query_current_slice = 0 for i, query_start_slice in enumerate(query_slice_indexes): if query_start_slice == query_slice_indexes[-1]: query_batch_x = query_volume[query_slice_indexes[i]:] else: query_batch_x = query_volume[query_slice_indexes[i]:query_slice_indexes[i + 1]] support_batch_x = support_volume[support_slice_indexes[i]] support_batch_x = support_batch_x.repeat(len(query_batch_x), 1, 1, 1) if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model.conditioner(support_batch_x) out = model.segmentor(query_batch_x, weights) _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction.append(batch_output) query_current_slice += slice_gap_query support_current_slice += slice_gap_support # query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, # remap_config=remap_config) # query_labelmap = query_labelmap == query_label # range_query = get_range(query_labelmap) # query_volume = query_volume[range_query[0]: range_query[1]] # # query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] # query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), torch.tensor( # query_labelmap).type(torch.LongTensor) # # support_batch_x = [] # # volume_prediction = [] # # support_current_slice = 0 # query_current_slice = 0 # support_slice_left = support_volume[range_index[0]] # for i in range(0, range_index[0], batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < range_index[0] else range_index[0] # # query_batch_x = query_volume[i: end_index_query] # # support_batch_x = support_slice_left.repeat(query_batch_x.size()[0], 1, 1, 1) # # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice = end_index_query # support_current_slice = query_current_slice # # for i in range(range_index[0], range_index[1] + 1, batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < range_index[1] + 1 else range_index[1] + 1 # # query_batch_x = query_volume[i: end_index_query] # # # end_index_support = support_current_slice + batch_size # # end_index_support = end_index_support if end_index_support < len(range_index[1] + 1) else len( # # range_index[1] + 1) # # print(len(support_volume)) # # print(support_current_slice, end_index_query) # support_batch_x = support_volume[support_current_slice: end_index_query] # # query_current_slice = end_index_query # support_current_slice = query_current_slice # # support_batch_x = support_batch_x[0].repeat(query_batch_x.size()[0], 1, 1, 1) # # # k += 1 # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # # support_slice_right = support_volume[range_index[1]] # for i in range(range_index[1] + 1, len(support_volume), batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < len(support_volume) else len(support_volume) # # query_batch_x = query_volume[i: end_index_query] # # support_batch_x = support_slice_right.repeat(query_batch_x.size()[0], 1, 1, 1) # # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice = end_index_query # support_current_slice = query_current_slice volume_prediction = torch.cat(volume_prediction) # batch, _, _ = query_labelmap.size() # slice_with_class = torch.sum(query_labelmap.view(batch, -1), dim=1) > 10 # index = slice_with_class[:-1] - slice_with_class[1:] > 0 # seq = torch.Tensor(range(batch - 1)) # range_index_gt = seq[index].type(torch.LongTensor) volume_dice_score = dice_score_binary(volume_prediction[:len(query_labelmap)], query_labelmap.cuda(device), phase=mode) volume_prediction = (volume_prediction.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(volume_prediction), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # # # Save Input # # nifti_img = nib.MGHImage(np.squeeze(query_volume.cpu().numpy()), np.eye(4)) # # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # Cond GT nifti_img = nib.MGHImage(np.squeeze(support_labelmap.cpu().numpy()).astype('float32'), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # Save Ground Truth nifti_img = nib.MGHImage(np.squeeze(query_labelmap.cpu().numpy()), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + fold + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_2view(model1_path, model2_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model1.eval() model2.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label query_labelmap2 = query_labelmap2 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction = 0.5 * volume_prediction1 + 0.5 * volume_prediction2.permute(3, 1, 0, 2) _, batch_output = torch.max(F.softmax(volume_prediction, dim=1), dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_3view(model1_path, model2_path, model3_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) model3 = torch.load(model3_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model3.cuda(device) model1.eval() model2.eval() model3.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume3, support_labelmap3 = support_volume1.transpose((2, 0, 1)), support_labelmap1.transpose( (2, 0, 1)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume3 = support_volume3 if len(support_volume3.shape) == 4 else support_volume3[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume3, support_labelmap3 = torch.tensor(support_volume3).type( torch.FloatTensor), torch.tensor( support_labelmap3).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) support_volume3 = binarize_label(support_volume3, support_labelmap3, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume3, query_labelmap3 = query_volume1.transpose((2, 0, 1)), query_labelmap1.transpose( (2, 0, 1)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume3 = query_volume3 if len(query_volume3.shape) == 4 else query_volume3[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_volume3, query_labelmap3 = torch.tensor(query_volume3).type(torch.FloatTensor), torch.tensor( query_labelmap3).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label # query_labelmap2 = query_labelmap2 == query_label # query_labelmap3 = query_labelmap3 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) # Evaluate for orientation 3 support_batch_x = [] k = 2 volume_prediction3 = [] for i in range(0, len(query_volume3), batch_size): query_batch_x = query_volume3[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume3[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model3.conditioner(support_batch_x) out = model3.segmentor(query_batch_x, weights) volume_prediction3.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction3 = torch.cat(volume_prediction3) volume_prediction = 0.33 * F.softmax(volume_prediction1, dim=1) + 0.33 * F.softmax( volume_prediction2.permute(3, 1, 0, 2), dim=1) + 0.33 * F.softmax( volume_prediction3.permute(2, 1, 3, 0), dim=1) _, batch_output = torch.max(volume_prediction, dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/evaluator_multi_volume_support.py
.py
31,169
629
import os import nibabel as nib import numpy as np import torch import utils.common_utils as common_utils import utils.data_utils as du import torch.nn.functional as F import matplotlib.pyplot as plt import shot_batch_sampler as SB def dice_score_binary(vol_output, ground_truth, no_samples=10, phase='train'): ground_truth = ground_truth.type(torch.FloatTensor) vol_output = vol_output.type(torch.FloatTensor) if phase == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] inter = 2 * torch.sum(torch.mul(ground_truth, vol_output)) union = torch.sum(ground_truth) + torch.sum(vol_output) + 0.0001 return torch.div(inter, union) def dice_confusion_matrix(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_cm = torch.zeros(num_classes, num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() for j in range(num_classes): Pred = (vol_output == j).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_cm[i, j] = 2 * torch.div(inter, union) avg_dice = torch.mean(torch.diagflat(dice_cm)) return avg_dice, dice_cm def get_range(volume): batch, _, _ = volume.size() slice_with_class = torch.sum(volume.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) return range_index def dice_score_perclass(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_perclass = torch.zeros(num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() Pred = (vol_output == i).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_perclass[i] = (2 * torch.div(inter, union)) return dice_perclass def binarize_label(volume, groud_truth, class_label): groud_truth = (groud_truth == class_label).type(torch.FloatTensor) batch, _, _ = groud_truth.size() slice_with_class = torch.sum(groud_truth.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) groud_truth = groud_truth[slice_with_class] volume = volume[slice_with_class] condition_input = torch.cat((volume, groud_truth.unsqueeze(1)), dim=1) return condition_input, range_index.cpu().numpy() def CV(samples_arr): eps = 0.0001 threshold = 0.0001 sample_size = samples_arr[0].size() total_pixels = sample_size[-1] * sample_size[-2] samples_arr = [sample.squeeze() for sample in samples_arr if (sample.sum().item() / total_pixels) > threshold] if len(samples_arr) > 0: samples_arr = torch.cat(samples_arr).float().squeeze() std = torch.std(samples_arr).item() mean = torch.mean(samples_arr).item() + eps return std / mean else: return 1000000 def IOU_Single(sample1, sample2): eps = 0.0001 sample1, sample2 = sample1.squeeze().byte(), sample2.squeeze().byte() intersection = sample1 & sample2 union = sample1 | sample2 numerator = intersection.sum().item() denominator = union.sum().item() + eps return numerator / denominator def IoU(samples_arr, support, query, vol): # Hardcoded for 3 elements as of now eps = 0.0001 threshold = 0.0001 sample_size = samples_arr[0].size() total_pixels = sample_size[-1] * sample_size[-2] samples_arr = [sample.squeeze().byte() for sample in samples_arr if (sample.sum().item() / total_pixels) > threshold] # plt.imsave(str(vol) + '_' + str(query) + '_' + str(support) + '_' + 'fig1', sample1.cpu().numpy()) # plt.imsave(str(vol) + '_' + str(query) + '_' + str(support) + '_' + 'fig2', sample2.cpu().numpy()) # plt.imsave(str(vol) + '_' + str(query) + '_' + str(support) + '_' + 'fig3', sample3.cpu().numpy()) if len(samples_arr) > 0: intersection = torch.ones(samples_arr[0].size()).byte().cuda() union = torch.zeros(samples_arr[0].size()).byte().cuda() for sample in samples_arr: intersection = intersection & sample union = union | sample numerator = intersection.sum().item() denominator = union.sum().item() + eps return numerator / denominator else: return 0 # inter = torch.ones(samples_arr[0].size()).cuda() # union = torch.zeros(samples_arr[0].size()).cuda() # # # for sample in samples_arr: # inter = torch.sum(torch.mul(inter, sample.type(torch.cuda.FloatTensor))) # union = torch.sum(union) + torch.sum(sample.type(torch.cuda.FloatTensor)) - inter # return -torch.div(inter, union + 0.0001).item() def evaluate_dice_score(model_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model_path) batch_size = 20 Num_support = 15 MC_samples = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model = torch.load(model_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model.cuda(device) model.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] support_slices = [] for i, file_path in enumerate(support_file_paths): # Loading support support_volume, support_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, remap_config=remap_config) support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), \ torch.tensor(support_labelmap).type(torch.LongTensor) support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) slice_gap_support = int(np.ceil(len(support_volume) / Num_support)) support_slice_indexes = [i for i in range(0, len(support_volume), slice_gap_support)] if len(support_slice_indexes) < Num_support: support_slice_indexes.append(len(support_volume) - 1) support_slices.extend([support_volume[idx] for idx in support_slice_indexes]) for vol_idx, file_path in enumerate(query_file_paths): query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, remap_config=remap_config) query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), \ torch.tensor(query_labelmap).type(torch.LongTensor) query_labelmap = query_labelmap == query_label range_query = get_range(query_labelmap) query_volume = query_volume[range_query[0]: range_query[1] + 1] query_labelmap = query_labelmap[range_query[0]: range_query[1] + 1] slice_gap_query = int(np.ceil(len(query_volume) / Num_support)) dice_per_batch = [] batch_output_arr = [] for support_slice_idx, i in enumerate(range(0, len(query_volume), slice_gap_query)): query_batch_x = query_volume[i:i+slice_gap_query] support_batch_x = support_volume[support_slice_idx].repeat(query_batch_x.size()[0], 1, 1, 1) if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model.conditioner(support_batch_x) out = model.segmentor(query_batch_x, weights) _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) batch_output_arr.append(batch_output) volume_output = torch.cat(batch_output_arr) volume_dice_score = dice_score_binary(volume_output, query_labelmap.cuda(device), phase=mode) volume_dice_score_list.append(volume_dice_score.item()) print(str(file_path), volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print(volume_dice_score_list) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_2view(model1_path, model2_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model1.eval() model2.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label query_labelmap2 = query_labelmap2 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction = 0.5 * volume_prediction1 + 0.5 * volume_prediction2.permute(3, 1, 0, 2) _, batch_output = torch.max(F.softmax(volume_prediction, dim=1), dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_3view(model1_path, model2_path, model3_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) model3 = torch.load(model3_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model3.cuda(device) model1.eval() model2.eval() model3.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume3, support_labelmap3 = support_volume1.transpose((2, 0, 1)), support_labelmap1.transpose( (2, 0, 1)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume3 = support_volume3 if len(support_volume3.shape) == 4 else support_volume3[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume3, support_labelmap3 = torch.tensor(support_volume3).type( torch.FloatTensor), torch.tensor( support_labelmap3).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) support_volume3 = binarize_label(support_volume3, support_labelmap3, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume3, query_labelmap3 = query_volume1.transpose((2, 0, 1)), query_labelmap1.transpose( (2, 0, 1)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume3 = query_volume3 if len(query_volume3.shape) == 4 else query_volume3[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_volume3, query_labelmap3 = torch.tensor(query_volume3).type(torch.FloatTensor), torch.tensor( query_labelmap3).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label # query_labelmap2 = query_labelmap2 == query_label # query_labelmap3 = query_labelmap3 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) # Evaluate for orientation 3 support_batch_x = [] k = 2 volume_prediction3 = [] for i in range(0, len(query_volume3), batch_size): query_batch_x = query_volume3[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume3[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model3.conditioner(support_batch_x) out = model3.segmentor(query_batch_x, weights) volume_prediction3.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction3 = torch.cat(volume_prediction3) volume_prediction = 0.33 * F.softmax(volume_prediction1, dim=1) + 0.33 * F.softmax( volume_prediction2.permute(3, 1, 0, 2), dim=1) + 0.33 * F.softmax( volume_prediction3.permute(2, 1, 3, 0), dim=1) _, batch_output = torch.max(volume_prediction, dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/convert_h5.py
.py
7,067
121
""" Convert to h5 utility. Sample command to create new dataset - python utils/convert_h5.py -dd /home/masterthesis/shayan/nas_drive/Data_Neuro/OASISchallenge/FS -ld /home/masterthesis/shayan/nas_drive/Data_Neuro/OASISchallenge -trv datasets/train_volumes.txt -tev datasets/test_volumes.txt -rc Neo -o COR -df datasets/MALC/coronal - python utils/convert_h5.py -dd /home/masterthesis/shayan/nas_drive/Data_Neuro/IXI/IXI_FS -ld /home/masterthesis/shayan/nas_drive/Data_Neuro/IXI/IXI_FS -ds 98,2 -rc FS -o COR -df datasets/IXI/coronal - python3.6 utils/convert_h5.py -dd /home/deeplearning/Abhijit/nas_drive/Abhijit/WholeBody/CT_ce/Data/SilverCorpus -ld /home/deeplearning/Abhijit/nas_drive/Abhijit/WholeBody/CT_ce/Data/SilverCorpus -trv datasets/test_volumes_silver.txt -tev datasets/test_volumes_silver.txt -rc WholeBody -o AXI -df datasets/silver_corpus """ import argparse import os import h5py import numpy as np import common_utils import data_utils as du import preprocessor def apply_split(data_split, data_dir, label_dir): file_paths = du.load_file_paths(data_dir, label_dir) print("Total no of volumes to process : %d" % len(file_paths)) train_ratio, test_ratio = data_split.split(",") train_len = int((int(train_ratio) / 100) * len(file_paths)) train_idx = np.random.choice(len(file_paths), train_len, replace=False) test_idx = np.array([i for i in range(len(file_paths)) if i not in train_idx]) train_file_paths = [file_paths[i] for i in train_idx] test_file_paths = [file_paths[i] for i in test_idx] return train_file_paths, test_file_paths def _write_h5(data, label, class_weights, weights, f, mode): no_slices, H, W = data[0].shape with h5py.File(f[mode]['data'], "w") as data_handle: data_handle.create_dataset("data", data=np.concatenate(data).reshape((-1, H, W))) with h5py.File(f[mode]['label'], "w") as label_handle: label_handle.create_dataset("label", data=np.concatenate(label).reshape((-1, H, W))) with h5py.File(f[mode]['weights'], "w") as weights_handle: weights_handle.create_dataset("weights", data=np.concatenate(weights)) with h5py.File(f[mode]['class_weights'], "w") as class_weights_handle: class_weights_handle.create_dataset("class_weights", data=np.concatenate( class_weights).reshape((-1, H, W))) def convert_h5(data_dir, label_dir, data_split, train_volumes, test_volumes, f, remap_config='Neo', orientation=preprocessor.ORIENTATION['coronal']): # Data splitting if data_split: train_file_paths, test_file_paths = apply_split(data_split, data_dir, label_dir) elif train_volumes and test_volumes: train_file_paths = du.load_file_paths_brain(data_dir, label_dir, train_volumes) test_file_paths = du.load_file_paths_brain(data_dir, label_dir, test_volumes) else: raise ValueError('You must either provide the split ratio or a train, train dataset list') print("Train dataset size: %d, Test dataset size: %d" % (len(train_file_paths), len(test_file_paths))) # loading,pre-processing and writing train data print("===Train data===") data_train, label_train, class_weights_train, weights_train = du.load_dataset(train_file_paths, orientation, remap_config=remap_config, return_weights=True, reduce_slices=True, remove_black=True) _write_h5(data_train, label_train, class_weights_train, weights_train, f, mode='train') # loading,pre-processing and writing test data print("===Test data===") data_test, label_test, class_weights_test, weights_test = du.load_dataset(test_file_paths, orientation, remap_config=remap_config, return_weights=True, reduce_slices=True, remove_black=True) _write_h5(data_test, label_test, class_weights_test, weights_test, f, mode='test') if __name__ == "__main__": print("* Start *") parser = argparse.ArgumentParser() parser.add_argument('--data_dir', '-dd', required=True, help='Base directory of the data folder. This folder should contain one folder per volume.') parser.add_argument('--label_dir', '-ld', required=True, help='Base directory of all the label files. This folder should have one file per volumn with same name as the corresponding volumn folder name inside data_dir') parser.add_argument('--data_split', '-ds', required=False, help='Ratio to split data randomly into train and test. input e.g. 80,20') parser.add_argument('--train_volumes', '-trv', required=False, help='Path to a text file containing the list of volumes to be used for training') parser.add_argument('--test_volumes', '-tev', required=False, help='Path to a text file containing the list of volumes to be used for testing') parser.add_argument('--remap_config', '-rc', required=True, help='Valid options are "FS" and "Neo"') parser.add_argument('--orientation', '-o', required=True, help='Valid options are COR, AXI, SAG') parser.add_argument('--destination_folder', '-df', required=True, help='Path where to generate the h5 files') args = parser.parse_args() common_utils.create_if_not(args.destination_folder) f = { 'train': { "data": os.path.join(args.destination_folder, "Data_train.h5"), "label": os.path.join(args.destination_folder, "Label_train.h5"), "weights": os.path.join(args.destination_folder, "Weight_train.h5"), "class_weights": os.path.join(args.destination_folder, "Class_Weight_train.h5"), }, 'test': { "data": os.path.join(args.destination_folder, "Data_test.h5"), "label": os.path.join(args.destination_folder, "Label_test.h5"), "weights": os.path.join(args.destination_folder, "Weight_test.h5"), "class_weights": os.path.join(args.destination_folder, "Class_Weight_test.h5") } } convert_h5(args.data_dir, args.label_dir, args.data_split, args.train_volumes, args.test_volumes, f, args.remap_config, args.orientation) print("* Finish *")
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/common_utils.py
.py
96
7
import os def create_if_not(path): if not os.path.exists(path): os.makedirs(path)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/preprocessor.py
.py
3,898
104
import numpy as np ORIENTATION = { 'coronal': "COR", 'axial': "AXI", 'sagital': "SAG" } def rotate_orientation(volume_data, volume_label, orientation=ORIENTATION['coronal']): if orientation == ORIENTATION['coronal']: return volume_data.transpose((2, 0, 1)), volume_label.transpose((2, 0, 1)) elif orientation == ORIENTATION['axial']: return volume_data.transpose((1, 2, 0)), volume_label.transpose((1, 2, 0)) elif orientation == ORIENTATION['sagital']: return volume_data, volume_label else: raise ValueError("Invalid value for orientation. Pleas see help") def estimate_weights_mfb(labels): class_weights = np.zeros_like(labels) unique, counts = np.unique(labels, return_counts=True) median_freq = np.median(counts) weights = np.zeros(len(unique)) for i, label in enumerate(unique): class_weights += (median_freq // counts[i]) * np.array(labels == label) try: weights[int(label)] = median_freq // counts[i] except IndexError as e: print("Exception in processing") continue grads = np.gradient(labels) edge_weights = (grads[0] ** 2 + grads[1] ** 2) > 0 class_weights += 2 * edge_weights return class_weights, weights def remap_labels(labels, remap_config): """ Function to remap the label values into the desired range of algorithm """ if remap_config == 'FS': label_list = [2, 3, 4, 5, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 24, 26, 28, 41, 42, 43, 44, 46, 47, 49, 50, 51, 52, 53, 54, 58, 60] elif remap_config == 'Neo': labels[(labels >= 100) & (labels % 2 == 0)] = 210 labels[(labels >= 100) & (labels % 2 == 1)] = 211 label_list = [45, 211, 52, 50, 41, 39, 60, 37, 58, 56, 4, 11, 35, 48, 32, 46, 30, 62, 44, 210, 51, 49, 40, 38, 59, 36, 57, 55, 47, 31, 23, 61] elif remap_config == 'WholeBody': label_list = [1, 2, 7, 8, 9, 13, 14, 17, 18] elif remap_config == 'brain_fewshot': labels[(labels >= 100) & (labels % 2 == 0)] = 210 labels[(labels >= 100) & (labels % 2 == 1)] = 211 label_list = [[210, 211], [45, 44], [52, 51], [35], [39, 41, 40, 38], [36, 37, 57, 58, 60, 59, 56, 55]] else: raise ValueError("Invalid argument value for remap config, only valid options are FS and Neo") new_labels = np.zeros_like(labels) k = isinstance(label_list[0], list) if not k: for i, label in enumerate(label_list): label_present = np.zeros_like(labels) label_present[labels == label] = 1 new_labels = new_labels + (i + 1) * label_present else: for i, label in enumerate(label_list): label_present = np.zeros_like(labels) for j in label: label_present[labels == j] = 1 new_labels = new_labels + (i + 1) * label_present return new_labels def reduce_slices(data, labels, skip_Frame=40): """ This function removes the useless black slices from the start and end. And then selects every even numbered frame. """ no_slices, H, W = data.shape mask_vector = np.zeros(no_slices, dtype=int) mask_vector[::2], mask_vector[1::2] = 1, 0 mask_vector[:skip_Frame], mask_vector[-skip_Frame:-1] = 0, 0 data_reduced = np.compress(mask_vector, data, axis=0).reshape(-1, H, W) labels_reduced = np.compress(mask_vector, labels, axis=0).reshape(-1, H, W) return data_reduced, labels_reduced def remove_black(data, labels): clean_data, clean_labels = [], [] for i, frame in enumerate(labels): unique, counts = np.unique(frame, return_counts=True) if counts[0] / sum(counts) < .99: clean_labels.append(frame) clean_data.append(data[i]) return np.array(clean_data), np.array(clean_labels)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/__init__.py
.py
0
0
null
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/log_utils.py
.py
8,456
200
import itertools import os import re import shutil from textwrap import wrap import matplotlib import matplotlib.pyplot as plt import numpy as np from tensorboardX import SummaryWriter import torch import utils.evaluator as eu import logging logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") plt.switch_backend('agg') plt.axis('scaled') # TODO: Add custom phase names class LogWriter(object): def __init__(self, num_class, log_dir_name, exp_name, use_last_checkpoint=False, labels=None, cm_cmap=plt.cm.Blues): self.num_class = num_class train_log_path, val_log_path = os.path.join(log_dir_name, exp_name, "train"), os.path.join(log_dir_name, exp_name, "val") if not use_last_checkpoint: if os.path.exists(train_log_path): shutil.rmtree(train_log_path) if os.path.exists(val_log_path): shutil.rmtree(val_log_path) self.writer = { 'train': SummaryWriter(log_dir=train_log_path, comment='Train Summary', flush_secs=30), 'val': SummaryWriter(log_dir=val_log_path, comment='Val Summary', flush_secs=30) } self.curr_iter = 1 self.cm_cmap = cm_cmap self.labels = self.beautify_labels(labels) self.logger = logging.getLogger() file_handler = logging.FileHandler("{0}/{1}.log".format(os.path.join(log_dir_name, exp_name), "console_logs")) # console_handler = logging.StreamHandler() self.logger.addHandler(file_handler) # self.logger.addHandler(console_handler) def log(self, text, phase='train'): self.logger.info(text) def loss_per_iter(self, loss_value, i_batch, current_iteration): self.log('[Iteration : ' + str(i_batch) + '] Loss -> ' + str(loss_value)) self.writer['train'].add_scalar('loss/per_iteration', loss_value, current_iteration) def loss_per_epoch(self, loss_arr, phase, epoch): if phase == 'train': loss = loss_arr[-1] else: loss = np.mean(loss_arr) self.writer[phase].add_scalar('loss/per_epoch', loss, epoch) self.log('epoch ' + phase + ' loss = ' + str(loss)) return loss def cm_per_epoch(self, phase, output, correct_labels, epoch): self.log("Confusion Matrix...") _, cm = eu.dice_confusion_matrix(output, correct_labels, self.num_class, mode='train') self.plot_cm('confusion_matrix', phase, cm, epoch) self.log("DONE") def plot_cm(self, caption, phase, cm, step=None): fig = matplotlib.figure.Figure(figsize=(8, 8), dpi=180, facecolor='w', edgecolor='k') ax = fig.add_subplot(1, 1, 1) ax.imshow(cm, interpolation='nearest', cmap=self.cm_cmap) ax.set_xlabel('Predicted', fontsize=7) ax.set_xticks(np.arange(self.num_class)) c = ax.set_xticklabels(self.labels, fontsize=4, rotation=-90, ha='center') ax.xaxis.set_label_position('bottom') ax.xaxis.tick_bottom() ax.set_ylabel('True Label', fontsize=7) ax.set_yticks(np.arange(self.num_class)) ax.set_yticklabels(self.labels, fontsize=4, va='center') ax.yaxis.set_label_position('left') ax.yaxis.tick_left() thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): ax.text(j, i, format(cm[i, j], '.2f') if cm[i, j] != 0 else '.', horizontalalignment="center", fontsize=6, verticalalignment='center', color="white" if cm[i, j] > thresh else "black") fig.set_tight_layout(True) np.set_printoptions(precision=2) if step: self.writer[phase].add_figure(caption + '/' + phase, fig, step) else: self.writer[phase].add_figure(caption + '/' + phase, fig) def dice_score_per_epoch(self, phase, output, correct_labels, epoch): self.log("Dice Score...") # TODO: multiclass vs binary ds = eu.dice_score_binary(output, correct_labels, self.num_class, phase) self.log('Dice score is ' + str(ds)) # self.plot_dice_score(phase, 'dice_score_per_epoch', ds, 'Dice Score', epoch) self.log("DONE") return ds def dice_score_per_epoch_segmentor(self, phase, output, correct_labels, epoch): self.log("Dice Score...") # TODO: multiclass vs binary ds = eu.dice_score_perclass(output, correct_labels, self.num_class, mode=phase) ds_mean = torch.mean(ds[1:]) self.log('Dice score is ' + str(ds)) self.log('Dice score mean ' + str(ds_mean)) self.plot_dice_score(phase, 'dice_score_per_epoch', ds, 'Dice Score', epoch) self.log("DONE") return ds_mean def plot_dice_score(self, phase, caption, ds, title, step=None): fig = matplotlib.figure.Figure(figsize=(8, 6), dpi=180, facecolor='w', edgecolor='k') ax = fig.add_subplot(1, 1, 1) ax.set_xlabel(title, fontsize=10) ax.xaxis.set_label_position('top') ax.bar(np.arange(self.num_class), ds) ax.set_xticks(np.arange(self.num_class)) c = ax.set_xticklabels(self.labels, fontsize=6, rotation=-90, ha='center') ax.xaxis.tick_bottom() if step: self.writer[phase].add_figure(caption + '/' + phase, fig, step) else: self.writer[phase].add_figure(caption + '/' + phase, fig) def plot_eval_box_plot(self, caption, class_dist, title): fig = matplotlib.figure.Figure(figsize=(8, 6), dpi=180, facecolor='w', edgecolor='k') ax = fig.add_subplot(1, 1, 1) ax.set_xlabel(title, fontsize=10) ax.xaxis.set_label_position('top') ax.boxplot(class_dist) ax.set_xticks(np.arange(self.num_class)) c = ax.set_xticklabels(self.labels, fontsize=6, rotation=-90, ha='center') ax.xaxis.tick_bottom() self.writer['val'].add_figure(caption, fig) def image_per_epoch_segmentor(self, prediction, ground_truth, phase, epoch): self.log("Sample Images...") ncols = 2 nrows = len(prediction) fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(10, 20)) for i in range(nrows): ax[i][0].imshow(torch.squeeze(ground_truth[i]), cmap='CMRmap', vmin=0, vmax=self.num_class - 1) ax[i][0].set_title("Ground Truth", fontsize=10, color="blue") ax[i][0].axis('off') ax[i][1].imshow(torch.squeeze(prediction[i]), cmap='CMRmap', vmin=0, vmax=self.num_class - 1) ax[i][1].set_title("Predicted", fontsize=10, color="blue") ax[i][1].axis('off') fig.set_tight_layout(True) self.writer[phase].add_figure('sample_prediction/' + phase, fig, epoch) self.log('DONE') def image_per_epoch(self, prediction, ground_truth, phase, epoch, additional_image=None): self.log("Sample Images...") ncols = 3 nrows = len(prediction) fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(10, 20)) for i in range(nrows): ax[i][0].imshow(additional_image[i].squeeze().transpose(0,2).cpu(), cmap='gray', vmin=0, vmax=5) ax[i][0].set_title("Input Image", fontsize=10, color="blue") ax[i][0].axis('off') ax[i][1].imshow(ground_truth[i].squeeze(), cmap='jet', vmin=0, vmax=5) ax[i][1].set_title("Ground Truth", fontsize=10, color="blue") ax[i][1].axis('off') ax[i][2].imshow(prediction[i].squeeze(), cmap='jet', vmin=0, vmax=5) ax[i][2].set_title("Predicted", fontsize=10, color="blue") ax[i][2].axis('off') fig.set_tight_layout(True) self.writer[phase].add_figure('sample_prediction/' + phase, fig, epoch) self.log('DONE') def graph(self, model, X): self.writer['train'].add_graph(model, X) def close(self): self.writer['train'].close() self.writer['val'].close() def beautify_labels(self, labels): classes = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in labels] classes = ['\n'.join(wrap(l, 40)) for l in classes] return classes
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/evaluator_kshot.py
.py
30,640
592
import os import nibabel as nib import numpy as np import torch import utils.common_utils as common_utils import utils.data_utils as du import torch.nn.functional as F import shot_batch_sampler as SB def dice_score_binary(vol_output, ground_truth, no_samples=10, phase='train'): ground_truth = ground_truth.type(torch.FloatTensor) vol_output = vol_output.type(torch.FloatTensor) if phase == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] inter = 2 * torch.sum(torch.mul(ground_truth, vol_output)) union = torch.sum(ground_truth) + torch.sum(vol_output) + 0.0001 return torch.div(inter, union) def dice_confusion_matrix(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_cm = torch.zeros(num_classes, num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() for j in range(num_classes): Pred = (vol_output == j).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_cm[i, j] = 2 * torch.div(inter, union) avg_dice = torch.mean(torch.diagflat(dice_cm)) return avg_dice, dice_cm def get_range(volume): batch, _, _ = volume.size() slice_with_class = torch.sum(volume.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) return range_index def dice_score_perclass(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_perclass = torch.zeros(num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() Pred = (vol_output == i).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_perclass[i] = (2 * torch.div(inter, union)) return dice_perclass def binarize_label(volume, groud_truth, class_label): groud_truth = (groud_truth == class_label).type(torch.FloatTensor) batch, _, _ = groud_truth.size() slice_with_class = torch.sum(groud_truth.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) # groud_truth = groud_truth[slice_with_class] # volume = volume[slice_with_class] condition_input = torch.cat((volume, groud_truth.unsqueeze(1)), dim=1) return condition_input, range_index.cpu().numpy() def evaluate_dice_score(model_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model_path) batch_size = 20 Num_support = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model = torch.load(model_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model.cuda(device) model.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] # Loading support support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], orientation=orientation, remap_config=remap_config) support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), \ torch.tensor(support_labelmap).type(torch.LongTensor) support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) # # Save Input nifti_img = nib.MGHImage(np.squeeze(support_volume[:, 0, :, :].cpu().numpy()), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, 'SupportInput_' + str('.mgz'))) nifti_img = nib.MGHImage(np.squeeze(support_volume[:, 1, :, :].cpu().numpy()), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, 'SupportGT_' + str('.mgz'))) print("Saved") slice_gap_support = int(np.ceil(len(support_volume) / Num_support)) support_slice_indexes = [i for i in range(0, len(support_volume), slice_gap_support)] if len(support_slice_indexes) < Num_support: support_slice_indexes.append(len(support_volume) - 1) for vol_idx, file_path in enumerate(query_file_paths): query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, remap_config=remap_config) query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), \ torch.tensor(query_labelmap).type(torch.LongTensor) query_labelmap = query_labelmap == query_label range_query = get_range(query_labelmap) query_volume = query_volume[range_query[0]: range_query[1] + 1] query_labelmap = query_labelmap[range_query[0]: range_query[1] + 1] dice_per_slice = [] vol_output = [] for support_slice_idx in support_slice_indexes: batch_output = [] for i in range(0, len(query_volume), batch_size): query_batch_x = query_volume[i: i + batch_size] support_batch_x = support_volume[support_slice_idx].repeat(query_batch_x.size()[0], 1, 1, 1) if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model.conditioner(support_batch_x) out = model.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) batch_output.append(out) batch_output = torch.cat(batch_output) vol_output.append(batch_output) vol_output = torch.stack(vol_output) vol_output = torch.mean(vol_output, dim=0) _, vol_output = torch.max(F.softmax(vol_output, dim=1), dim=1) # for i, query_slice in enumerate(query_volume): # query_batch_x = query_slice.unsqueeze(0) # max_dice = -1.0 # max_output = None # for j in range(0, len(support_volume), 5): # support_slice = support_volume[j] # # support_batch_x = support_slice.unsqueeze(0) # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # slice_dice_score = dice_score_binary(batch_output, # query_labelmap[i].cuda(device), phase=mode) # if slice_dice_score.item() >= max_dice: # max_dice = slice_dice_score.item() # max_output = batch_output # # dice_per_slice.append(max_dice) # vol_output.append(max_output) # # vol_output = torch.cat(vol_output) # volume_dice_score = np.mean(np.asarray(dice_per_slice)) volume_dice_score = dice_score_binary(vol_output, query_labelmap.cuda(device), phase=mode) volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_2view(model1_path, model2_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model1.eval() model2.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label query_labelmap2 = query_labelmap2 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction = 0.5 * volume_prediction1 + 0.5 * volume_prediction2.permute(3, 1, 0, 2) _, batch_output = torch.max(F.softmax(volume_prediction, dim=1), dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_3view(model1_path, model2_path, model3_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) model3 = torch.load(model3_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model3.cuda(device) model1.eval() model2.eval() model3.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume3, support_labelmap3 = support_volume1.transpose((2, 0, 1)), support_labelmap1.transpose( (2, 0, 1)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume3 = support_volume3 if len(support_volume3.shape) == 4 else support_volume3[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume3, support_labelmap3 = torch.tensor(support_volume3).type( torch.FloatTensor), torch.tensor( support_labelmap3).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) support_volume3 = binarize_label(support_volume3, support_labelmap3, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume3, query_labelmap3 = query_volume1.transpose((2, 0, 1)), query_labelmap1.transpose( (2, 0, 1)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume3 = query_volume3 if len(query_volume3.shape) == 4 else query_volume3[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_volume3, query_labelmap3 = torch.tensor(query_volume3).type(torch.FloatTensor), torch.tensor( query_labelmap3).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label # query_labelmap2 = query_labelmap2 == query_label # query_labelmap3 = query_labelmap3 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) # Evaluate for orientation 3 support_batch_x = [] k = 2 volume_prediction3 = [] for i in range(0, len(query_volume3), batch_size): query_batch_x = query_volume3[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume3[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model3.conditioner(support_batch_x) out = model3.segmentor(query_batch_x, weights) volume_prediction3.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction3 = torch.cat(volume_prediction3) volume_prediction = 0.33 * F.softmax(volume_prediction1, dim=1) + 0.33 * F.softmax( volume_prediction2.permute(3, 1, 0, 2), dim=1) + 0.33 * F.softmax( volume_prediction3.permute(2, 1, 3, 0), dim=1) _, batch_output = torch.max(volume_prediction, dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/evaluator_slow.py
.py
28,985
565
import os import nibabel as nib import numpy as np import torch import utils.common_utils as common_utils import utils.data_utils as du import torch.nn.functional as F import shot_batch_sampler as SB def dice_score_binary(vol_output, ground_truth, no_samples=10, phase='train'): ground_truth = ground_truth.type(torch.FloatTensor) vol_output = vol_output.type(torch.FloatTensor) if phase == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] inter = 2 * torch.sum(torch.mul(ground_truth, vol_output)) union = torch.sum(ground_truth) + torch.sum(vol_output) + 0.0001 return torch.div(inter, union) def dice_confusion_matrix(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_cm = torch.zeros(num_classes, num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() for j in range(num_classes): Pred = (vol_output == j).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_cm[i, j] = 2 * torch.div(inter, union) avg_dice = torch.mean(torch.diagflat(dice_cm)) return avg_dice, dice_cm def get_range(volume): batch, _, _ = volume.size() slice_with_class = torch.sum(volume.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) return range_index def dice_score_perclass(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_perclass = torch.zeros(num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() Pred = (vol_output == i).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_perclass[i] = (2 * torch.div(inter, union)) return dice_perclass def binarize_label(volume, groud_truth, class_label): groud_truth = (groud_truth == class_label).type(torch.FloatTensor) batch, _, _ = groud_truth.size() slice_with_class = torch.sum(groud_truth.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) groud_truth = groud_truth[slice_with_class] volume = volume[slice_with_class] condition_input = torch.cat((volume, groud_truth.unsqueeze(1)), dim=1) return condition_input, range_index.cpu().numpy() def evaluate_dice_score(model_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model_path) batch_size = 20 Num_support = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model = torch.load(model_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model.cuda(device) model.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] # Loading support support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], orientation=orientation, remap_config=remap_config) support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), \ torch.tensor(support_labelmap).type(torch.LongTensor) support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) # slice_gap_support = int(np.ceil(len(support_volume) / Num_support)) # # support_slice_indexes = [i for i in range(0, len(support_volume), slice_gap_support)] # # if len(support_slice_indexes) < Num_support: # support_slice_indexes.append(len(support_volume) - 1) for vol_idx, file_path in enumerate(query_file_paths): query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, remap_config=remap_config) query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), \ torch.tensor(query_labelmap).type(torch.LongTensor) query_labelmap = query_labelmap == query_label range_query = get_range(query_labelmap) query_volume = query_volume[range_query[0]: range_query[1] + 1] query_labelmap = query_labelmap[range_query[0]: range_query[1] + 1] dice_per_slice = [] vol_output = [] for i, query_slice in enumerate(query_volume): query_batch_x = query_slice.unsqueeze(0) max_dice = -1.0 max_output = None for j in range(0, len(support_volume), 10): support_slice = support_volume[j] support_batch_x = support_slice.unsqueeze(0) if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model.conditioner(support_batch_x) out = model.segmentor(query_batch_x, weights) _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) slice_dice_score = dice_score_binary(batch_output, query_labelmap[i].cuda(device), phase=mode) dice_per_slice.append(slice_dice_score.item()) if slice_dice_score.item() >= max_dice: max_dice = slice_dice_score.item() max_output = batch_output # dice_per_slice.append(max_dice) vol_output.append(max_output) vol_output = torch.cat(vol_output) volume_dice_score = dice_score_binary(vol_output, query_labelmap.cuda(device), phase=mode) volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_2view(model1_path, model2_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model1.eval() model2.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label query_labelmap2 = query_labelmap2 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction = 0.5 * volume_prediction1 + 0.5 * volume_prediction2.permute(3, 1, 0, 2) _, batch_output = torch.max(F.softmax(volume_prediction, dim=1), dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_3view(model1_path, model2_path, model3_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) model3 = torch.load(model3_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model3.cuda(device) model1.eval() model2.eval() model3.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume3, support_labelmap3 = support_volume1.transpose((2, 0, 1)), support_labelmap1.transpose( (2, 0, 1)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume3 = support_volume3 if len(support_volume3.shape) == 4 else support_volume3[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume3, support_labelmap3 = torch.tensor(support_volume3).type( torch.FloatTensor), torch.tensor( support_labelmap3).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) support_volume3 = binarize_label(support_volume3, support_labelmap3, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume3, query_labelmap3 = query_volume1.transpose((2, 0, 1)), query_labelmap1.transpose( (2, 0, 1)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume3 = query_volume3 if len(query_volume3.shape) == 4 else query_volume3[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_volume3, query_labelmap3 = torch.tensor(query_volume3).type(torch.FloatTensor), torch.tensor( query_labelmap3).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label # query_labelmap2 = query_labelmap2 == query_label # query_labelmap3 = query_labelmap3 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) # Evaluate for orientation 3 support_batch_x = [] k = 2 volume_prediction3 = [] for i in range(0, len(query_volume3), batch_size): query_batch_x = query_volume3[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume3[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model3.conditioner(support_batch_x) out = model3.segmentor(query_batch_x, weights) volume_prediction3.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction3 = torch.cat(volume_prediction3) volume_prediction = 0.33 * F.softmax(volume_prediction1, dim=1) + 0.33 * F.softmax( volume_prediction2.permute(3, 1, 0, 2), dim=1) + 0.33 * F.softmax( volume_prediction3.permute(2, 1, 3, 0), dim=1) _, batch_output = torch.max(volume_prediction, dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/evaluator.py
.py
38,938
735
import os import nibabel as nib import numpy as np import torch import utils.common_utils as common_utils import utils.data_utils as du import torch.nn.functional as F def dice_score_binary(vol_output, ground_truth, no_samples=10, phase='train'): ground_truth = ground_truth.type(torch.FloatTensor) vol_output = vol_output.type(torch.FloatTensor) if phase == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] inter = 2 * torch.sum(torch.mul(ground_truth, vol_output)) union = torch.sum(ground_truth) + torch.sum(vol_output) + 0.0001 return torch.div(inter, union) def dice_confusion_matrix(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_cm = torch.zeros(num_classes, num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() for j in range(num_classes): Pred = (vol_output == j).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_cm[i, j] = 2 * torch.div(inter, union) avg_dice = torch.mean(torch.diagflat(dice_cm)) return avg_dice, dice_cm def get_range(volume): batch, _, _ = volume.size() slice_with_class = torch.sum(volume.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) return range_index def dice_score_perclass(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_perclass = torch.zeros(num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() Pred = (vol_output == i).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_perclass[i] = (2 * torch.div(inter, union)) return dice_perclass def binarize_label(volume, groud_truth, class_label): groud_truth = (groud_truth == class_label).type(torch.FloatTensor) batch, _, _ = groud_truth.size() slice_with_class = torch.sum(groud_truth.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) groud_truth = groud_truth[slice_with_class] volume = volume[slice_with_class] condition_input = torch.cat((volume, groud_truth.unsqueeze(1)), dim=1) return condition_input, range_index.cpu().numpy() def evaluate_dice_score(model_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model_path) batch_size = 20 Num_support = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model = torch.load(model_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model.cuda(device) model.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] # # support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], # orientation=orientation, # remap_config=remap_config) # # support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] # # support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), torch.tensor( # support_labelmap).type(torch.LongTensor) # support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) # support_volume = support_volume[range_index[0]: range_index[1]] # Loading support support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], orientation=orientation, remap_config=remap_config) support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), \ torch.tensor(support_labelmap).type(torch.LongTensor) support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) support_slice_indexes = np.round(np.linspace(0, len(support_volume) - 1, Num_support + 1)).astype(int) support_slice_indexes += (len(support_volume) // Num_support) // 2 support_slice_indexes = support_slice_indexes[:-1] # support_slice_indexes[0] += (len(support_volume) // Num_support) // 2 # if len(support_slice_indexes) > 1: # support_slice_indexes[-1] -= (len(support_volume) // Num_support) // 2 if len(support_slice_indexes) < Num_support: support_slice_indexes.append(len(support_volume) - 1) # batch_needed = Num_support < 5 for vol_idx, file_path in enumerate(query_file_paths): query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, remap_config=remap_config) query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), \ torch.tensor(query_labelmap).type(torch.LongTensor) query_labelmap = query_labelmap == query_label range_query = get_range(query_labelmap) query_volume = query_volume[range_query[0]: range_query[1] + 1] query_labelmap = query_labelmap[range_query[0]: range_query[1] + 1] query_slice_indexes = np.round(np.linspace(0, len(query_volume) - 1, Num_support)).astype(int) if len(query_slice_indexes) < Num_support: query_slice_indexes.append(len(query_volume) - 1) volume_prediction = [] # for i in range(0, len(query_volume), batch_size): # support_current_slice = 0 # query_current_slice = 0 for i, query_start_slice in enumerate(query_slice_indexes): if query_start_slice == query_slice_indexes[-1]: query_batch_x = query_volume[query_slice_indexes[i]:] else: query_batch_x = query_volume[query_slice_indexes[i]:query_slice_indexes[i + 1]] support_batch_x = support_volume[support_slice_indexes[i]] # Running larger blocks in smaller batches # if batch_needed: volume_prediction_10 = [] for b in range(0, len(query_batch_x), 10): query_batch_x_10 = query_batch_x[b:b + 10] support_batch_x_10 = support_batch_x.repeat(len(query_batch_x_10), 1, 1, 1) if cuda_available: query_batch_x_10 = query_batch_x_10.cuda(device) support_batch_x_10 = support_batch_x_10.cuda(device) weights_10 = model.conditioner(support_batch_x_10) out_10 = model.segmentor(query_batch_x_10, weights_10) # For shaban et al # batch_output_10 = out_10 > 0.5 # batch_output_10 = batch_output_10.squeeze() # For others _, batch_output_10 = torch.max(F.softmax(out_10, dim=1), dim=1) volume_prediction_10.append(batch_output_10) volume_prediction.extend(volume_prediction_10) # else: # support_batch_x = support_batch_x.repeat(len(query_batch_x), 1, 1, 1) # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice += slice_gap_query # support_current_slice += slice_gap_support # query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, # remap_config=remap_config) # query_labelmap = query_labelmap == query_label # range_query = get_range(query_labelmap) # query_volume = query_volume[range_query[0]: range_query[1]] # # query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] # query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), torch.tensor( # query_labelmap).type(torch.LongTensor) # # support_batch_x = [] # # volume_prediction = [] # # support_current_slice = 0 # query_current_slice = 0 # support_slice_left = support_volume[range_index[0]] # for i in range(0, range_index[0], batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < range_index[0] else range_index[0] # # query_batch_x = query_volume[i: end_index_query] # # support_batch_x = support_slice_left.repeat(query_batch_x.size()[0], 1, 1, 1) # # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice = end_index_query # support_current_slice = query_current_slice # # for i in range(range_index[0], range_index[1] + 1, batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < range_index[1] + 1 else range_index[1] + 1 # # query_batch_x = query_volume[i: end_index_query] # # # end_index_support = support_current_slice + batch_size # # end_index_support = end_index_support if end_index_support < len(range_index[1] + 1) else len( # # range_index[1] + 1) # # print(len(support_volume)) # # print(support_current_slice, end_index_query) # support_batch_x = support_volume[support_current_slice: end_index_query] # # query_current_slice = end_index_query # support_current_slice = query_current_slice # # support_batch_x = support_batch_x[0].repeat(query_batch_x.size()[0], 1, 1, 1) # # # k += 1 # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # # support_slice_right = support_volume[range_index[1]] # for i in range(range_index[1] + 1, len(support_volume), batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < len(support_volume) else len(support_volume) # # query_batch_x = query_volume[i: end_index_query] # # support_batch_x = support_slice_right.repeat(query_batch_x.size()[0], 1, 1, 1) # # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice = end_index_query # support_current_slice = query_current_slice volume_prediction = torch.cat(volume_prediction) # volume_prediction = volume_prediction.squeeze() # batch, _, _ = query_labelmap.size() # slice_with_class = torch.sum(query_labelmap.view(batch, -1), dim=1) > 10 # index = slice_with_class[:-1] - slice_with_class[1:] > 0 # seq = torch.Tensor(range(batch - 1)) # range_index_gt = seq[index].type(torch.LongTensor) volume_dice_score = dice_score_binary(volume_prediction[:len(query_labelmap)], query_labelmap.cuda(device), phase=mode) volume_prediction = (volume_prediction.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(volume_prediction), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # # # Save Input nifti_img = nib.MGHImage(np.squeeze(query_volume.cpu().numpy()), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input nifti_img = nib.MGHImage(np.squeeze(support_volume.cpu().numpy()), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # Cond GT nifti_img = nib.MGHImage(np.squeeze(support_labelmap.cpu().numpy()).astype('float32'), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # Save Ground Truth nifti_img = nib.MGHImage(np.squeeze(query_labelmap.cpu().numpy()), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + fold + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.item() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) print(volume_dice_score_list) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_2view(model1_path, model2_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model1.eval() model2.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label query_labelmap2 = query_labelmap2 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction = 0.5 * volume_prediction1 + 0.5 * volume_prediction2.permute(3, 1, 0, 2) _, batch_output = torch.max(F.softmax(volume_prediction, dim=1), dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_3view(model1_path, model2_path, model3_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) model3 = torch.load(model3_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model3.cuda(device) model1.eval() model2.eval() model3.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume3, support_labelmap3 = support_volume1.transpose((2, 0, 1)), support_labelmap1.transpose( (2, 0, 1)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume3 = support_volume3 if len(support_volume3.shape) == 4 else support_volume3[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume3, support_labelmap3 = torch.tensor(support_volume3).type( torch.FloatTensor), torch.tensor( support_labelmap3).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) support_volume3 = binarize_label(support_volume3, support_labelmap3, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume3, query_labelmap3 = query_volume1.transpose((2, 0, 1)), query_labelmap1.transpose( (2, 0, 1)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume3 = query_volume3 if len(query_volume3.shape) == 4 else query_volume3[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_volume3, query_labelmap3 = torch.tensor(query_volume3).type(torch.FloatTensor), torch.tensor( query_labelmap3).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label # query_labelmap2 = query_labelmap2 == query_label # query_labelmap3 = query_labelmap3 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) # Evaluate for orientation 3 support_batch_x = [] k = 2 volume_prediction3 = [] for i in range(0, len(query_volume3), batch_size): query_batch_x = query_volume3[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume3[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model3.conditioner(support_batch_x) out = model3.segmentor(query_batch_x, weights) volume_prediction3.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction3 = torch.cat(volume_prediction3) volume_prediction = 0.33 * F.softmax(volume_prediction1, dim=1) + 0.33 * F.softmax( volume_prediction2.permute(3, 1, 0, 2), dim=1) + 0.33 * F.softmax( volume_prediction3.permute(2, 1, 3, 0), dim=1) _, batch_output = torch.max(volume_prediction, dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/shot_batch_sampler.py
.py
2,744
89
import numpy as np lab_list_fold = {"fold1": {"train": [2, 6, 7, 8, 9], "val": [1]}, "fold2": {"train": [1, 6, 7, 8, 9], "val": [2]}, "fold3": {"train": [1, 2, 8, 9], "val": [6, 7]}, "fold4": {"train": [1, 2, 6, 7], "val": [8, 9]}} def get_lab_list(phase, fold): return lab_list_fold[fold][phase] # def get_class_slices(labels, i): num_slices, H, W = labels.shape thresh = 0.005 total_slices = labels == i pixel_sum = np.sum(total_slices, axis=(1, 2)).squeeze() pixel_sum = pixel_sum / (H * W) threshold_list = [idx for idx, slice in enumerate( pixel_sum) if slice > thresh] return threshold_list def get_index_dict(labels, lab_list): index_list = {i: get_class_slices(labels, i) for i in lab_list} p = [1 - (len(val) / len(labels)) for val in index_list.values()] p = p / np.sum(p) return index_list, p class OneShotBatchSampler: ''' ''' def _gen_query_label(self): """ Returns a query label uniformly from the label list of current phase. Also returns indexes of the slices which contain that label :return: random query label, index list of slices with generated class available """ query_label = np.random.choice(self.lab_list, 1, p=self.p)[0] return query_label def __init__(self, labels, phase, fold, batch_size, iteration=500): ''' ''' super(OneShotBatchSampler, self).__init__() self.index_list = None self.query_label = None self.batch_size = batch_size self.iteration = iteration self.labels = labels self.phase = phase self.lab_list = get_lab_list(phase, fold) self.index_dict, self.p = get_index_dict(labels, self.lab_list) def __iter__(self): ''' yield a batch of indexes ''' self.n = 0 return self def __next__(self): """ Called on each iteration to return slices a random class label. On each iteration gets a random class label from label list and selects 2 x batch_size slices uniformly from index list :return: randomly select 2 x batch_size slices of a class label for the given iteration """ if self.n > self.iteration: raise StopIteration self.query_label = self._gen_query_label() self.index_list = self.index_dict[self.query_label] batch = np.random.choice(self.index_list, size=2 * self.batch_size) self.n += 1 return batch def __len__(self): """ returns the number of iterations (episodes) per epoch :return: number os iterations """ return self.iteration
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/data_utils.py
.py
7,914
195
import os import h5py import numpy as np import torch import torch.utils.data as data import scipy.io as sio import utils.preprocessor as preprocessor import nibabel as nb import math from torchvision import transforms # import utils.preprocessor as preprocessor # transform_train = transforms.Compose([ # transforms.RandomCrop((480, 220), padding=(32, 36)), # transforms.ToTensor(), # ]) class ImdbData(data.Dataset): def __init__(self, X, y, w=None, transforms=None): # TODO:Improve later # lung_mask_1 = (y == 4) # lung_mask_2 = (y == 5) # lung_mask = 0.5 * (lung_mask_1 + lung_mask_2) # X = X + lung_mask self.X = X if len(X.shape) == 4 else X[:, np.newaxis, :, :] self.y = y self.w = w self.transforms = transforms def __getitem__(self, index): img = torch.from_numpy(self.X[index]) label = torch.from_numpy(self.y[index]) if self.w is not None: weight = torch.from_numpy(self.w[index]) return img, label, weight else: return img, label def __len__(self): return len(self.y) def get_imdb_dataset(data_params): data_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_data_file']), 'r') label_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_label_file']), 'r') class_weight_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_class_weights_file']), 'r') weight_train = h5py.File(os.path.join(data_params['data_dir'], data_params['train_weights_file']), 'r') data_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_data_file']), 'r') label_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_label_file']), 'r') class_weight_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_class_weights_file']), 'r') weight_test = h5py.File(os.path.join(data_params['data_dir'], data_params['test_weights_file']), 'r') return (ImdbData(data_train['data'][()], label_train['label'][()], class_weight_train['class_weights'][()]), ImdbData(data_test['data'][()], label_test['label'][()], class_weight_test['class_weights'][()])) def load_dataset(file_paths, orientation, remap_config, return_weights=False, reduce_slices=False, remove_black=False): print("Loading and preprocessing data...") volume_list, labelmap_list, headers, class_weights_list, weights_list = [], [], [], [], [] for file_path in file_paths: volume, labelmap, class_weights, weights = load_and_preprocess(file_path, orientation, remap_config=remap_config, reduce_slices=reduce_slices, remove_black=remove_black, return_weights=return_weights) volume_list.append(volume) labelmap_list.append(labelmap) if return_weights: class_weights_list.append(class_weights) weights_list.append(weights) print("#", end='', flush=True) print("100%", flush=True) if return_weights: return volume_list, labelmap_list, class_weights_list, weights_list else: return volume_list, labelmap_list def load_and_preprocess(file_path, orientation, remap_config, reduce_slices=False, remove_black=False, return_weights=False): print(file_path) volume, labelmap = load_data_mat(file_path, orientation) volume, labelmap, class_weights, weights = preprocess(volume, labelmap, remap_config=remap_config, reduce_slices=reduce_slices, remove_black=remove_black, return_weights=return_weights) return volume, labelmap, class_weights, weights def load_data(file_path, orientation): print(file_path[0], file_path[1]) volume_nifty, labelmap_nifty = nb.load(file_path[0]), nb.load(file_path[1]) volume, labelmap = volume_nifty.get_fdata(), labelmap_nifty.get_fdata() volume = (volume - np.min(volume)) / (np.max(volume) - np.min(volume)) volume, labelmap = preprocessor.rotate_orientation(volume, labelmap, orientation) return volume, labelmap, volume_nifty.header def load_data_mat(file_path, orientation): data = sio.loadmat(file_path) volume = data['DatVol'] labelmap = data['LabVol'] volume = (volume - np.min(volume)) / (np.max(volume) - np.min(volume)) volume, labelmap = preprocessor.rotate_orientation(volume, labelmap, orientation) return volume, labelmap def preprocess(volume, labelmap, remap_config, reduce_slices=False, remove_black=False, return_weights=False): if reduce_slices: volume, labelmap = preprocessor.reduce_slices(volume, labelmap) if remap_config: labelmap = preprocessor.remap_labels(labelmap, remap_config) if remove_black: volume, labelmap = preprocessor.remove_black(volume, labelmap) if return_weights: class_weights, weights = preprocessor.estimate_weights_mfb(labelmap) return volume, labelmap, class_weights, weights else: return volume, labelmap, None, None def load_file_paths_brain(data_dir, label_dir, volumes_txt_file=None): """ This function returns the file paths combined as a list where each element is a 2 element tuple, 0th being data and 1st being label. It should be modified to suit the need of the project :param data_dir: Directory which contains the data files :param label_dir: Directory which contains the label files :param volumes_txt_file: (Optional) Path to the a csv file, when provided only these data points will be read :return: list of file paths as string """ volume_exclude_list = ['IXI290', 'IXI423'] if volumes_txt_file: with open(volumes_txt_file) as file_handle: volumes_to_use = file_handle.read().splitlines() else: volumes_to_use = [name for name in os.listdir(data_dir) if name not in volume_exclude_list] file_paths = [ [os.path.join(data_dir, vol, 'mri/orig.mgz'), os.path.join(label_dir, vol+'_glm.mgz')] for vol in volumes_to_use] return file_paths def load_file_paths(data_dir, label_dir, volumes_txt_file=None): """ This function returns the file paths combined as a list where each element is a 2 element tuple, 0th being data and 1st being label. It should be modified to suit the need of the project :param data_dir: Directory which contains the data files :param label_dir: Directory which contains the label files :param volumes_txt_file: (Optional) Path to the a csv file, when provided only these data points will be read :return: list of file paths as string """ with open(volumes_txt_file) as file_handle: volumes_to_use = file_handle.read().splitlines() file_paths = [os.path.join(data_dir, vol) for vol in volumes_to_use] return file_paths def split_batch(X, y, query_label): batch_size = len(X) // 2 input1 = X[0:batch_size, :, :, :] input2 = X[batch_size:, :, :, :] y1 = (y[0:batch_size, :, :] == query_label).type(torch.FloatTensor) y2 = (y[batch_size:, :, :] == query_label).type(torch.LongTensor) # y2 = (y[batch_size:, :, :] == query_label).type(torch.FloatTensor) # y2 = y2.unsqueeze(1) # Why? # input1 = torch.cat([input1, y1.unsqueeze(1)], dim=1) return input1, input2, y1, y2
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/utils/evaluator_finetuning.py
.py
38,979
735
import os import nibabel as nib import numpy as np import torch import utils.common_utils as common_utils import utils.data_utils as du import torch.nn.functional as F def dice_score_binary(vol_output, ground_truth, no_samples=10, phase='train'): ground_truth = ground_truth.type(torch.FloatTensor) vol_output = vol_output.type(torch.FloatTensor) if phase == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] inter = 2 * torch.sum(torch.mul(ground_truth, vol_output)) union = torch.sum(ground_truth) + torch.sum(vol_output) + 0.0001 return torch.div(inter, union) def dice_confusion_matrix(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_cm = torch.zeros(num_classes, num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() for j in range(num_classes): Pred = (vol_output == j).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_cm[i, j] = 2 * torch.div(inter, union) avg_dice = torch.mean(torch.diagflat(dice_cm)) return avg_dice, dice_cm def get_range(volume): batch, _, _ = volume.size() slice_with_class = torch.sum(volume.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) return range_index def dice_score_perclass(vol_output, ground_truth, num_classes, no_samples=10, mode='train'): dice_perclass = torch.zeros(num_classes) if mode == 'train': samples = np.random.choice(len(vol_output), no_samples) vol_output, ground_truth = vol_output[samples], ground_truth[samples] for i in range(num_classes): GT = (ground_truth == i).float() Pred = (vol_output == i).float() inter = torch.sum(torch.mul(GT, Pred)) union = torch.sum(GT) + torch.sum(Pred) + 0.0001 dice_perclass[i] = (2 * torch.div(inter, union)) return dice_perclass def binarize_label(volume, groud_truth, class_label): groud_truth = (groud_truth == class_label).type(torch.FloatTensor) batch, _, _ = groud_truth.size() slice_with_class = torch.sum(groud_truth.view(batch, -1), dim=1) > 10 index = slice_with_class[:-1] - slice_with_class[1:] > 0 seq = torch.Tensor(range(batch - 1)) range_index = seq[index].type(torch.LongTensor) groud_truth = groud_truth[slice_with_class] volume = volume[slice_with_class] condition_input = torch.cat((volume, groud_truth.unsqueeze(1)), dim=1) return condition_input, range_index.cpu().numpy() def evaluate_dice_score(model_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model_path) batch_size = 20 Num_support = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model = torch.load(model_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model.cuda(device) model.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] # # support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], # orientation=orientation, # remap_config=remap_config) # # support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, :] # # support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), torch.tensor( # support_labelmap).type(torch.LongTensor) # support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) # support_volume = support_volume[range_index[0]: range_index[1]] # Loading support # support_volume, support_labelmap, _, _ = du.load_and_preprocess(support_file_paths[0], # orientation=orientation, # remap_config=remap_config) # support_volume = support_volume if len(support_volume.shape) == 4 else support_volume[:, np.newaxis, :, # :] # support_volume, support_labelmap = torch.tensor(support_volume).type(torch.FloatTensor), \ # torch.tensor(support_labelmap).type(torch.LongTensor) # support_volume, range_index = binarize_label(support_volume, support_labelmap, query_label) # # support_slice_indexes = np.round(np.linspace(0, len(support_volume) - 1, Num_support + 1)).astype(int) # support_slice_indexes += (len(support_volume) // Num_support) // 2 # support_slice_indexes = support_slice_indexes[:-1] # support_slice_indexes[0] += (len(support_volume) // Num_support) // 2 # if len(support_slice_indexes) > 1: # support_slice_indexes[-1] -= (len(support_volume) // Num_support) // 2 # if len(support_slice_indexes) < Num_support: # support_slice_indexes.append(len(support_volume) - 1) # batch_needed = Num_support < 5 for vol_idx, file_path in enumerate(query_file_paths): query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, remap_config=remap_config) query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), \ torch.tensor(query_labelmap).type(torch.LongTensor) query_labelmap = query_labelmap == query_label range_query = get_range(query_labelmap) query_volume = query_volume[range_query[0]: range_query[1] + 1] query_labelmap = query_labelmap[range_query[0]: range_query[1] + 1] query_slice_indexes = np.round(np.linspace(0, len(query_volume) - 1, Num_support)).astype(int) if len(query_slice_indexes) < Num_support: query_slice_indexes.append(len(query_volume) - 1) volume_prediction = [] # for i in range(0, len(query_volume), batch_size): # support_current_slice = 0 # query_current_slice = 0 for i, query_start_slice in enumerate(query_slice_indexes): if query_start_slice == query_slice_indexes[-1]: query_batch_x = query_volume[query_slice_indexes[i]:] else: query_batch_x = query_volume[query_slice_indexes[i]:query_slice_indexes[i + 1]] # support_batch_x = support_volume[support_slice_indexes[i]] # Running larger blocks in smaller batches # if batch_needed: volume_prediction_10 = [] for b in range(0, len(query_batch_x), 10): query_batch_x_10 = query_batch_x[b:b + 10] # support_batch_x_10 = support_batch_x.repeat(len(query_batch_x_10), 1, 1, 1) if cuda_available: query_batch_x_10 = query_batch_x_10.cuda(device) # support_batch_x_10 = support_batch_x_10.cuda(device) # weights_10 = model.conditioner(support_batch_x_10) out_10 = model(query_batch_x_10) # For shaban et al # batch_output_10 = out_10 > 0.5 # batch_output_10 = batch_output_10.squeeze() # For others _, batch_output_10 = torch.max(F.softmax(out_10, dim=1), dim=1) volume_prediction_10.append(batch_output_10) volume_prediction.extend(volume_prediction_10) # else: # support_batch_x = support_batch_x.repeat(len(query_batch_x), 1, 1, 1) # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice += slice_gap_query # support_current_slice += slice_gap_support # query_volume, query_labelmap, _, _ = du.load_and_preprocess(file_path, orientation=orientation, # remap_config=remap_config) # query_labelmap = query_labelmap == query_label # range_query = get_range(query_labelmap) # query_volume = query_volume[range_query[0]: range_query[1]] # # query_volume = query_volume if len(query_volume.shape) == 4 else query_volume[:, np.newaxis, :, :] # query_volume, query_labelmap = torch.tensor(query_volume).type(torch.FloatTensor), torch.tensor( # query_labelmap).type(torch.LongTensor) # # support_batch_x = [] # # volume_prediction = [] # # support_current_slice = 0 # query_current_slice = 0 # support_slice_left = support_volume[range_index[0]] # for i in range(0, range_index[0], batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < range_index[0] else range_index[0] # # query_batch_x = query_volume[i: end_index_query] # # support_batch_x = support_slice_left.repeat(query_batch_x.size()[0], 1, 1, 1) # # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice = end_index_query # support_current_slice = query_current_slice # # for i in range(range_index[0], range_index[1] + 1, batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < range_index[1] + 1 else range_index[1] + 1 # # query_batch_x = query_volume[i: end_index_query] # # # end_index_support = support_current_slice + batch_size # # end_index_support = end_index_support if end_index_support < len(range_index[1] + 1) else len( # # range_index[1] + 1) # # print(len(support_volume)) # # print(support_current_slice, end_index_query) # support_batch_x = support_volume[support_current_slice: end_index_query] # # query_current_slice = end_index_query # support_current_slice = query_current_slice # # support_batch_x = support_batch_x[0].repeat(query_batch_x.size()[0], 1, 1, 1) # # # k += 1 # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # # support_slice_right = support_volume[range_index[1]] # for i in range(range_index[1] + 1, len(support_volume), batch_size): # end_index_query = query_current_slice + batch_size # end_index_query = end_index_query if end_index_query < len(support_volume) else len(support_volume) # # query_batch_x = query_volume[i: end_index_query] # # support_batch_x = support_slice_right.repeat(query_batch_x.size()[0], 1, 1, 1) # # if cuda_available: # query_batch_x = query_batch_x.cuda(device) # support_batch_x = support_batch_x.cuda(device) # # weights = model.conditioner(support_batch_x) # out = model.segmentor(query_batch_x, weights) # # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) # volume_prediction.append(batch_output) # query_current_slice = end_index_query # support_current_slice = query_current_slice volume_prediction = torch.cat(volume_prediction) # volume_prediction = volume_prediction.squeeze() # batch, _, _ = query_labelmap.size() # slice_with_class = torch.sum(query_labelmap.view(batch, -1), dim=1) > 10 # index = slice_with_class[:-1] - slice_with_class[1:] > 0 # seq = torch.Tensor(range(batch - 1)) # range_index_gt = seq[index].type(torch.LongTensor) volume_dice_score = dice_score_binary(volume_prediction[:len(query_labelmap)], query_labelmap.cuda(device), phase=mode) volume_prediction = (volume_prediction.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(volume_prediction), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # # # Save Input nifti_img = nib.MGHImage(np.squeeze(query_volume.cpu().numpy()), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + fold # + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.item() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) print(volume_dice_score_list) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_2view(model1_path, model2_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model1.eval() model2.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label query_labelmap2 = query_labelmap2 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction = 0.5 * volume_prediction1 + 0.5 * volume_prediction2.permute(3, 1, 0, 2) _, batch_output = torch.max(F.softmax(volume_prediction, dim=1), dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list) def evaluate_dice_score_3view(model1_path, model2_path, model3_path, num_classes, query_labels, data_dir, query_txt_file, support_txt_file, remap_config, orientation1, prediction_path, device=0, logWriter=None, mode='eval', fold=None): print("**Starting evaluation. Please check tensorboard for plots if a logWriter is provided in arguments**") print("Loading model => " + model1_path + " and " + model2_path) batch_size = 10 with open(query_txt_file) as file_handle: volumes_query = file_handle.read().splitlines() # with open(support_txt_file) as file_handle: # volumes_support = file_handle.read().splitlines() model1 = torch.load(model1_path) model2 = torch.load(model2_path) model3 = torch.load(model3_path) cuda_available = torch.cuda.is_available() if cuda_available: torch.cuda.empty_cache() model1.cuda(device) model2.cuda(device) model3.cuda(device) model1.eval() model2.eval() model3.eval() common_utils.create_if_not(prediction_path) print("Evaluating now... " + fold) query_file_paths = du.load_file_paths(data_dir, data_dir, query_txt_file) support_file_paths = du.load_file_paths(data_dir, data_dir, support_txt_file) with torch.no_grad(): all_query_dice_score_list = [] for query_label in query_labels: volume_dice_score_list = [] for vol_idx, file_path in enumerate(support_file_paths): # Loading support support_volume1, support_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) support_volume2, support_labelmap2 = support_volume1.transpose((1, 2, 0)), support_labelmap1.transpose( (1, 2, 0)) support_volume3, support_labelmap3 = support_volume1.transpose((2, 0, 1)), support_labelmap1.transpose( (2, 0, 1)) support_volume1 = support_volume1 if len(support_volume1.shape) == 4 else support_volume1[:, np.newaxis, :, :] support_volume2 = support_volume2 if len(support_volume2.shape) == 4 else support_volume2[:, np.newaxis, :, :] support_volume3 = support_volume3 if len(support_volume3.shape) == 4 else support_volume3[:, np.newaxis, :, :] support_volume1, support_labelmap1 = torch.tensor(support_volume1).type( torch.FloatTensor), torch.tensor( support_labelmap1).type(torch.LongTensor) support_volume2, support_labelmap2 = torch.tensor(support_volume2).type( torch.FloatTensor), torch.tensor( support_labelmap2).type(torch.LongTensor) support_volume3, support_labelmap3 = torch.tensor(support_volume3).type( torch.FloatTensor), torch.tensor( support_labelmap3).type(torch.LongTensor) support_volume1 = binarize_label(support_volume1, support_labelmap1, query_label) support_volume2 = binarize_label(support_volume2, support_labelmap2, query_label) support_volume3 = binarize_label(support_volume3, support_labelmap3, query_label) for vol_idx, file_path in enumerate(query_file_paths): query_volume1, query_labelmap1, _, _ = du.load_and_preprocess(file_path, orientation=orientation1, remap_config=remap_config) query_volume2, query_labelmap2 = query_volume1.transpose((1, 2, 0)), query_labelmap1.transpose( (1, 2, 0)) query_volume3, query_labelmap3 = query_volume1.transpose((2, 0, 1)), query_labelmap1.transpose( (2, 0, 1)) query_volume1 = query_volume1 if len(query_volume1.shape) == 4 else query_volume1[:, np.newaxis, :, :] query_volume2 = query_volume2 if len(query_volume2.shape) == 4 else query_volume2[:, np.newaxis, :, :] query_volume3 = query_volume3 if len(query_volume3.shape) == 4 else query_volume3[:, np.newaxis, :, :] query_volume1, query_labelmap1 = torch.tensor(query_volume1).type(torch.FloatTensor), torch.tensor( query_labelmap1).type(torch.LongTensor) query_volume2, query_labelmap2 = torch.tensor(query_volume2).type(torch.FloatTensor), torch.tensor( query_labelmap2).type(torch.LongTensor) query_volume3, query_labelmap3 = torch.tensor(query_volume3).type(torch.FloatTensor), torch.tensor( query_labelmap3).type(torch.LongTensor) query_labelmap1 = query_labelmap1 == query_label # query_labelmap2 = query_labelmap2 == query_label # query_labelmap3 = query_labelmap3 == query_label # Evaluate for orientation 1 support_batch_x = [] k = 2 volume_prediction1 = [] for i in range(0, len(query_volume1), batch_size): query_batch_x = query_volume1[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume1[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model1.conditioner(support_batch_x) out = model1.segmentor(query_batch_x, weights) # _, batch_output = torch.max(F.softmax(out, dim=1), dim=1) volume_prediction1.append(out) # Evaluate for orientation 2 support_batch_x = [] k = 2 volume_prediction2 = [] for i in range(0, len(query_volume2), batch_size): query_batch_x = query_volume2[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume2[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model2.conditioner(support_batch_x) out = model2.segmentor(query_batch_x, weights) volume_prediction2.append(out) # Evaluate for orientation 3 support_batch_x = [] k = 2 volume_prediction3 = [] for i in range(0, len(query_volume3), batch_size): query_batch_x = query_volume3[i: i + batch_size] if k % 2 == 0: support_batch_x = support_volume3[i: i + batch_size] sz = query_batch_x.size() support_batch_x = support_batch_x[batch_size - 1].repeat(sz[0], 1, 1, 1) k += 1 if cuda_available: query_batch_x = query_batch_x.cuda(device) support_batch_x = support_batch_x.cuda(device) weights = model3.conditioner(support_batch_x) out = model3.segmentor(query_batch_x, weights) volume_prediction3.append(out) volume_prediction1 = torch.cat(volume_prediction1) volume_prediction2 = torch.cat(volume_prediction2) volume_prediction3 = torch.cat(volume_prediction3) volume_prediction = 0.33 * F.softmax(volume_prediction1, dim=1) + 0.33 * F.softmax( volume_prediction2.permute(3, 1, 0, 2), dim=1) + 0.33 * F.softmax( volume_prediction3.permute(2, 1, 3, 0), dim=1) _, batch_output = torch.max(volume_prediction, dim=1) volume_dice_score = dice_score_binary(batch_output, query_labelmap1.cuda(device), phase=mode) batch_output = (batch_output.cpu().numpy()).astype('float32') nifti_img = nib.MGHImage(np.squeeze(batch_output), np.eye(4)) nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_' + fold + str('.mgz'))) # # Save Input # nifti_img = nib.MGHImage(np.squeeze(query_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_Input_' + str('.mgz'))) # # # Condition Input # nifti_img = nib.MGHImage(np.squeeze(support_volume1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInput_' + str('.mgz'))) # # # Cond GT # nifti_img = nib.MGHImage(np.squeeze(support_labelmap1.cpu().numpy()).astype('float32'), np.eye(4)) # nib.save(nifti_img, # os.path.join(prediction_path, volumes_query[vol_idx] + '_CondInputGT_' + str('.mgz'))) # # # # Save Ground Truth # nifti_img = nib.MGHImage(np.squeeze(query_labelmap1.cpu().numpy()), np.eye(4)) # nib.save(nifti_img, os.path.join(prediction_path, volumes_query[vol_idx] + '_GT_' + str('.mgz'))) # if logWriter: # logWriter.plot_dice_score('val', 'eval_dice_score', volume_dice_score, volumes_to_use[vol_idx], # vol_idx) volume_dice_score = volume_dice_score.cpu().numpy() volume_dice_score_list.append(volume_dice_score) print(volume_dice_score) dice_score_arr = np.asarray(volume_dice_score_list) avg_dice_score = np.median(dice_score_arr) print('Query Label -> ' + str(query_label) + ' ' + str(avg_dice_score)) all_query_dice_score_list.append(avg_dice_score) # class_dist = [dice_score_arr[:, c] for c in range(num_classes)] # if logWriter: # logWriter.plot_eval_box_plot('eval_dice_score_box_plot', class_dist, 'Box plot Dice Score') print("DONE") return np.mean(all_query_dice_score_list)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/util/sbd_instance_process.py
.py
1,242
39
""" This snippet processes SBD instance segmentation data and transform it from .mat to .png. Then transformed images will be saved in VOC data folder. The name of the new folder is "SegmentationObjectAug" """ import os from scipy.io import loadmat from PIL import Image # set path voc_dir = '../Pascal/VOCdevkit/VOC2012/' sbd_dir = '../SBD/' inst_path = os.path.join(voc_dir, 'SegmentationObject') inst_aug_path = os.path.join(sbd_dir, 'inst') # set target dirctory target_path = os.path.join(voc_dir, 'SegmentationObjectAug') os.makedirs(target_path, exist_ok=True) # copy original VOC instance masks inst_files = os.listdir(inst_path) for inst_file in inst_files: im = Image.open(os.path.join(inst_path, inst_file)) im.save(os.path.join(target_path, inst_file)) palette = im.getpalette() # read SBD instance masks and save them inst_aug_files = os.listdir(inst_aug_path) for inst_aug_file in inst_aug_files: target_file = os.path.join(target_path, inst_aug_file.replace('.mat', '.png')) if not os.path.isfile(target_file): data = loadmat(os.path.join(inst_aug_path, inst_aug_file)) im = Image.fromarray(data['GTinst']['Segmentation'][0, 0]) im.putpalette(palette) im.save(target_file)
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/util/metric.py
.py
6,195
152
""" Metrics for computing evalutation results """ import numpy as np class Metric(object): """ Compute evaluation result Args: max_label: max label index in the data (0 denoting background) n_runs: number of test runs """ def __init__(self, max_label=20, n_runs=None): self.labels = list(range(max_label + 1)) # all class labels self.n_runs = 1 if n_runs is None else n_runs # list of list of array, each array save the TP/FP/FN statistic of a testing sample self.tp_lst = [[] for _ in range(self.n_runs)] self.fp_lst = [[] for _ in range(self.n_runs)] self.fn_lst = [[] for _ in range(self.n_runs)] def record(self, pred, target, labels=None, n_run=None): """ Record the evaluation result for each sample and each class label, including: True Positive, False Positive, False Negative Args: pred: predicted mask array, expected shape is H x W target: target mask array, expected shape is H x W labels: only count specific label, used when knowing all possible labels in advance """ assert pred.shape == target.shape if self.n_runs == 1: n_run = 0 # array to save the TP/FP/FN statistic for each class (plus BG) tp_arr = np.full(len(self.labels), np.nan) fp_arr = np.full(len(self.labels), np.nan) fn_arr = np.full(len(self.labels), np.nan) if labels is None: labels = self.labels else: labels = [0,] + labels for j, label in enumerate(labels): # Get the location of the pixels that are predicted as class j idx = np.where(np.logical_and(pred == j, target != 255)) pred_idx_j = set(zip(idx[0].tolist(), idx[1].tolist())) # Get the location of the pixels that are class j in ground truth idx = np.where(target == j) target_idx_j = set(zip(idx[0].tolist(), idx[1].tolist())) if target_idx_j: # if ground-truth contains this class tp_arr[label] = len(set.intersection(pred_idx_j, target_idx_j)) fp_arr[label] = len(pred_idx_j - target_idx_j) fn_arr[label] = len(target_idx_j - pred_idx_j) self.tp_lst[n_run].append(tp_arr) self.fp_lst[n_run].append(fp_arr) self.fn_lst[n_run].append(fn_arr) def get_mIoU(self, labels=None, n_run=None): """ Compute mean IoU Args: labels: specify a subset of labels to compute mean IoU, default is using all classes """ if labels is None: labels = self.labels # Sum TP, FP, FN statistic of all samples if n_run is None: tp_sum = [np.nansum(np.vstack(self.tp_lst[run]), axis=0).take(labels) for run in range(self.n_runs)] fp_sum = [np.nansum(np.vstack(self.fp_lst[run]), axis=0).take(labels) for run in range(self.n_runs)] fn_sum = [np.nansum(np.vstack(self.fn_lst[run]), axis=0).take(labels) for run in range(self.n_runs)] # Compute mean IoU classwisely # Average across n_runs, then average over classes mIoU_class = np.vstack([tp_sum[run] / (tp_sum[run] + fp_sum[run] + fn_sum[run]) for run in range(self.n_runs)]) mIoU = mIoU_class.mean(axis=1) return (mIoU_class.mean(axis=0), mIoU_class.std(axis=0), mIoU.mean(axis=0), mIoU.std(axis=0)) else: tp_sum = np.nansum(np.vstack(self.tp_lst[n_run]), axis=0).take(labels) fp_sum = np.nansum(np.vstack(self.fp_lst[n_run]), axis=0).take(labels) fn_sum = np.nansum(np.vstack(self.fn_lst[n_run]), axis=0).take(labels) # Compute mean IoU classwisely and average over classes mIoU_class = tp_sum / (tp_sum + fp_sum + fn_sum) mIoU = mIoU_class.mean() return mIoU_class, mIoU def get_mIoU_binary(self, n_run=None): """ Compute mean IoU for binary scenario (sum all foreground classes as one class) """ # Sum TP, FP, FN statistic of all samples if n_run is None: tp_sum = [np.nansum(np.vstack(self.tp_lst[run]), axis=0) for run in range(self.n_runs)] fp_sum = [np.nansum(np.vstack(self.fp_lst[run]), axis=0) for run in range(self.n_runs)] fn_sum = [np.nansum(np.vstack(self.fn_lst[run]), axis=0) for run in range(self.n_runs)] # Sum over all foreground classes tp_sum = [np.c_[tp_sum[run][0], np.nansum(tp_sum[run][1:])] for run in range(self.n_runs)] fp_sum = [np.c_[fp_sum[run][0], np.nansum(fp_sum[run][1:])] for run in range(self.n_runs)] fn_sum = [np.c_[fn_sum[run][0], np.nansum(fn_sum[run][1:])] for run in range(self.n_runs)] # Compute mean IoU classwisely and average across classes mIoU_class = np.vstack([tp_sum[run] / (tp_sum[run] + fp_sum[run] + fn_sum[run]) for run in range(self.n_runs)]) mIoU = mIoU_class.mean(axis=1) return (mIoU_class.mean(axis=0), mIoU_class.std(axis=0), mIoU.mean(axis=0), mIoU.std(axis=0)) else: tp_sum = np.nansum(np.vstack(self.tp_lst[n_run]), axis=0) fp_sum = np.nansum(np.vstack(self.fp_lst[n_run]), axis=0) fn_sum = np.nansum(np.vstack(self.fn_lst[n_run]), axis=0) # Sum over all foreground classes tp_sum = np.c_[tp_sum[0], np.nansum(tp_sum[1:])] fp_sum = np.c_[fp_sum[0], np.nansum(fp_sum[1:])] fn_sum = np.c_[fn_sum[0], np.nansum(fn_sum[1:])] mIoU_class = tp_sum / (tp_sum + fp_sum + fn_sum) mIoU = mIoU_class.mean() return mIoU_class, mIoU
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/util/__init__.py
.py
0
0
null
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/util/scribbles.py
.py
12,787
344
from __future__ import absolute_import, division import networkx as nx import numpy as np from scipy.ndimage import binary_dilation, binary_erosion from scipy.special import comb from skimage.filters import rank from skimage.morphology import dilation, disk, erosion, medial_axis from sklearn.neighbors import radius_neighbors_graph def bezier_curve(points, nb_points=1000): """ Given a list of points compute a bezier curve from it. # Arguments points: ndarray. Array of points with shape (N, 2) with N being the number of points and the second dimension representing the (x, y) coordinates. nb_points: Integer. Number of points to sample from the bezier curve. This value must be larger than the number of points given in `points`. Maximum value 10000. # Returns ndarray: Array of shape (1000, 2) with the bezier curve of the given path of points. """ nb_points = min(nb_points, 1000) points = np.asarray(points, dtype=np.float) if points.ndim != 2 or points.shape[1] != 2: raise ValueError( '`points` should be two dimensional and have shape: (N, 2)') n_points = len(points) if n_points > nb_points: # We are downsampling points return points t = np.linspace(0., 1., nb_points).reshape(1, -1) # Compute the Bernstein polynomial of n, i as a function of t i = np.arange(n_points).reshape(-1, 1) n = n_points - 1 polynomial_array = comb(n, i) * (t**(n - i)) * (1 - t)**i bezier_curve_points = polynomial_array.T.dot(points) return bezier_curve_points def bresenham(points): """ Apply Bresenham algorithm for a list points. More info: https://en.wikipedia.org/wiki/Bresenham's_line_algorithm # Arguments points: ndarray. Array of points with shape (N, 2) with N being the number if points and the second coordinate representing the (x, y) coordinates. # Returns ndarray: Array of points after having applied the bresenham algorithm. """ points = np.asarray(points, dtype=np.int) def line(x0, y0, x1, y1): """ Bresenham line algorithm. """ d_x = x1 - x0 d_y = y1 - y0 x_sign = 1 if d_x > 0 else -1 y_sign = 1 if d_y > 0 else -1 d_x = np.abs(d_x) d_y = np.abs(d_y) if d_x > d_y: xx, xy, yx, yy = x_sign, 0, 0, y_sign else: d_x, d_y = d_y, d_x xx, xy, yx, yy = 0, y_sign, x_sign, 0 D = 2 * d_y - d_x y = 0 line = np.empty((d_x + 1, 2), dtype=points.dtype) for x in range(d_x + 1): line[x] = [x0 + x * xx + y * yx, y0 + x * xy + y * yy] if D >= 0: y += 1 D -= 2 * d_x D += 2 * d_y return line nb_points = len(points) if nb_points < 2: return points new_points = [] for i in range(nb_points - 1): p = points[i:i + 2].ravel().tolist() new_points.append(line(*p)) new_points = np.concatenate(new_points, axis=0) return new_points def scribbles2mask(scribbles, output_resolution, bezier_curve_sampling=False, nb_points=1000, compute_bresenham=True, default_value=0): """ Convert the scribbles data into a mask. # Arguments scribbles: Dictionary. Scribbles in the default format. output_resolution: Tuple. Output resolution (H, W). bezier_curve_sampling: Boolean. Weather to sample first the returned scribbles using bezier curve or not. nb_points: Integer. If `bezier_curve_sampling` is `True` set the number of points to sample from the bezier curve. compute_bresenham: Boolean. Whether to compute bresenham algorithm for the scribbles lines. default_value: Integer. Default value for the pixels which do not belong to any scribble. # Returns ndarray: Array with the mask of the scribbles with the index of the object ids. The shape of the returned array is (B x H x W) by default or (H x W) if `only_annotated_frame==True`. """ if len(output_resolution) != 2: raise ValueError( 'Invalid output resolution: {}'.format(output_resolution)) for r in output_resolution: if r < 1: raise ValueError( 'Invalid output resolution: {}'.format(output_resolution)) size_array = np.asarray(output_resolution[::-1], dtype=np.float) - 1 m = np.full(output_resolution, default_value, dtype=np.int) for p in scribbles: p /= output_resolution[::-1] path = p.tolist() path = np.asarray(path, dtype=np.float) if bezier_curve_sampling: path = bezier_curve(path, nb_points=nb_points) path *= size_array path = path.astype(np.int) if compute_bresenham: path = bresenham(path) m[path[:, 1], path[:, 0]] = 1 return m class ScribblesRobot(object): """Robot that generates realistic scribbles simulating human interaction. # Attributes: kernel_size: Float. Fraction of the square root of the area used to compute the dilation and erosion before computing the skeleton of the error masks. max_kernel_radius: Float. Maximum kernel radius when applying dilation and erosion. Default 16 pixels. min_nb_nodes: Integer. Number of nodes necessary to keep a connected graph and convert it into a scribble. nb_points: Integer. Number of points to sample the bezier curve when converting the final paths into curves. Reference: [1] Sergi et al., "The 2018 DAVIS Challenge on Video Object Segmentation", arxiv 2018 [2] Jordi et al., "The 2017 DAVIS Challenge on Video Object Segmentation", arxiv 2017 """ def __init__(self, kernel_size=.15, max_kernel_radius=16, min_nb_nodes=4, nb_points=1000): if kernel_size >= 1. or kernel_size < 0: raise ValueError('kernel_size must be a value between [0, 1).') self.kernel_size = kernel_size self.max_kernel_radius = max_kernel_radius self.min_nb_nodes = min_nb_nodes self.nb_points = nb_points def _generate_scribble_mask(self, mask): """ Generate the skeleton from a mask Given an error mask, the medial axis is computed to obtain the skeleton of the objects. In order to obtain smoother skeleton and remove small objects, an erosion and dilation operations are performed. The kernel size used is proportional the squared of the area. # Arguments mask: Numpy Array. Error mask Returns: skel: Numpy Array. Skeleton mask """ mask = np.asarray(mask, dtype=np.uint8) side = np.sqrt(np.sum(mask > 0)) mask_ = mask # kernel_size = int(self.kernel_size * side) kernel_radius = self.kernel_size * side * .5 kernel_radius = min(kernel_radius, self.max_kernel_radius) # logging.verbose( # 'Erosion and dilation with kernel radius: {:.1f}'.format( # kernel_radius), 2) compute = True while kernel_radius > 1. and compute: kernel = disk(kernel_radius) mask_ = rank.minimum(mask.copy(), kernel) mask_ = rank.maximum(mask_, kernel) compute = False if mask_.astype(np.bool).sum() == 0: compute = True prev_kernel_radius = kernel_radius kernel_radius *= .9 # logging.verbose('Reducing kernel radius from {:.1f} '.format( # prev_kernel_radius) + # 'pixels to {:.1f}'.format(kernel_radius), 1) mask_ = np.pad( mask_, ((1, 1), (1, 1)), mode='constant', constant_values=False) skel = medial_axis(mask_.astype(np.bool)) skel = skel[1:-1, 1:-1] return skel def _mask2graph(self, skeleton_mask): """ Transforms a skeleton mask into a graph Args: skeleton_mask (ndarray): Skeleton mask Returns: tuple(nx.Graph, ndarray): Returns a tuple where the first element is a Graph and the second element is an array of xy coordinates indicating the coordinates for each Graph node. If an empty mask is given, None is returned. """ mask = np.asarray(skeleton_mask, dtype=np.bool) if np.sum(mask) == 0: return None h, w = mask.shape x, y = np.arange(w), np.arange(h) X, Y = np.meshgrid(x, y) X, Y = X.ravel(), Y.ravel() M = mask.ravel() X, Y = X[M], Y[M] points = np.c_[X, Y] G = radius_neighbors_graph(points, np.sqrt(2), mode='distance') T = nx.from_scipy_sparse_matrix(G) return T, points def _acyclics_subgraphs(self, G): """ Divide a graph into connected components subgraphs Divide a graph into connected components subgraphs and remove its cycles removing the edge with higher weight inside the cycle. Also prune the graphs by number of nodes in case the graph has not enought nodes. Args: G (nx.Graph): Graph Returns: list(nx.Graph): Returns a list of graphs which are subgraphs of G with cycles removed. """ if not isinstance(G, nx.Graph): raise TypeError('G must be a nx.Graph instance') S = [] # List of subgraphs of G for g in nx.connected_component_subgraphs(G): # Remove all cycles that we may find has_cycles = True while has_cycles: try: cycle = nx.find_cycle(g) weights = np.asarray([G[u][v]['weight'] for u, v in cycle]) idx = weights.argmax() # Remove the edge with highest weight at cycle g.remove_edge(*cycle[idx]) except nx.NetworkXNoCycle: has_cycles = False if len(g) < self.min_nb_nodes: # Prune small subgraphs # logging.verbose('Remove a small line with {} nodes'.format( # len(g)), 1) continue S.append(g) return S def _longest_path_in_tree(self, G): """ Given a tree graph, compute the longest path and return it Given an undirected tree graph, compute the longest path and return it. The approach use two shortest path transversals (shortest path in a tree is the same as longest path). This could be improve but would require implement it: https://cs.stackexchange.com/questions/11263/longest-path-in-an-undirected-tree-with-only-one-traversal Args: G (nx.Graph): Graph which should be an undirected tree graph Returns: list(int): Returns a list of indexes of the nodes belonging to the longest path. """ if not isinstance(G, nx.Graph): raise TypeError('G must be a nx.Graph instance') if not nx.is_tree(G): raise ValueError('Graph G must be a tree (graph without cycles)') # Compute the furthest node to the random node v v = list(G.nodes())[0] distance = nx.single_source_shortest_path_length(G, v) vp = max(distance.items(), key=lambda x: x[1])[0] # From this furthest point v' find again the longest path from it distance = nx.single_source_shortest_path(G, vp) longest_path = max(distance.values(), key=len) # Return the longest path return list(longest_path) def generate_scribbles(self, mask): """Given a binary mask, the robot will return a scribble in the region""" # generate scribbles skel_mask = self._generate_scribble_mask(mask) G, P = self._mask2graph(skel_mask) S = self._acyclics_subgraphs(G) longest_paths_idx = [self._longest_path_in_tree(s) for s in S] longest_paths = [P[idx] for idx in longest_paths_idx] scribbles_paths = [ bezier_curve(p, self.nb_points) for p in longest_paths ] output_resolution = tuple([mask.shape[0], mask.shape[1]]) scribble_mask = scribbles2mask(scribbles_paths, output_resolution) return scribble_mask
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/util/voc_classwise_filenames.py
.py
2,540
72
""" This snippet processes VOC segmentation data and generates filename list according to the class labels each image contains. This snippet will create folders under "ImageSets/Segmentaion/" with the same names as the splits. Each folder has 20 txt files each contains the filenames whose associated image contains this class label. """ import os import numpy as np from PIL import Image # set path voc_dir = '../../data/Pascal/VOCdevkit/VOC2012/' seg_dir = os.path.join(voc_dir, 'SegmentationClassAug') trainaug_path = os.path.join(voc_dir, 'ImageSets', 'Segmentation', 'trainaug.txt') trainval_path = os.path.join(voc_dir, 'ImageSets', 'Segmentation', 'trainval.txt') train_path = os.path.join(voc_dir, 'ImageSets', 'Segmentation', 'train.txt') val_path = os.path.join(voc_dir, 'ImageSets', 'Segmentation', 'val.txt') # list filenames of all segmentation masks filenames = os.listdir(seg_dir) # read filenames in different data splits with open(train_path, 'r') as f: train = f.read().splitlines() with open(val_path, 'r') as f: val = f.read().splitlines() with open(trainval_path, 'r') as f: trainval = f.read().splitlines() with open(trainaug_path, 'r') as f: trainaug = f.read().splitlines() filenames_dic = {'train': train, 'val': val, 'trainval': trainval, 'trainaug': trainaug} # create a dic to store the classwise filename lists dic = {'train': {}, 'val': {}, 'trainval': {}, 'trainaug': {}} for split in dic: os.makedirs(os.path.join(voc_dir, 'ImageSets', 'Segmentation', split), exist_ok=True) # check if each mask contains certain label for filename in filenames: filepath = os.path.join(seg_dir, filename) label_set = set(np.unique(np.asarray(Image.open(filepath)))) - set((0, 255)) # exclude 0 and 255 filename_wo_png = filename.replace('.png', '') for label in label_set: for split in dic: if filename_wo_png in filenames_dic[split]: if label in dic[split].keys(): dic[split][label].append(filename_wo_png) else: dic[split][label] = [filename_wo_png,] # write the result to file for split in dic: for label in dic[split].keys(): imageset_path = os.path.join(voc_dir, 'ImageSets', 'Segmentation', split, 'class{}.txt'.format(label)) with open(imageset_path, 'w+') as f: for item in dic[split][label]: f.write("{}\n".format(item))
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/util/utils.py
.py
1,995
74
"""Util functions""" import random from datetime import datetime import torch import numpy as np def try_mkdir(path): try: os.mkdir(path) print(f"mkdir : {path}") except: print(f"failed to make a directory : {path}") def date(): now = datetime.now() string = now.year + now.month + now.day string = now.strftime('%Y%m%d_%H%M%S') return string def set_seed(seed): """ Set the random seed """ random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) CLASS_LABELS = { 'VOC': { 'all': set(range(1, 21)), 0: set(range(1, 21)) - set(range(1, 6)), 1: set(range(1, 21)) - set(range(6, 11)), 2: set(range(1, 21)) - set(range(11, 16)), 3: set(range(1, 21)) - set(range(16, 21)), }, 'COCO': { 'all': set(range(1, 81)), 0: set(range(1, 81)) - set(range(1, 21)), 1: set(range(1, 81)) - set(range(21, 41)), 2: set(range(1, 81)) - set(range(41, 61)), 3: set(range(1, 81)) - set(range(61, 81)), } } def get_bbox(fg_mask, inst_mask): """ Get the ground truth bounding boxes """ fg_bbox = torch.zeros_like(fg_mask, device=fg_mask.device) bg_bbox = torch.ones_like(fg_mask, device=fg_mask.device) inst_mask[fg_mask == 0] = 0 area = torch.bincount(inst_mask.view(-1)) cls_id = area[1:].argmax() + 1 cls_ids = np.unique(inst_mask)[1:] mask_idx = np.where(inst_mask[0] == cls_id) y_min = mask_idx[0].min() y_max = mask_idx[0].max() x_min = mask_idx[1].min() x_max = mask_idx[1].max() fg_bbox[0, y_min:y_max+1, x_min:x_max+1] = 1 for i in cls_ids: mask_idx = np.where(inst_mask[0] == i) y_min = max(mask_idx[0].min(), 0) y_max = min(mask_idx[0].max(), fg_mask.shape[1] - 1) x_min = max(mask_idx[1].min(), 0) x_max = min(mask_idx[1].max(), fg_mask.shape[2] - 1) bg_bbox[0, y_min:y_max+1, x_min:x_max+1] = 0 return fg_bbox, bg_bbox
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/test/decathlon_5shot.sh
.sh
2,316
33
# this code require gpu_id when running # 1 2 3 4 5 6 7 8 9 10 11 12 13 mkdir runs/log mkdir runs/log/decathlon_1shot_last gpu=$1 j=$2 #j=9 j=5 organ=1 for support in 0 5 10 15 20 do #echo "python train.py with mode=train gpu_id=${gpu} target=${organ} board=ID${j}_${organ} record=False n_work=3 external_train=decathlon n_shot=1 " #python train.py with mode=train gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_data record=False n_work=3 external_train=decathlon n_shot=1 echo "python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_lowest record=False external_test=decathlon n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/decathlon_1shot_last/ID${j}_5shot_${organ}_${support}.txt" python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_lowest record=False external_test=decathlon n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/decathlon_1shot_last/ID${j}_5shot_${organ}_${support}.txt #echo "python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_last record=False external_test=decathlon n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/decathlon_1shot_last/ID${j}_5shot_${organ}_${support}.txt" #python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_last record=False external_test=decathlon n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/decathlon_1shot_last/ID${j}_5shot_${organ}_${support}.txt done #j=11 j=7 organ=6 for support in 0 5 10 15 20 do echo "python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_lowest record=False external_test=decathlon n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/decathlon_1shot_last/ID${j}_5shot_${organ}_${support}.txt" python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_lowest record=False external_test=decathlon n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/decathlon_1shot_last/ID${j}_5shot_${organ}_${support}.txt done exit 0
Shell
3D
oopil/3D_medical_image_FSS
FSS_SE/test/summarize_test_results.py
.py
4,955
154
import re import glob import numpy as np def summarize(files): if len(files) < 5: print("There is no results for this set.") return 0,0 dices = [] for file in files[:5]: fd = open(file) lines = fd.readlines() # print(len(lines),file) result_line = lines[-2] find = re.search("0.*",result_line) line_parts = re.split(" ", result_line) dice = line_parts[-2] dices.append(float(dice)) return dices def main(): bcv_dir = "runs/log/bcv" bcv_dir_last = "runs/log/bcv_last" bcv_dice = "runs/log/bcv_dice" bcv_dice_last = "runs/log/bcv_dice_last" bcv_dice_v1 = "runs/log/bcv_dice_1shot_low" # dirs = [bcv_dir, bcv_dir_last, bcv_dice, bcv_dice_last] dirs = [bcv_dice_v1] for dir in dirs: print() print(dir) for shot in [1,3,5]: for organ in [1,3,6,14]: files = glob.glob(f"{dir}/*_{organ}_*{shot}shot*") files.sort() dices = summarize(files) avg, std = np.mean(dices), np.std(dices) avg = float("{:.3f}".format(avg)) std = float("{:.4f}".format(std)) dices = [str(dice) for dice in dices] dice_str = ",".join(dices) # print(dir, organ, shot) if avg*std!=0: print(f"organ:{organ},{shot}shot,{dice_str},{avg},{std}") dir = "runs/log/ctorg_1shot" print(dir) shot=5 # 1shot actually for organ in [1,3,6,14]: files = glob.glob(f"{dir}/*{shot}shot*_{organ}_*") files.sort() dices = summarize(files) avg, std = np.mean(dices), np.std(dices) avg = float("{:.3f}".format(avg)) std = float("{:.4f}".format(std)) dices = [str(dice) for dice in dices] dice_str = ",".join(dices) # print(dir, organ, shot) if avg*std!=0: print(f"organ:{organ},{shot}shot,{dice_str},{avg},{std}") print() dir = "runs/log/decathlon_1shot" print(dir) shot=5 # 1shot actually for organ in [1,3,6,14]: files = glob.glob(f"{dir}/*{shot}shot*_{organ}_*") files.sort() dices = summarize(files) avg, std = np.mean(dices), np.std(dices) avg = float("{:.3f}".format(avg)) std = float("{:.4f}".format(std)) dices = [str(dice) for dice in dices] dice_str = ",".join(dices) # print(dir, organ, shot) if avg*std!=0: print(f"organ:{organ},{shot}shot,{dice_str},{avg},{std}") print() dir = "runs/log/ctorg_1shot_last" print(dir) shot=5 # 1shot actually for organ in [1,3,6,14]: files = glob.glob(f"{dir}/*{shot}shot*_{organ}_*") files.sort() dices = summarize(files) avg, std = np.mean(dices), np.std(dices) avg = float("{:.3f}".format(avg)) std = float("{:.4f}".format(std)) dices = [str(dice) for dice in dices] dice_str = ",".join(dices) # print(dir, organ, shot) if avg*std!=0: print(f"organ:{organ},{shot}shot,{dice_str},{avg},{std}") print() dir = "runs/log/decathlon_1shot_last" print(dir) shot=5 # 1shot actually for organ in [1,3,6,14]: files = glob.glob(f"{dir}/*{shot}shot*_{organ}_*") files.sort() dices = summarize(files) avg, std = np.mean(dices), np.std(dices) avg = float("{:.3f}".format(avg)) std = float("{:.4f}".format(std)) dices = [str(dice) for dice in dices] dice_str = ",".join(dices) # print(dir, organ, shot) if avg*std!=0: print(f"organ:{organ},{shot}shot,{dice_str},{avg},{std}") print() dir = "runs/log/ctorg_1shot_low" print(dir) shot=5 # 1shot actually for organ in [1,3,6,14]: files = glob.glob(f"{dir}/*{shot}shot*_{organ}_*") files.sort() dices = summarize(files) avg, std = np.mean(dices), np.std(dices) avg = float("{:.3f}".format(avg)) std = float("{:.4f}".format(std)) dices = [str(dice) for dice in dices] dice_str = ",".join(dices) # print(dir, organ, shot) if avg*std!=0: print(f"organ:{organ},{shot}shot,{dice_str},{avg},{std}") print() dir = "runs/log/decathlon_1shot_low" print(dir) shot=5 # 1shot actually for organ in [1,3,6,14]: files = glob.glob(f"{dir}/*{shot}shot*_{organ}_*") files.sort() dices = summarize(files) avg, std = np.mean(dices), np.std(dices) avg = float("{:.3f}".format(avg)) std = float("{:.4f}".format(std)) dices = [str(dice) for dice in dices] dice_str = ",".join(dices) # print(dir, organ, shot) if avg*std!=0: print(f"organ:{organ},{shot}shot,{dice_str},{avg},{std}") print() if __name__=="__main__": main()
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/test/bcv_5shot.sh
.sh
1,096
34
# test code for external dataset ctorg with different support data mkdir runs/log mkdir runs/log/bcv_dice_1shot_low declare -a gpu_list declare -a ID_list #gpu_list=(0 1 2 7) gpu=$1 # BCV configuration #ID_list=(1 2 3 4) #1shot ID_list=(9 10 11 12) #1shot idx=0 for organ in 1 3 6 14 do j=${ID_list[$idx]} echo "" for support in `seq 0 9` do echo "python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/lowest.pth target=${organ} n_shot=5 record=False board=ID${j}_${organ}_1shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_1shot_low/ID${j}_${organ}_1shot_${support}.txt" python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/lowest.pth target=${organ} n_shot=5 record=False board=ID${j}_${organ}_1shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_1shot_low/ID${j}_${organ}_1shot_${support}.txt echo "--------------------------------------------------------------" sleep 5 done idx=$(($idx+1)) done exit 0
Shell
3D
oopil/3D_medical_image_FSS
FSS_SE/test/bcv_5shot_save_sample.sh
.sh
816
26
# test code for external dataset ctorg with different support data mkdir runs/log mkdir runs/log/bcv_dice_ce declare -a gpu_list gpu_list=(0 1 2 7) gpu=$1 j=$2 idx=0 # BCV configuration # 1 shot - 21, 3 shot - 5, 5 shot - 17 j=5 support=0 for organ in 1 3 6 14 do echo "python test.py with target=${organ} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth n_shot=1 gpu_id=${gpu} record=False board=ID${j}_${organ}_5shot_${support} s_idx=${support} save_sample=True save_name=1shot_noFT_last" python test.py with target=${organ} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth n_shot=1 gpu_id=${gpu} record=False board=ID${j}_${organ}_5shot_${support} s_idx=${support} save_sample=True save_name=1shot_noFT_last sleep 5 j=$(($j+1)) done
Shell
3D
oopil/3D_medical_image_FSS
FSS_SE/test/ctorg_5shot.sh
.sh
1,715
27
# this code require gpu_id when running # 1 2 3 4 5 6 7 8 9 10 11 12 13 mkdir runs/log mkdir runs/log/ctorg_1shot_last gpu=$1 j=$2 #j=10 j=6 for organ in 3 6 14 do for support in 0 5 10 15 20 do #echo "python train.py with mode=train gpu_id=${gpu} target=${organ} board=ID${j}_${organ} record=False n_work=3 external_train=CT_ORG n_shot=1 " #python train.py with mode=train gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_data record=False n_work=3 external_train=CT_ORG n_shot=1 echo "python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_last record=False external_test=CT_ORG n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/ctorg_1shot_last/ID${j}_5shot_${organ}_${support}.txt" python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_last record=False external_test=CT_ORG n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/ctorg_1shot_last/ID${j}_5shot_${organ}_${support}.txt #echo "python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_last record=False external_test=CT_ORG n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/ctorg_1shot_last/ID${j}_5shot_${organ}_${support}.txt" #python test.py with gpu_id=${gpu} target=${organ} board=ID${j}_${organ}_last record=False external_test=CT_ORG n_shot=1 s_idx=${support} snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth >> runs/log/ctorg_1shot_last/ID${j}_5shot_${organ}_${support}.txt done j=$(($j+1)) done
Shell
3D
oopil/3D_medical_image_FSS
FSS_SE/test/bcv.sh
.sh
2,828
76
# test code for external dataset ctorg with different support data mkdir runs/log mkdir runs/log/bcv_dice_last declare -a gpu_list declare -a ID_list #gpu_list=(0 1 2 7) gpu=$1 # BCV configuration #ID_list=(1 2 3 4) #1shot ID_list=(5 6 7 8) #1shot idx=0 for organ in 1 3 6 14 do j=${ID_list[$idx]} echo "" for support in `seq 0 9` do echo "python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth target=${organ} n_shot=1 record=False board=ID${j}_${organ}_1shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_last/ID${j}_${organ}_1shot_${support}.txt" python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_1shot_train/${j}/snapshots/last.pth target=${organ} n_shot=1 record=False board=ID${j}_${organ}_1shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_last/ID${j}_${organ}_1shot_align_${support}.txt echo "--------------------------------------------------------------" sleep 5 done idx=$(($idx+1)) done #ID_list=(1 2 3 4) #3shot ID_list=(5 6 7 8) #3shot idx=0 for organ in 1 3 6 14 do j=${ID_list[$idx]} echo "" for support in 0 3 6 9 12 do echo "python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_3shot_train/${j}/snapshots/last.pth target=${organ} n_shot=3 record=False board=ID${j}_${organ}_3shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_last/ID${j}_${organ}_3shot_${support}.txt" python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_3shot_train/${j}/snapshots/last.pth target=${organ} n_shot=3 record=False board=ID${j}_${organ}_3shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_last/ID${j}_${organ}_3shot_align_${support}.txt echo "--------------------------------------------------------------" sleep 5 done idx=$(($idx+1)) done #ID_list=(1 2 3 4) #5shot ID_list=(5 6 7 8) #5shot idx=0 for organ in 1 3 6 14 do j=${ID_list[$idx]} echo "" for support in 0 3 5 7 10 do echo "python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_5shot_train/${j}/snapshots/last.pth target=${organ} n_shot=5 record=False board=ID${j}_${organ}_5shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_last/ID${j}_${organ}_5shot_${support}.txt" python test_multishot.py with snapshot=runs/PANet_BCV_align_sets_0_1way_5shot_train/${j}/snapshots/last.pth target=${organ} n_shot=5 record=False board=ID${j}_${organ}_5shot_${support} s_idx=${support} gpu_id=${gpu} >> runs/log/bcv_dice_last/ID${j}_${organ}_5shot_align_${support}.txt echo "--------------------------------------------------------------" sleep 5 done idx=$(($idx+1)) done exit 0
Shell
3D
oopil/3D_medical_image_FSS
FSS_SE/dataloaders_medical/decathlon.py
.py
10,510
285
import os import re import sys import json import math import random import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") # sys.path.append("../dataloaders_medical") from dataloaders_medical.common import * # from common import * import cv2 from cv2 import resize def prostate_img_process(img_arr, HE=False): if HE: img_arr = equalize_hist(img_arr) * 255.0 else: img_arr = normalize(img_arr, type=0) return img_arr def totensor(arr): tensor = torch.from_numpy(arr).float() return tensor def random_augment(s_imgs, s_labels, q_imgs, q_labels): ## do random rotation and flip k = random.sample([i for i in range(0, 4)], 1)[0] s_imgs = np.rot90(s_imgs, k, (3, 4)).copy() s_labels = np.rot90(s_labels, k, (3, 4)).copy() q_imgs = np.rot90(q_imgs, k, (2, 3)).copy() q_labels = np.rot90(q_labels, k, (2, 3)).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 3).copy() s_labels = np.flip(s_labels, 3).copy() q_imgs = np.flip(q_imgs, 2).copy() q_labels = np.flip(q_labels, 2).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 4).copy() s_labels = np.flip(s_labels, 4).copy() q_imgs = np.flip(q_imgs, 3).copy() q_labels = np.flip(q_labels, 3).copy() return s_imgs, s_labels, q_imgs, q_labels class Base_dataset(): def __init__(self, img_paths, label_paths, config): """ dataset constructor for training """ super().__init__() self.mode = config['mode'] self.length = config['n_iter'] self.valid_img_n = len(img_paths) self.size = config['size'] self.img_paths = img_paths self.label_paths = label_paths self.n_shot = config["n_shot"] self.s_idx = config["s_idx"] self.is_train = True if str(self.__class__).split(".")[-1][:4]=="Test": self.is_train = False ## load file names in advance self.img_lists = [] self.slice_cnts = [] for img_path in self.img_paths: fnames = os.listdir(img_path) self.slice_cnts.append(len(fnames)) fnames = [int(e.split(".")[0]) for e in fnames] fnames.sort() fnames = [f"{e}.npy" for e in fnames] self.img_lists.append(fnames) if not self.is_train: # for testing self.length = sum(self.slice_cnts) def get_sample(self, s_img_paths_all, s_label_paths_all, q_img_paths, q_label_paths): seed = random.randrange(0,1000) # s_length = len(s_img_paths) s_imgs_all, s_labels_all = [],[] for s_idx, s_img_paths in enumerate(s_img_paths_all): s_label_paths = s_label_paths_all[s_idx] imgs, labels = [],[] for i in range(len(s_img_paths)): img_path, label_path = s_img_paths[i], s_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) s_imgs = np.stack(imgs,axis=0) s_labels = np.stack(labels,axis=0) s_imgs_all.append(s_imgs) s_labels_all.append(s_labels) s_imgs = np.stack(s_imgs_all,axis=0) s_labels = np.stack(s_labels_all,axis=0) q_length = len(q_img_paths) imgs, labels = [],[] for i in range(len(q_img_paths)): img_path, label_path = q_img_paths[i], q_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) q_imgs = np.stack(imgs,axis=0) q_labels = np.stack(labels,axis=0) # print(imgs.shape) [slice_num,1,256,256]? if self.is_train: ## random augmentation : flip, rotation s_imgs, s_labels, q_imgs, q_labels = random_augment(s_imgs, s_labels, q_imgs, q_labels) sample = { "s_x":totensor(s_imgs), "s_y":totensor(s_labels), #.long() "q_x":totensor(q_imgs), "q_y":totensor(q_labels), #.long() # "s_length":s_length, # "q_length":q_length, "s_fname":s_img_paths_all, "q_fname":q_img_paths, } return sample def handle_idx(self, s_n, q_idx, q_n): """ choose slices for support and query volume :return: supp_idx, qry_idx """ q_ratio = (q_idx)/(q_n-1) s_idx = round((s_n-1)*q_ratio) return s_idx def getitem_train(self): ## choose support and target idx_space = [i for i in range(self.valid_img_n)] subj_idxs = random.sample(idx_space, self.n_shot+1) s_subj_idxs = subj_idxs[:self.n_shot] q_subj_idx = subj_idxs[self.n_shot] q_subj_img_path = self.img_paths[q_subj_idx] q_subj_label_path = self.label_paths[q_subj_idx] q_fnames = self.img_lists[q_subj_idx] q_idx = random.randrange(0, len(q_fnames)) is_flip = False if random.random() < 0.5: is_flip = True q_fnames.reverse() s_img_paths_all, s_label_paths_all = [],[] for s_subj_idx in s_subj_idxs: s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] s_fnames = self.img_lists[s_subj_idx] ## flip augmentation if is_flip: s_fnames.reverse() ## choose support and query slice s_idx = self.handle_idx(len(s_fnames), q_idx, len(q_fnames)) s_fnames_selected = s_fnames[s_idx:s_idx+1] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) q_fnames_selected = q_fnames[q_idx:q_idx + 1] q_img_paths_selected = [f"{q_subj_img_path}/{fname}" for fname in q_fnames_selected] q_label_paths_selected = [f"{q_subj_label_path}/{fname}" for fname in q_fnames_selected] return self.get_sample(s_img_paths_all, s_label_paths_all, q_img_paths_selected, q_label_paths_selected) def getitme_test(self, idx): q_subj_idx, q_idx = self.get_test_subj_idx(idx) q_subj_img_path = self.img_paths[q_subj_idx] q_subj_label_path = self.label_paths[q_subj_idx] q_fnames = self.img_lists[q_subj_idx] s_img_paths_all, s_label_paths_all = [],[] for s_idx in range(self.n_shot): s_subj_img_path = self.s_img_paths[s_idx] s_subj_label_path = self.s_label_paths[s_idx] s_fnames = self.s_fnames_list[s_idx] ## choose support and query slice s_idx = self.handle_idx(len(s_fnames), q_idx, len(q_fnames)) s_fnames_selected = s_fnames[s_idx:s_idx+1] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) q_fnames_selected = q_fnames[q_idx:q_idx + 1] q_img_paths_selected = [f"{q_subj_img_path}/{fname}" for fname in q_fnames_selected] q_label_paths_selected = [f"{q_subj_label_path}/{fname}" for fname in q_fnames_selected] return self.get_sample(s_img_paths_all, s_label_paths_all, q_img_paths_selected, q_label_paths_selected) def get_len_train(self): return self.length def get_len_test(self): return self.length def get_val_subj_idx(self, idx): for subj_idx,cnt in enumerate(self.q_cnts): if idx < cnt: return subj_idx, idx*self.q_max_slice else: idx -= cnt print("get_val_subj_idx function is not working.") assert False def get_test_subj_idx(self, idx): for subj_idx,cnt in enumerate(self.slice_cnts): if idx < cnt: return subj_idx, idx else: idx -= cnt print("get_test_subj_idx function is not working.") assert False def get_cnts(self): ## only for test loader return self.slice_cnts def img_load(self, img_path, seed=0): img_arr = np.load(img_path) return img_arr class BaseLoader(Base_dataset): modal_i = [0] # there is only one modality label_i = 1.0 # there is only one label for each image class TrainLoader(BaseLoader): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class TestLoader(BaseLoader): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) def set_support_volume(self, s_img_paths, s_label_paths): ## set support img path and label path for validation and testing self.s_img_paths = [] self.s_label_paths = [] self.s_fnames_list = [] for i in range(len(s_img_paths)): s_fnames = os.listdir(s_img_paths[i]) s_fnames = [int(e.split(".")[0]) for e in s_fnames] s_fnames.sort() print(f'support img {i} path : {s_img_paths[i]} length : {len(s_fnames)}') self.s_img_paths.append(s_img_paths[i]) self.s_label_paths.append(s_label_paths[i]) self.s_fnames_list.append([f"{e}.npy" for e in s_fnames]) if __name__ == "__main__": pass # main()
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/dataloaders_medical/common.py
.py
6,690
210
""" Dataset classes for common uses """ import random import SimpleITK as sitk import numpy as np from PIL import Image from torch.utils.data import Dataset import torch import torchvision.transforms.functional as tr_F from skimage.exposure import equalize_hist import pdb def crop_resize(slice): x_size, y_size = np.shape(slice) slice = slice[40:x_size - 20, 50:y_size - 50] slice = resize(slice, (240, 240)) return slice def fill_empty_space(arr): arr[arr==0] = np.mean(arr) return arr def prostate_sample(img_arr, label_arr, isize): img = Image.fromarray(img_arr.astype(np.uint8)) label = Image.fromarray(label_arr.astype(np.uint8)) sample = { 'image':img, 'label':label, 'inst':label, 'scribble':label, } # pdb.set_trace() sample = resize(sample, (isize,isize)) sample = to_tensor_normalize(sample) return sample def prostate_mask(sample, isize): # pdb.set_trace() label = sample['label'] fg_mask = torch.where(label == 1, torch.ones_like(label), torch.zeros_like(label)) bg_mask = torch.ones_like(label) - fg_mask fg_mask = fg_mask.expand((1, isize, isize)) bg_mask = bg_mask.expand((1, isize, isize)) return {'fg_mask': fg_mask, 'bg_mask': bg_mask, } def get_support_sample(ipath, lpath, modal_index, mask_n, is_HE, shift=0): arr = read_npy(ipath, modal_index, is_HE) # pdb.set_trace() ## for debugging # arr = fill_empty_space(arr) arr_mask = read_sitk(lpath) ## for 2-way(binary) segmentation arr_mask = (arr_mask>0)*1.0 # arr_mask = (arr_mask == mask_n) * 1.0 cnt = np.sum(arr_mask, axis=(1, 2)) maxarg = np.argmax(cnt) slice = arr[maxarg+shift, :, :] slice = crop_resize(slice) # slice = normalize(slice) slice = convert3ch(slice) save_img(slice, "tmp_img.png") slice_mask = arr_mask[maxarg+shift, :, :]*255.0 slice_mask = crop_resize(slice_mask) # slice_mask = convert3ch(slice_mask) save_img(slice_mask, "tmp_label.png") sample = read_sample("tmp_img.png", "tmp_label.png") # sample = transforms(sample) sample = to_tensor_normalize(sample) return sample ## for 5 way segmentation # arr_mask = (arr_mask == mask_n)*1.0 # if mask_n == 2: # arr_mask = (arr_mask > 0)*1.0 # elif mask_n == 1: # arr_mask = (arr_mask == 1)*1.0 # elif mask_n == 4: # arr_mask = (arr_mask == 4)*1.0 + (arr_mask == 1)*1.0 # else: # raise("invalid mask_n") def getMask(sample, class_id=1, class_ids=[0, 1]): label = sample['label'] empty = sample['empty'] fg_mask = torch.where(label == class_id, torch.ones_like(label), torch.zeros_like(label)) brain_bg_mask = empty # bg_mask = torch.ones_like(label) - fg_mask - empty bg_mask = torch.ones_like(label) - fg_mask # brain_fg_mask = torch.ones_like(label) - empty brain_fg_mask = torch.ones_like(label) - empty - fg_mask fg_mask = fg_mask.expand((1, 240, 240)) bg_mask = bg_mask.expand((1, 240, 240)) brain_fg_mask = brain_fg_mask.expand((1, 240, 240)) brain_bg_mask = brain_bg_mask.expand((1, 240, 240)) return {'fg_mask': fg_mask, 'bg_mask': bg_mask, 'brain_fg_mask': brain_fg_mask, 'brain_bg_mask': brain_bg_mask,} def read_npy(path, modal_index, is_HE): arr = np.load(path)[modal_index] if is_HE: arr = equalize_hist(arr) arr = normalize(arr, type=0) return arr def convert3ch(slice, axis=2): slice = np.expand_dims(slice, axis=axis) slice = np.concatenate([slice, slice, slice], axis=axis) return slice def normalize(arr, type=0): # print(np.mean(arr*255.0), np.std(arr*255.0), np.amin(arr*255.0), np.amax(arr*255.0)) if type == 0: # min and max mini = np.amin(arr) arr -= mini maxi = np.amax(arr) arr_norm = arr/maxi elif type == 1: # stddev and mean mean = np.mean(arr) stddev = np.std(arr) arr_norm = (arr-mean)/stddev return arr_norm*255.0 def map_distribution(arr, tg_mean=0, tg_std=1, tg_min=0, tg_max=255): arr_nonzero = arr[np.nonzero(arr)] ## input arr range : (0,255) mean, std, mini, maxi = np.mean(arr_nonzero), np.std(arr_nonzero), np.amin(arr_nonzero), np.amax(arr_nonzero) Z = (arr - mean) / std ## map arr into standard var Z new_arr = Z*tg_std + tg_mean ## map Z into the target distribution print(np.mean(new_arr), np.std(new_arr), np.amin(new_arr), np.amax(new_arr)) new_arr = np.clip(new_arr, tg_min, tg_max) return new_arr def to_tensor_normalize(sample): img, label = sample['image'], sample['label'] inst, scribble = sample['inst'], sample['scribble'] ## map distribution # pdb.set_trace() # arr = np.array(img) # arr = map_distribution(arr, tg_mean=0.456, tg_std=0.224, tg_min=-10, tg_max=10) # img = Image.fromarray(arr.astype(dtype=np.uint8)) img = tr_F.to_tensor(img) empty = (img[0] == 0.0) * 1.0 img = tr_F.normalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) label = torch.Tensor(np.array(label)).long() img = img.expand((1, 3, 240, 240)) label = label/255.0 sample['empty'] = empty.long() sample['image'] = img sample['label'] = label sample['inst'] = inst sample['scribble'] = scribble return sample def read_sample(img_path, label_path): sample = {} sample['image'] = Image.open(img_path) sample['label'] = Image.open(label_path) sample['inst'] = Image.open(label_path) sample['scribble'] = Image.open(label_path) # Save the original image (without normalization) sample['original'] = Image.open(img_path) return sample def read_sitk(path): itk_img = sitk.ReadImage(path) arr = sitk.GetArrayFromImage(itk_img) arr = np.array(arr, dtype=np.float32) return arr def save_sitk(arr, itk_ref, opath): sitk_oimg = sitk.GetImageFromArray(arr) sitk_oimg.CopyInformation(itk_ref) sitk.WriteImage(sitk_oimg, opath) def save_img(arr, path): im = Image.fromarray(arr.astype(np.uint8)) im.save(path) def load_img(path): arr = read_PIL(path) return to_tensor_normalize(arr) def load_seg(path): arr = read_PIL(path) arr = np.expand_dims(arr, axis=0) arr = tr_F.to_tensor(arr) return arr def read_PIL(path): im = Image.open(path) arr = np.array(im, dtype=np.float32) # arr = np.swapaxes(arr, 0, 2) return arr def resize(sample, size): img, label = sample['image'], sample['label'] img = tr_F.resize(img, size) label = tr_F.resize(label, size, interpolation=Image.NEAREST) sample['image'] = img sample['label'] = label return sample
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/dataloaders_medical/__init__.py
.py
0
0
null
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/dataloaders_medical/dataset_CT_ORG.py
.py
10,422
278
import os import re import sys import json import math import random import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") # sys.path.append("../dataloaders_medical") from dataloaders_medical.common import * # from common import * import cv2 from cv2 import resize def totensor(arr): tensor = torch.from_numpy(arr).float() return tensor def random_augment(s_imgs, s_labels, q_imgs, q_labels): ## do random rotation and flip k = random.sample([i for i in range(0, 4)], 1)[0] s_imgs = np.rot90(s_imgs, k, (3, 4)).copy() s_labels = np.rot90(s_labels, k, (3, 4)).copy() q_imgs = np.rot90(q_imgs, k, (2, 3)).copy() q_labels = np.rot90(q_labels, k, (2, 3)).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 3).copy() s_labels = np.flip(s_labels, 3).copy() q_imgs = np.flip(q_imgs, 2).copy() q_labels = np.flip(q_labels, 2).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 4).copy() s_labels = np.flip(s_labels, 4).copy() q_imgs = np.flip(q_imgs, 3).copy() q_labels = np.flip(q_labels, 3).copy() return s_imgs, s_labels, q_imgs, q_labels class Base_dataset_ctorg(): def __init__(self, img_paths, label_paths, config): """ dataset constructor for training """ super().__init__() self.mode = config['mode'] self.length = config['n_iter'] self.valid_img_n = len(img_paths) self.size = config['size'] self.img_paths = img_paths self.label_paths = label_paths self.n_shot = config["n_shot"] self.s_idx = config["s_idx"] self.is_train = True if str(self.__class__).split(".")[-1][:4] == "Test": self.is_train = False ## load file names in advance self.img_lists = [] self.slice_cnts = [] for img_path in self.img_paths: fnames = os.listdir(img_path) self.slice_cnts.append(len(fnames)) fnames = [int(e.split(".")[0]) for e in fnames] fnames.sort() fnames = [f"{e}.npy" for e in fnames] self.img_lists.append(fnames) if not self.is_train: # for testing self.length = sum(self.slice_cnts) def get_sample(self, s_img_paths_all, s_label_paths_all, q_img_paths, q_label_paths): seed = random.randrange(0, 1000) # s_length = len(s_img_paths) s_imgs_all, s_labels_all = [], [] for s_idx, s_img_paths in enumerate(s_img_paths_all): s_label_paths = s_label_paths_all[s_idx] imgs, labels = [], [] for i in range(len(s_img_paths)): img_path, label_path = s_img_paths[i], s_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) s_imgs = np.stack(imgs, axis=0) s_labels = np.stack(labels, axis=0) s_imgs_all.append(s_imgs) s_labels_all.append(s_labels) s_imgs = np.stack(s_imgs_all, axis=0) s_labels = np.stack(s_labels_all, axis=0) q_length = len(q_img_paths) imgs, labels = [], [] for i in range(len(q_img_paths)): img_path, label_path = q_img_paths[i], q_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) q_imgs = np.stack(imgs, axis=0) q_labels = np.stack(labels, axis=0) # print(imgs.shape) [slice_num,1,256,256]? if self.is_train: ## random augmentation : flip, rotation s_imgs, s_labels, q_imgs, q_labels = random_augment(s_imgs, s_labels, q_imgs, q_labels) sample = { "s_x": totensor(s_imgs), "s_y": totensor(s_labels), # .long() "q_x": totensor(q_imgs), "q_y": totensor(q_labels), # .long() # "s_length":s_length, # "q_length":q_length, "s_fname": s_img_paths_all, "q_fname": q_img_paths, } return sample def handle_idx(self, s_n, q_idx, q_n): """ choose slices for support and query volume :return: supp_idx, qry_idx """ q_ratio = (q_idx) / (q_n - 1) s_idx = round((s_n - 1) * q_ratio) return s_idx def getitem_train(self): ## choose support and target idx_space = [i for i in range(self.valid_img_n)] subj_idxs = random.sample(idx_space, self.n_shot + 1) s_subj_idxs = subj_idxs[:self.n_shot] q_subj_idx = subj_idxs[self.n_shot] q_subj_img_path = self.img_paths[q_subj_idx] q_subj_label_path = self.label_paths[q_subj_idx] q_fnames = self.img_lists[q_subj_idx] q_idx = random.randrange(0, len(q_fnames)) is_flip = False if random.random() < 0.5: is_flip = True q_fnames.reverse() s_img_paths_all, s_label_paths_all = [], [] for s_subj_idx in s_subj_idxs: s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] s_fnames = self.img_lists[s_subj_idx] ## flip augmentation if is_flip: s_fnames.reverse() ## choose support and query slice s_idx = self.handle_idx(len(s_fnames), q_idx, len(q_fnames)) s_fnames_selected = s_fnames[s_idx:s_idx + 1] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) q_fnames_selected = q_fnames[q_idx:q_idx + 1] q_img_paths_selected = [f"{q_subj_img_path}/{fname}" for fname in q_fnames_selected] q_label_paths_selected = [f"{q_subj_label_path}/{fname}" for fname in q_fnames_selected] return self.get_sample(s_img_paths_all, s_label_paths_all, q_img_paths_selected, q_label_paths_selected) def getitme_test(self, idx): q_subj_idx, q_idx = self.get_test_subj_idx(idx) q_subj_img_path = self.img_paths[q_subj_idx] q_subj_label_path = self.label_paths[q_subj_idx] q_fnames = self.img_lists[q_subj_idx] s_img_paths_all, s_label_paths_all = [], [] for s_idx in range(self.n_shot): s_subj_img_path = self.s_img_paths[s_idx] s_subj_label_path = self.s_label_paths[s_idx] s_fnames = self.s_fnames_list[s_idx] ## choose support and query slice s_idx = self.handle_idx(len(s_fnames), q_idx, len(q_fnames)) s_fnames_selected = s_fnames[s_idx:s_idx + 1] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) q_fnames_selected = q_fnames[q_idx:q_idx + 1] q_img_paths_selected = [f"{q_subj_img_path}/{fname}" for fname in q_fnames_selected] q_label_paths_selected = [f"{q_subj_label_path}/{fname}" for fname in q_fnames_selected] return self.get_sample(s_img_paths_all, s_label_paths_all, q_img_paths_selected, q_label_paths_selected) def get_len_train(self): return self.length def get_len_test(self): return self.length def get_val_subj_idx(self, idx): for subj_idx, cnt in enumerate(self.q_cnts): if idx < cnt: return subj_idx, idx * self.q_max_slice else: idx -= cnt print("get_val_subj_idx function is not working.") assert False def get_test_subj_idx(self, idx): for subj_idx, cnt in enumerate(self.slice_cnts): if idx < cnt: return subj_idx, idx else: idx -= cnt print("get_test_subj_idx function is not working.") assert False def get_cnts(self): ## only for test loader return self.slice_cnts def img_load(self, img_path, seed=0): img_arr = np.load(img_path) + 0.25 return img_arr def set_support_volume(self, s_img_paths, s_label_paths): ## set support img path and label path for validation and testing self.s_img_paths = [] self.s_label_paths = [] self.s_fnames_list = [] for i in range(len(s_img_paths)): s_fnames = os.listdir(s_img_paths[i]) s_fnames = [int(e.split(".")[0]) for e in s_fnames] s_fnames.sort() print(f'support img {i} path : {s_img_paths[i]} length : {len(s_fnames)}') self.s_img_paths.append(s_img_paths[i]) self.s_label_paths.append(s_label_paths[i]) self.s_fnames_list.append([f"{e}.npy" for e in s_fnames]) class BaseLoader_CTORG(Base_dataset_ctorg): modal_i = [0] # there is only one modality label_i = 1.0 # there is only one label for each image class TrainLoader_CTORG(BaseLoader_CTORG): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class TestLoader_CTORG(BaseLoader_CTORG): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) if __name__ == "__main__": pass # main()
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/dataloaders_medical/dataset_decathlon.py
.py
14,795
458
import os import re import sys import json import random import numpy as np sys.path.append("/home/soopil/Desktop/github/python_utils") # sys.path.append("../dataloaders_medical") from dataloaders_medical.common import * # from common import * import cv2 from cv2 import resize def totensor(arr): tensor = torch.from_numpy(arr).float() # tensor = F.interpolate(tensor, size=size,mode=interp) return tensor def random_augment(s_imgs, s_labels, q_imgs, q_labels): ## do random rotation and flip k = random.sample([i for i in range(0, 4)], 1)[0] s_imgs = np.rot90(s_imgs, k, (3, 4)).copy() s_labels = np.rot90(s_labels, k, (3, 4)).copy() q_imgs = np.rot90(q_imgs, k, (2, 3)).copy() q_labels = np.rot90(q_labels, k, (2, 3)).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 3).copy() s_labels = np.flip(s_labels, 3).copy() q_imgs = np.flip(q_imgs, 2).copy() q_labels = np.flip(q_labels, 2).copy() if random.random() < 0.5: s_imgs = np.flip(s_imgs, 4).copy() s_labels = np.flip(s_labels, 4).copy() q_imgs = np.flip(q_imgs, 3).copy() q_labels = np.flip(q_labels, 3).copy() return s_imgs, s_labels, q_imgs, q_labels class Base_dataset(): def __init__(self, img_paths, label_paths, config): """ dataset constructor for training """ super().__init__() self.mode = config['mode'] self.length = config['n_iter'] self.valid_img_n = len(img_paths) self.size = config['size'] self.img_paths = img_paths self.label_paths = label_paths self.n_shot = config["n_shot"] self.s_idx = config["s_idx"] self.is_train = True crit = str(self.__class__).split("_")[-1][:4] print(f"training word : {crit}") if crit == "test": self.is_train = False ## load file names in advance self.img_lists = [] self.slice_cnts = [] for img_path in self.img_paths: fnames = os.listdir(img_path) self.slice_cnts.append(len(fnames)) fnames = [int(e.split(".")[0]) for e in fnames] fnames.sort() fnames = [f"{e}.npy" for e in fnames] self.img_lists.append(fnames) if not self.is_train: # for testing self.length = sum(self.slice_cnts) def get_sample(self, s_img_paths_all, s_label_paths_all, q_img_paths, q_label_paths): seed = random.randrange(0, 1000) # s_length = len(s_img_paths) s_imgs_all, s_labels_all = [], [] for s_idx, s_img_paths in enumerate(s_img_paths_all): s_label_paths = s_label_paths_all[s_idx] imgs, labels = [], [] for i in range(len(s_img_paths)): img_path, label_path = s_img_paths[i], s_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) s_imgs = np.stack(imgs, axis=0) s_labels = np.stack(labels, axis=0) s_imgs_all.append(s_imgs) s_labels_all.append(s_labels) s_imgs = np.stack(s_imgs_all, axis=0) s_labels = np.stack(s_labels_all, axis=0) q_length = len(q_img_paths) imgs, labels = [], [] for i in range(len(q_img_paths)): img_path, label_path = q_img_paths[i], q_label_paths[i] img = self.img_load(img_path, seed) img = resize(img, dsize=(self.size, self.size), interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) imgs.append(img) label = np.load(label_path) label = resize(label, dsize=(self.size, self.size), interpolation=cv2.INTER_NEAREST) label = np.expand_dims(label, axis=0) labels.append(label) q_imgs = np.stack(imgs, axis=0) q_labels = np.stack(labels, axis=0) # print(imgs.shape) [slice_num,1,256,256]? if self.is_train: ## random augmentation : flip, rotation s_imgs, s_labels, q_imgs, q_labels = random_augment(s_imgs, s_labels, q_imgs, q_labels) sample = { "s_x": totensor(s_imgs), "s_y": totensor(s_labels), # .long() "q_x": totensor(q_imgs), "q_y": totensor(q_labels), # .long() # "s_length":s_length, # "q_length":q_length, "s_fname": s_img_paths_all, "q_fname": q_img_paths, } return sample def handle_idx(self, s_n, q_idx, q_n): """ choose slices for support and query volume :return: supp_idx, qry_idx """ q_ratio = (q_idx) / (q_n - 1) s_idx = round((s_n - 1) * q_ratio) return s_idx def getitem_train(self): ## choose support and target idx_space = [i for i in range(self.valid_img_n)] subj_idxs = random.sample(idx_space, self.n_shot + 1) s_subj_idxs = subj_idxs[:self.n_shot] q_subj_idx = subj_idxs[self.n_shot] q_subj_img_path = self.img_paths[q_subj_idx] q_subj_label_path = self.label_paths[q_subj_idx] q_fnames = self.img_lists[q_subj_idx] q_idx = random.randrange(0, len(q_fnames)) is_flip = False if random.random() < 0.5: is_flip = True q_fnames.reverse() s_img_paths_all, s_label_paths_all = [], [] for s_subj_idx in s_subj_idxs: s_subj_img_path = self.img_paths[s_subj_idx] s_subj_label_path = self.label_paths[s_subj_idx] s_fnames = self.img_lists[s_subj_idx] ## flip augmentation if is_flip: s_fnames.reverse() ## choose support and query slice s_idx = self.handle_idx(len(s_fnames), q_idx, len(q_fnames)) s_fnames_selected = s_fnames[s_idx:s_idx + 1] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) q_fnames_selected = q_fnames[q_idx:q_idx + 1] q_img_paths_selected = [f"{q_subj_img_path}/{fname}" for fname in q_fnames_selected] q_label_paths_selected = [f"{q_subj_label_path}/{fname}" for fname in q_fnames_selected] return self.get_sample(s_img_paths_all, s_label_paths_all, q_img_paths_selected, q_label_paths_selected) def getitme_test(self, idx): q_subj_idx, q_idx = self.get_test_subj_idx(idx) q_subj_img_path = self.img_paths[q_subj_idx] q_subj_label_path = self.label_paths[q_subj_idx] q_fnames = self.img_lists[q_subj_idx] s_img_paths_all, s_label_paths_all = [], [] for s_idx in range(self.n_shot): s_subj_img_path = self.s_img_paths[s_idx] s_subj_label_path = self.s_label_paths[s_idx] s_fnames = self.s_fnames_list[s_idx] ## choose support and query slice s_idx = self.handle_idx(len(s_fnames), q_idx, len(q_fnames)) s_fnames_selected = s_fnames[s_idx:s_idx + 1] ## define path, load data, and return s_img_paths_selected = [f"{s_subj_img_path}/{fname}" for fname in s_fnames_selected] s_label_paths_selected = [f"{s_subj_label_path}/{fname}" for fname in s_fnames_selected] s_img_paths_all.append(s_img_paths_selected) s_label_paths_all.append(s_label_paths_selected) q_fnames_selected = q_fnames[q_idx:q_idx + 1] q_img_paths_selected = [f"{q_subj_img_path}/{fname}" for fname in q_fnames_selected] q_label_paths_selected = [f"{q_subj_label_path}/{fname}" for fname in q_fnames_selected] return self.get_sample(s_img_paths_all, s_label_paths_all, q_img_paths_selected, q_label_paths_selected) def get_len_train(self): return self.length def get_len_test(self): return self.length def get_val_subj_idx(self, idx): for subj_idx, cnt in enumerate(self.q_cnts): if idx < cnt: return subj_idx, idx * self.q_max_slice else: idx -= cnt print("get_val_subj_idx function is not working.") assert False def get_test_subj_idx(self, idx): for subj_idx, cnt in enumerate(self.slice_cnts): if idx < cnt: return subj_idx, idx else: idx -= cnt print("get_test_subj_idx function is not working.") assert False def get_cnts(self): ## only for test loader return self.slice_cnts def img_load(self, img_path, seed=0): img_arr = np.load(img_path) return img_arr def set_support_volume(self, s_img_paths, s_label_paths): ## set support img path and label path for validation and testing self.s_img_paths = [] self.s_label_paths = [] self.s_fnames_list = [] for i in range(len(s_img_paths)): s_fnames = os.listdir(s_img_paths[i]) s_fnames = [int(e.split(".")[0]) for e in s_fnames] s_fnames.sort() print(f'support img {i} path : {s_img_paths[i]} length : {len(s_fnames)}') self.s_img_paths.append(s_img_paths[i]) self.s_label_paths.append(s_label_paths[i]) self.s_fnames_list.append([f"{e}.npy" for e in s_fnames]) class Spleen_Base(Base_dataset): modal_i = 0 label_i = 1.0 class Spleen_train(Spleen_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Spleen_test(Spleen_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Liver_Base(Base_dataset): modal_i = 0 # only 1 modality label_i = 1.0 # use both 1 : cancer / 2 : liver class Liver_train(Liver_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Liver_test(Liver_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Tumor_Base(Base_dataset): modal_i = [0, 1, 2, 3] # 4 modalities label_i = 3.0 # 1 : edema / 2 : non enhancing tumor / 3 : enhancing tumour def img_load(self, img_path, seed=0): modal_idx = seed%len(self.modal_i) img_arr = np.load(img_path) return img_arr[modal_idx] # synchronize with query img and other support img class Tumor_train(Tumor_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Tumor_test(Tumor_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Prostate_Base(Base_dataset): modality_n = 2 modal_i = 0 label_i = 2.0 def img_load(self, img_path, seed=0): img_arr = np.load(img_path) return img_arr[self.modal_i] class Prostate_train(Prostate_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Prostate_test(Prostate_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Hippo_Base(Base_dataset): modal_i = 0 label_i = 1.0 # use both 1.0 and 2.0 class Hippo_train(Hippo_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Hippo_test(Hippo_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Lung_Base(Base_dataset): modal_i = 0 # only 1 modality label_i = 1.0 # use both 1 : cancer class Lung_train(Lung_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Lung_test(Lung_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class HepaticVessel_Base(Base_dataset): modality_n = 1 # modal_i = 0 label_i = 1.0 # 1 for vessel, 2 for tumour # use only vessel class HepaticVessel_train(HepaticVessel_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class HepaticVessel_test(HepaticVessel_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Heart_Base(Base_dataset): modality_n = 1 # modal_i = 0 label_i = 1.0 # 1 for left atrium class Heart_train(Heart_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Heart_test(Heart_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Pancreas_Base(Base_dataset): modality_n = 1 # only 1 modality # modal_i = 0 label_i = 1.0 # 1 for pancreas, 2 for cancer # use all of them class Pancreas_train(Pancreas_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Pancreas_test(Pancreas_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) class Colon_Base(Base_dataset): modality_n = 1 # only 1 modality # modal_i = 0 label_i = 1.0 # 1 for colon cancer primaries # use 1.0 class Colon_train(Colon_Base): def __len__(self): return self.get_len_train() def __getitem__(self, idx): return self.getitem_train() class Colon_test(Colon_Base): def __len__(self): return self.get_len_test() def __getitem__(self, idx): return self.getitme_test(idx) if __name__ == "__main__": pass # main()
Python
3D
oopil/3D_medical_image_FSS
FSS_SE/dataloaders_medical/prostate.py
.py
8,823
226
import sys import glob import json import re from glob import glob from util.utils import * from dataloaders_medical.decathlon import * from dataloaders_medical.dataset_decathlon import * from dataloaders_medical.dataset_CT_ORG import * import numpy as np class MetaSliceData_train(): def __init__(self, datasets, iter_n = 100): super().__init__() self.datasets = datasets self.dataset_n = len(datasets) self.iter_n =iter_n def __len__(self): return self.iter_n def __getitem__(self, idx): dataset = random.sample(self.datasets, 1)[0] return dataset.__getitem__(idx) def metadata(): info = { "src_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training", "trg_dir" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d", # 144 setting "trg_dir2" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_2", # 144 setting "trg_dir3" : "/user/home2/soopil/Datasets/MICCAI2015challenge/Abdomen/RawData/Training_2d_denoise", # "trg_dir" : "/home/soopil/Desktop/Dataset/MICCAI2015challenge/Abdomen/RawData/Training_2d", # desktop setting "Tasks" : [i for i in range(1,14)], # "Tasks" : [i for i in range(1,17+1)], # training : [1,2,3,5,6,7,8,9,14,15] # testing : [1,3,6,14] "Organs" : ["background", "spleen", #1 "right kidney", #2 "left kidney", #3 "gallbladder", #4 "esophagus", #5 "liver", #6 "stomach", #7 "aorta", #8 "inferior vana cava", #9 "portal vein & splenic vein", #10 "pancreas", #11 "right adrenal gland", #12 "left adrenal gland", #13 "bladder", #14 "uturus", #15 "rectum", #16 "small bowel", #17 ], } return info def meta_data(_config): def path_collect(idx, option='train'): # img_paths = glob(f"{meta['trg_dir2']}/{idx}/{option}/img/*") # label_paths = glob(f"{meta['trg_dir2']}/{idx}/{option}/label/*") img_paths = glob(f"{_config['data_src']}/{idx}/{option}/img/*") label_paths = glob(f"{_config['data_src']}/{idx}/{option}/label/*") return img_paths, label_paths def spliter(idx): tr_imgs, tr_labels = path_collect(idx, 'train') val_imgs, val_labels = path_collect(idx, 'valid') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels target_task = _config['target'] meta = metadata() print(meta['trg_dir']) # tasks = meta['Tasks'] tasks = [1,2,3,5,6,7,8,9,14,15] # tasks_remove = [4, 10, 12, 13] # 7 11 # tasks_remove = [4, 5, 8, 9, 10, 11, 12, 13] # tasks_remove = [4, 5, 8, 9, 10, 11, 12, 13, 16, 17] ## we sholdn't use both left and right kidneys # for task in tasks_remove: # tasks.remove(task) kidneys = [2,3] if target_task in kidneys: kidneys.remove(target_task) other_task = kidneys[0] try: tasks.remove(other_task) except: pass print(f"tasks : {tasks}") datasets = {} for task in tasks: tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = spliter(task) datasets[task] = [TrainLoader(tr_imgs, tr_labels, _config), TestLoader(val_imgs, val_labels, _config), TestLoader(ts_imgs, ts_labels, _config)] tr_imgs, tr_labels, val_imgs, val_labels, ts_imgs, ts_labels = spliter(target_task) if _config['add_target']: n_add_target = _config['add_target'] datasets[target_task] = [TrainLoader(tr_imgs[:n_add_target], tr_labels[:n_add_target], _config), TestLoader(val_imgs, val_labels, _config), TestLoader(ts_imgs, ts_labels, _config)] val_dataset = datasets[target_task][1] ts_dataset = datasets[target_task][2] tr_datasets = [dataset[0] for dataset in datasets.values()] else: val_dataset = datasets[target_task][1] ts_dataset = datasets[target_task][2] datasets.pop(target_task) #dictionary pop(key) tr_datasets = [dataset[0] for dataset in datasets.values()] print(f"training tasks : {datasets.keys()}") print(f"target tasks : {target_task}") ## set the support volume for testing if _config["internal_test"]: pass else: # _, _, ts_dataset = external_trainset(_config,target_task) tr_imgs, tr_labels, ts_dataset = external_testset(_config, target_task) val_dataset.set_support_volume(tr_imgs[_config['s_idx']:_config['s_idx'] + _config['n_shot']], tr_labels[_config['s_idx']:_config['s_idx'] + _config['n_shot']]) ts_dataset.set_support_volume(tr_imgs[_config['s_idx']:_config['s_idx'] + _config['n_shot']], tr_labels[_config['s_idx']:_config['s_idx'] + _config['n_shot']]) meta_tr_dataset = MetaSliceData_train(tr_datasets, iter_n=_config['n_iter']) return meta_tr_dataset, val_dataset, ts_dataset def external_testset(_config, target_task): def decathlon_spliter(idx): def path_collect(idx, option='train'): tasks = ["Task01_BrainTumour", "Task02_Heart", "Task03_Liver", "Task04_Hippocampus", "Task05_Prostate", "Task06_Lung", "Task07_Pancreas", "Task08_HepaticVessel", "Task09_Spleen", "Task10_Colon", "Task11_Davis" ] src_path = '/user/home2/soopil/Datasets/Decathlon_2d' img_paths = glob(f"{src_path}/{tasks[idx - 1]}/{option}/img/*") label_paths = glob(f"{src_path}/{tasks[idx - 1]}/{option}/label/*") return img_paths, label_paths tr_imgs, tr_labels = path_collect(idx, 'train') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, ts_imgs, ts_labels def CT_ORG_spliter(idx): def path_collect(idx, option='train'): Organs = ["background", "Liver", # 1 "Bladder", # 2 "Lung", # 3 "Kidney", # 4 "Bone", # 5 "Brain", # 6 ], src_path = "/user/home2/soopil/Datasets/CT_ORG/Training_2d_align" img_paths = glob(f"{src_path}/{idx}/{option}/img/*") label_paths = glob(f"{src_path}/{idx}/{option}/label/*") return img_paths, label_paths tr_imgs, tr_labels = path_collect(idx, 'train') ts_imgs, ts_labels = path_collect(idx, 'test') return tr_imgs, tr_labels, ts_imgs, ts_labels external = _config["external_test"] print(f"external testset : {external}") if external == "decathlon": if target_task == 1: # spleen target_idx_decath = 9 tr_imgs, tr_labels, ts_imgs, ts_labels = decathlon_spliter(target_idx_decath) ts_dataset = Spleen_test(ts_imgs, ts_labels, _config) # print(ts_imgs) elif target_task == 6: target_idx_decath = 3 tr_imgs, tr_labels, ts_imgs, ts_labels = decathlon_spliter(target_idx_decath) ts_dataset = Liver_test(ts_imgs, ts_labels, _config) else: print("There isn't according organ in Decathlon dataset.") assert False print(f"target index in external dataset : {target_idx_decath}") elif external == "CT_ORG": if target_task == 3: # kidney target_idx_ctorg = 4 tr_imgs, tr_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) ts_dataset = TestLoader_CTORG(ts_imgs, ts_labels, _config) elif target_task == 6: # liver target_idx_ctorg = 1 tr_imgs, tr_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) ts_dataset = TestLoader_CTORG(ts_imgs, ts_labels, _config) elif target_task == 14: # bladder target_idx_ctorg = 2 tr_imgs, tr_labels, ts_imgs, ts_labels = CT_ORG_spliter(target_idx_ctorg) ts_dataset = TestLoader_CTORG(ts_imgs, ts_labels, _config) else: print("There isn't according organ in CT_ORG dataset.") assert False print(f"target index in external dataset : {target_idx_ctorg}") else: print("configuration of external dataset is wrong") assert False return tr_imgs, tr_labels, ts_dataset if __name__=="__main__": pass
Python
3D
hku-mars/ImMesh
include/types.h
.h
1,421
37
#ifndef TYPES_H #define TYPES_H #include <Eigen/Eigen> #include <pcl/point_types.h> #include <pcl/point_cloud.h> typedef pcl::PointXYZINormal PointType; typedef pcl::PointXYZRGB PointTypeRGB; typedef pcl::PointCloud<PointType> PointCloudXYZI; typedef std::vector<PointType, Eigen::aligned_allocator<PointType>> PointVector; typedef pcl::PointCloud<PointTypeRGB> PointCloudXYZRGB; typedef Eigen::Vector2f V2F; typedef Eigen::Vector2d V2D; typedef Eigen::Vector3d V3D; typedef Eigen::Matrix3d M3D; typedef Eigen::Vector3f V3F; typedef Eigen::Matrix3f M3F; #define MD(a,b) Eigen::Matrix<double, (a), (b)> #define VD(a) Eigen::Matrix<double, (a), 1> #define MF(a,b) Eigen::Matrix<float, (a), (b)> #define VF(a) Eigen::Matrix<float, (a), 1> struct Pose6D { /*** the preintegrated Lidar states at the time of IMU measurements in a frame ***/ double offset_time; // the offset time of IMU measurement w.r.t the first lidar point double acc[3]; // the preintegrated total acceleration (global frame) at the Lidar origin double gyr[3]; // the unbiased angular velocity (body frame) at the Lidar origin double vel[3]; // the preintegrated velocity (global frame) at the Lidar origin double pos[3]; // the preintegrated position (global frame) at the Lidar origin double rot[9]; // the preintegrated rotation (global frame) at the Lidar origin }; #endif
Unknown
3D
hku-mars/ImMesh
include/so3_math.h
.h
2,739
106
#ifndef SO3_MATH_H #define SO3_MATH_H #include <math.h> #include <Eigen/Core> // #include <common_lib.h> #define SKEW_SYM_MATRX(v) 0.0,-v[2],v[1],v[2],0.0,-v[0],-v[1],v[0],0.0 template<typename T> Eigen::Matrix<T, 3, 3> Exp(const Eigen::Matrix<T, 3, 1> &&ang) { T ang_norm = ang.norm(); Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity(); if (ang_norm > 0.0000001) { Eigen::Matrix<T, 3, 1> r_axis = ang / ang_norm; Eigen::Matrix<T, 3, 3> K; K << SKEW_SYM_MATRX(r_axis); /// Roderigous Tranformation return Eye3 + std::sin(ang_norm) * K + (1.0 - std::cos(ang_norm)) * K * K; } else { return Eye3; } } template<typename T, typename Ts> Eigen::Matrix<T, 3, 3> Exp(const Eigen::Matrix<T, 3, 1> &ang_vel, const Ts &dt) { T ang_vel_norm = ang_vel.norm(); Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity(); if (ang_vel_norm > 0.0000001) { Eigen::Matrix<T, 3, 1> r_axis = ang_vel / ang_vel_norm; Eigen::Matrix<T, 3, 3> K; K << SKEW_SYM_MATRX(r_axis); T r_ang = ang_vel_norm * dt; /// Roderigous Tranformation return Eye3 + std::sin(r_ang) * K + (1.0 - std::cos(r_ang)) * K * K; } else { return Eye3; } } template<typename T> Eigen::Matrix<T, 3, 3> Exp(const T &v1, const T &v2, const T &v3) { T &&norm = sqrt(v1 * v1 + v2 * v2 + v3 * v3); Eigen::Matrix<T, 3, 3> Eye3 = Eigen::Matrix<T, 3, 3>::Identity(); if (norm > 0.00001) { T r_ang[3] = {v1 / norm, v2 / norm, v3 / norm}; Eigen::Matrix<T, 3, 3> K; K << SKEW_SYM_MATRX(r_ang); /// Roderigous Tranformation return Eye3 + std::sin(norm) * K + (1.0 - std::cos(norm)) * K * K; } else { return Eye3; } } /* Logrithm of a Rotation Matrix */ template<typename T> Eigen::Matrix<T,3,1> Log(const Eigen::Matrix<T, 3, 3> &R) { T theta = (R.trace() > 3.0 - 1e-6) ? 0.0 : std::acos(0.5 * (R.trace() - 1)); Eigen::Matrix<T,3,1> K(R(2,1) - R(1,2), R(0,2) - R(2,0), R(1,0) - R(0,1)); return (std::abs(theta) < 0.001) ? (0.5 * K) : (0.5 * theta / std::sin(theta) * K); } template<typename T> Eigen::Matrix<T, 3, 1> RotMtoEuler(const Eigen::Matrix<T, 3, 3> &rot) { T sy = sqrt(rot(0,0)*rot(0,0) + rot(1,0)*rot(1,0)); bool singular = sy < 1e-6; T x, y, z; if(!singular) { x = atan2(rot(2, 1), rot(2, 2)); y = atan2(-rot(2, 0), sy); z = atan2(rot(1, 0), rot(0, 0)); } else { x = atan2(-rot(1, 2), rot(1, 1)); y = atan2(-rot(2, 0), sy); z = 0; } Eigen::Matrix<T, 3, 1> ang(x, y, z); return ang; } #endif
Unknown
3D
hku-mars/ImMesh
include/feature.h
.h
2,224
66
// This file is part of SVO - Semi-direct Visual Odometry. // // Copyright (C) 2014 Christian Forster <forster at ifi dot uzh dot ch> // (Robotics and Perception Group, University of Zurich, Switzerland). // // SVO is free software: you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the Free Software // Foundation, either version 3 of the License, or any later version. // // SVO is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef SVO_FEATURE_H_ #define SVO_FEATURE_H_ #include <frame.h> #include <point.h> #include <common_lib.h> namespace lidar_selection { // A salient image region that is tracked across frames. struct Feature { EIGEN_MAKE_ALIGNED_OPERATOR_NEW enum FeatureType { CORNER, EDGELET }; int id_; FeatureType type; //!< Type can be corner or edgelet. Frame* frame; //!< Pointer to frame in which the feature was detected. cv::Mat img; vector<cv::Mat> ImgPyr; Vector2d px; //!< Coordinates in pixels on pyramid level 0. Vector3d f; //!< Unit-bearing vector of the feature. int level; //!< Image pyramid level where feature was extracted. Point* point; //!< Pointer to 3D point which corresponds to the feature. Vector2d grad; //!< Dominant gradient direction for edglets, normalized. float score; float error; // Vector2d grad_cur_; //!< edgelete grad direction in cur frame SE3 T_f_w_; float* patch; Feature(Point* _point, float* _patch, const Vector2d& _px, const Vector3d& _f, const SE3& _T_f_w, const float &_score, int _level) : type(CORNER), px(_px), f(_f), T_f_w_(_T_f_w), level(_level), patch(_patch), point(_point), score(_score) {} inline Vector3d pos() const { return T_f_w_.inverse().translation(); } }; } // namespace lidar_selection #endif // SVO_FEATURE_H_
Unknown
3D
hku-mars/ImMesh
include/common_lib.h
.h
12,251
404
#ifndef COMMON_LIB_H #define COMMON_LIB_H #pragma once #include <Eigen/Eigen> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <so3_math.h> #include <types.h> // #include <fast_lio/States.h> // #include <fast_lio/Pose6D.h> #include <boost/shared_ptr.hpp> #include <cv_bridge/cv_bridge.h> #include <eigen_conversions/eigen_msg.h> #include <nav_msgs/Odometry.h> #include <opencv2/opencv.hpp> #include <sensor_msgs/Imu.h> #include <tf/transform_broadcaster.h> #include <unordered_map> // #include <point.h> using namespace std; using namespace Eigen; // using namespace Sophus; // #define DEBUG_PRINT #define USE_ikdtree // #define USE_ikdforest //#define USE_IKFOM // #define USE_FOV_Checker #define print_line std::cout << __FILE__ << ", " << __LINE__ << std::endl; #define PI_M ( 3.14159265358 ) #define G_m_s2 ( 9.81 ) // Gravaty const in GuangDong/China #define DIM_STATE ( 18 ) // Dimension of states (Let Dim(SO(3)) = 3) #define DIM_PROC_N ( 12 ) // Dimension of process noise (Let Dim(SO(3)) = 3) #define CUBE_LEN ( 6.0 ) #define LIDAR_SP_LEN ( 2 ) #define INIT_COV ( 0.0000001 ) #define CALIB_ANGLE_COV ( 0.01 ) #define NUM_MATCH_POINTS ( 5 ) #define MAX_MEAS_DIM ( 10000 ) #define VEC_FROM_ARRAY( v ) v[ 0 ], v[ 1 ], v[ 2 ] #define MAT_FROM_ARRAY( v ) v[ 0 ], v[ 1 ], v[ 2 ], v[ 3 ], v[ 4 ], v[ 5 ], v[ 6 ], v[ 7 ], v[ 8 ] #define CONSTRAIN( v, min, max ) ( ( v > min ) ? ( ( v < max ) ? v : max ) : min ) #define ARRAY_FROM_EIGEN( mat ) mat.data(), mat.data() + mat.rows() * mat.cols() #define STD_VEC_FROM_EIGEN( mat ) vector< decltype( mat )::Scalar >( mat.data(), mat.data() + mat.rows() * mat.cols() ) #define DEBUG_FILE_DIR( name ) ( string( string( ROOT_DIR ) + "Log/" + name ) ) #define HASH_P 116101 #define MAX_N 10000000000 extern M3D Eye3d; extern M3F Eye3f; extern V3D Zero3d; extern V3F Zero3f; extern Vector3d Lidar_offset_to_IMU; enum LID_TYPE { AVIA = 1, VELO16 = 2, OUST64 = 3, L515 = 4, XT32 = 5, VELO32 = 6 }; //{1, 2, 3} enum TIME_UNIT { SEC = 0, MS = 1, US = 2, NS = 3 }; namespace lidar_selection { class Point; class VOXEL_POINTS { public: std::vector< Point * > voxel_points; int count; // bool is_visited; VOXEL_POINTS( int num ) : count( num ) {} }; class Warp { public: Matrix2d A_cur_ref; int search_level; // bool is_visited; Warp( int level, Matrix2d warp_matrix ) : search_level( level ), A_cur_ref( warp_matrix ) {} }; } // namespace lidar_selection // Key of hash table class VOXEL_KEY { public: int64_t x; int64_t y; int64_t z; VOXEL_KEY( int64_t vx = 0, int64_t vy = 0, int64_t vz = 0 ) : x( vx ), y( vy ), z( vz ) {} bool operator==( const VOXEL_KEY &other ) const { return ( x == other.x && y == other.y && z == other.z ); } bool operator<( const VOXEL_KEY &p ) const { if ( x < p.x ) return true; if ( x > p.x ) return false; if ( y < p.y ) return true; if ( y > p.y ) return false; if ( z < p.z ) return true; if ( z > p.z ) return false; } }; // Hash value namespace std { template <> struct hash< VOXEL_KEY > { size_t operator()( const VOXEL_KEY &s ) const { using std::hash; using std::size_t; // Compute individual hash values for first, // second and third and combine them using XOR // and bit shifting: // return ((hash<int64_t>()(s.x) ^ (hash<int64_t>()(s.y) << 1)) >> 1) ^ // (hash<int64_t>()(s.z) << 1); return ( ( ( hash< int64_t >()( s.z ) * HASH_P ) % MAX_N + hash< int64_t >()( s.y ) ) * HASH_P ) % MAX_N + hash< int64_t >()( s.x ); } }; } // namespace std struct MeasureGroup { double img_offset_time; deque< sensor_msgs::Imu::ConstPtr > imu; cv::Mat img; MeasureGroup() { img_offset_time = 0.0; }; }; struct LidarMeasureGroup { double lidar_beg_time; double last_update_time; PointCloudXYZI::Ptr lidar; deque< struct MeasureGroup > measures; bool is_lidar_end; int lidar_scan_index_now; LidarMeasureGroup() { lidar_beg_time = 0.0; is_lidar_end = false; this->lidar.reset( new PointCloudXYZI() ); this->measures.clear(); lidar_scan_index_now = 0; last_update_time = 0.0; }; void debug_show() { int i = 0; ROS_WARN( "Lidar selector debug:" ); std::cout << "last_update_time:" << setprecision( 20 ) << this->last_update_time << endl; std::cout << "lidar_beg_time:" << setprecision( 20 ) << this->lidar_beg_time << endl; // for (auto it = this->measures.begin(); it != this->measures.end(); // ++it,++i) { // std::cout<<"In "<<i<<" measures: "; // for (auto it_meas=it->imu.begin(); it_meas!=it->imu.end();++it_meas) // { // std::cout<<setprecision(20)<<(*it_meas)->header.stamp.toSec()-this->lidar_beg_time<<" // "; // } // std::cout<<"img_time:"<<setprecision(20)<<it->img_offset_time<<endl; // } std::cout << "is_lidar_end:" << this->is_lidar_end << "lidar_end_time:" << this->lidar->points.back().curvature / double( 1000 ) << endl; std::cout << "lidar_.points.size(): " << this->lidar->points.size() << endl << endl; }; }; struct StatesGroup { StatesGroup() { this->rot_end = M3D::Identity(); this->pos_end = Zero3d; this->vel_end = Zero3d; this->bias_g = Zero3d; this->bias_a = Zero3d; this->gravity = Zero3d; this->cov = Matrix< double, DIM_STATE, DIM_STATE >::Identity() * INIT_COV; // this->cov.block< 9, 9 >( 9, 9 ) = MD( 9, 9 )::Identity() * 0.00001; }; StatesGroup( const StatesGroup &b ) { this->rot_end = b.rot_end; this->pos_end = b.pos_end; this->vel_end = b.vel_end; this->bias_g = b.bias_g; this->bias_a = b.bias_a; this->gravity = b.gravity; this->cov = b.cov; }; StatesGroup &operator=( const StatesGroup &b ) { this->rot_end = b.rot_end; this->pos_end = b.pos_end; this->vel_end = b.vel_end; this->bias_g = b.bias_g; this->bias_a = b.bias_a; this->gravity = b.gravity; this->cov = b.cov; return *this; }; StatesGroup operator+( const Matrix< double, DIM_STATE, 1 > &state_add ) { StatesGroup a; a.rot_end = this->rot_end * Exp( state_add( 0, 0 ), state_add( 1, 0 ), state_add( 2, 0 ) ); a.pos_end = this->pos_end + state_add.block< 3, 1 >( 3, 0 ); a.vel_end = this->vel_end + state_add.block< 3, 1 >( 6, 0 ); a.bias_g = this->bias_g + state_add.block< 3, 1 >( 9, 0 ); a.bias_a = this->bias_a + state_add.block< 3, 1 >( 12, 0 ); a.gravity = this->gravity + state_add.block< 3, 1 >( 15, 0 ); a.cov = this->cov; return a; }; StatesGroup &operator+=( const Matrix< double, DIM_STATE, 1 > &state_add ) { this->rot_end = this->rot_end * Exp( state_add( 0, 0 ), state_add( 1, 0 ), state_add( 2, 0 ) ); this->pos_end += state_add.block< 3, 1 >( 3, 0 ); this->vel_end += state_add.block< 3, 1 >( 6, 0 ); this->bias_g += state_add.block< 3, 1 >( 9, 0 ); this->bias_a += state_add.block< 3, 1 >( 12, 0 ); this->gravity += state_add.block< 3, 1 >( 15, 0 ); return *this; }; Matrix< double, DIM_STATE, 1 > operator-( const StatesGroup &b ) { Matrix< double, DIM_STATE, 1 > a; M3D rotd( b.rot_end.transpose() * this->rot_end ); a.block< 3, 1 >( 0, 0 ) = Log( rotd ); a.block< 3, 1 >( 3, 0 ) = this->pos_end - b.pos_end; a.block< 3, 1 >( 6, 0 ) = this->vel_end - b.vel_end; a.block< 3, 1 >( 9, 0 ) = this->bias_g - b.bias_g; a.block< 3, 1 >( 12, 0 ) = this->bias_a - b.bias_a; a.block< 3, 1 >( 15, 0 ) = this->gravity - b.gravity; return a; }; void resetpose() { this->rot_end = M3D::Identity(); this->pos_end = Zero3d; this->vel_end = Zero3d; } M3D rot_end; // the estimated attitude (rotation matrix) at the end lidar // point V3D pos_end; // the estimated position at the end lidar point (world frame) V3D vel_end; // the estimated velocity at the end lidar point (world frame) V3D bias_g; // gyroscope bias V3D bias_a; // accelerator bias V3D gravity; // the estimated gravity acceleration Matrix< double, DIM_STATE, DIM_STATE > cov; // states covariance }; template < typename T > T rad2deg( T radians ) { return radians * 180.0 / PI_M; } template < typename T > T deg2rad( T degrees ) { return degrees * PI_M / 180.0; } template < typename T > auto set_pose6d( const double t, const Matrix< T, 3, 1 > &a, const Matrix< T, 3, 1 > &g, const Matrix< T, 3, 1 > &v, const Matrix< T, 3, 1 > &p, const Matrix< T, 3, 3 > &R ) { Pose6D rot_kp; rot_kp.offset_time = t; for ( int i = 0; i < 3; i++ ) { rot_kp.acc[ i ] = a( i ); rot_kp.gyr[ i ] = g( i ); rot_kp.vel[ i ] = v( i ); rot_kp.pos[ i ] = p( i ); for ( int j = 0; j < 3; j++ ) rot_kp.rot[ i * 3 + j ] = R( i, j ); } // Map<M3D>(rot_kp.rot, 3,3) = R; return move( rot_kp ); } /* comment plane equation: Ax + By + Cz + D = 0 convert to: A/D*x + B/D*y + C/D*z = -1 solve: A0*x0 = b0 where A0_i = [x_i, y_i, z_i], x0 = [A/D, B/D, C/D]^T, b0 = [-1, ..., -1]^T normvec: normalized x0 */ template < typename T > bool esti_normvector( Matrix< T, 3, 1 > &normvec, const PointVector &point, const T &threshold, const int &point_num ) { MatrixXf A( point_num, 3 ); MatrixXf b( point_num, 1 ); b.setOnes(); b *= -1.0f; for ( int j = 0; j < point_num; j++ ) { A( j, 0 ) = point[ j ].x; A( j, 1 ) = point[ j ].y; A( j, 2 ) = point[ j ].z; } normvec = A.colPivHouseholderQr().solve( b ); for ( int j = 0; j < point_num; j++ ) { if ( fabs( normvec( 0 ) * point[ j ].x + normvec( 1 ) * point[ j ].y + normvec( 2 ) * point[ j ].z + 1.0f ) > threshold ) { return false; } } normvec.normalize(); return true; } template < typename T > bool esti_plane( Matrix< T, 4, 1 > &pca_result, const PointVector &point, const T &threshold ) { Matrix< T, NUM_MATCH_POINTS, 3 > A; Matrix< T, NUM_MATCH_POINTS, 1 > b; b.setOnes(); b *= -1.0f; for ( int j = 0; j < NUM_MATCH_POINTS; j++ ) { A( j, 0 ) = point[ j ].x; A( j, 1 ) = point[ j ].y; A( j, 2 ) = point[ j ].z; } Matrix< T, 3, 1 > normvec = A.colPivHouseholderQr().solve( b ); T n = normvec.norm(); pca_result( 0 ) = normvec( 0 ) / n; pca_result( 1 ) = normvec( 1 ) / n; pca_result( 2 ) = normvec( 2 ) / n; pca_result( 3 ) = 1.0 / n; for ( int j = 0; j < NUM_MATCH_POINTS; j++ ) { if ( fabs( pca_result( 0 ) * point[ j ].x + pca_result( 1 ) * point[ j ].y + pca_result( 2 ) * point[ j ].z + pca_result( 3 ) ) > threshold ) { return false; } } // for (int j = 0; j < NUM_MATCH_POINTS; j++) // { // if (fabs(normvec(0) * point[j].x + normvec(1) * point[j].y + normvec(2) // * point[j].z + 1.0f) > threshold) // { // return false; // } // } // T n = normvec.norm(); // pca_result(0) = normvec(0) / n; // pca_result(1) = normvec(1) / n; // pca_result(2) = normvec(2) / n; // pca_result(3) = 1.0 / n; return true; } #endif
Unknown
3D
hku-mars/ImMesh
include/ikd-Tree/ikd_Tree.h
.h
10,683
321
#pragma once #include <stdio.h> #include <queue> #include <pthread.h> #include <chrono> #include <time.h> #include <unistd.h> #include <math.h> #include <algorithm> #include <memory> #include <pcl/point_types.h> #include "tools_eigen.hpp" #define EPSS 1e-6 #define Minimal_Unbalanced_Tree_Size 10 #define Multi_Thread_Rebuild_Point_Num 1500 #define DOWNSAMPLE_SWITCH true #define ForceRebuildPercentage 0.2 #define Q_LEN 1000000 using namespace std; struct ikdTree_PointType { float x, y, z; long m_pt_idx = -1; ikdTree_PointType( float px = 0.0f, float py = 0.0f, float pz = 0.0f ) { x = px; y = py; z = pz; m_pt_idx = -1; } template<typename T> void from_eigen_vec( const T & pt ) { x = pt(0); y = pt(1); z = pt(2); } template<typename T> ikdTree_PointType( const T & pt ) { from_eigen_vec(pt); m_pt_idx = -1; } template<typename T> ikdTree_PointType( const T & pt, const long & index ) { from_eigen_vec(pt); m_pt_idx = index; } template<typename T> void operator<<(const T & pt) { from_eigen_vec(pt); } }; struct BoxPointType { float vertex_min[ 3 ]; float vertex_max[ 3 ]; }; enum operation_set { ADD_POINT, DELETE_POINT, DELETE_BOX, ADD_BOX, DOWNSAMPLE_DELETE, PUSH_DOWN }; enum delete_point_storage_set { NOT_RECORD, DELETE_POINTS_REC, MULTI_THREAD_REC }; template < typename T > class MANUAL_Q { private: int head = 0, tail = 0, counter = 0; T q[ Q_LEN ]; bool is_empty; public: void pop(); T front(); T back(); void clear(); void push( T op ); bool empty(); int size(); }; template < typename PointType > class KD_TREE { public: using PointVector = vector< PointType, Eigen::aligned_allocator< PointType > >; using Ptr = shared_ptr< KD_TREE< PointType > >; struct KD_TREE_NODE { PointType point; uint8_t division_axis; int TreeSize = 1; int invalid_point_num = 0; int down_del_num = 0; bool point_deleted = false; bool tree_deleted = false; bool point_downsample_deleted = false; bool tree_downsample_deleted = false; bool need_push_down_to_left = false; bool need_push_down_to_right = false; bool working_flag = false; float radius_sq; pthread_mutex_t push_down_mutex_lock; float node_range_x[ 2 ], node_range_y[ 2 ], node_range_z[ 2 ]; KD_TREE_NODE * left_son_ptr = nullptr; KD_TREE_NODE * right_son_ptr = nullptr; KD_TREE_NODE * father_ptr = nullptr; // For paper data record float alpha_del; float alpha_bal; }; struct Operation_Logger_Type { PointType point; BoxPointType boxpoint; bool tree_deleted, tree_downsample_deleted; operation_set op; }; struct PointType_CMP { PointType point; float dist = 0.0; PointType_CMP( PointType p = PointType(), float d = INFINITY ) { this->point = p; this->dist = d; }; bool operator<( const PointType_CMP &a ) const { if ( fabs( dist - a.dist ) < 1e-10 ) return point.x < a.point.x; else return dist < a.dist; } }; class MANUAL_HEAP { public: MANUAL_HEAP( int max_capacity = 100 ) { cap = max_capacity; heap = new PointType_CMP[ max_capacity ]; heap_size = 0; } ~MANUAL_HEAP() { delete[] heap; } void pop() { if ( heap_size == 0 ) return; heap[ 0 ] = heap[ heap_size - 1 ]; heap_size--; MoveDown( 0 ); return; } PointType_CMP top() { return heap[ 0 ]; } void push( PointType_CMP point ) { if ( heap_size >= cap ) return; heap[ heap_size ] = point; FloatUp( heap_size ); heap_size++; return; } int size() { return heap_size; } void clear() { heap_size = 0; } private: int heap_size = 0; int cap = 0; PointType_CMP *heap; void MoveDown( int heap_index ) { int l = heap_index * 2 + 1; PointType_CMP tmp = heap[ heap_index ]; while ( l < heap_size ) { if ( l + 1 < heap_size && heap[ l ] < heap[ l + 1 ] ) l++; if ( tmp < heap[ l ] ) { heap[ heap_index ] = heap[ l ]; heap_index = l; l = heap_index * 2 + 1; } else break; } heap[ heap_index ] = tmp; return; } void FloatUp( int heap_index ) { int ancestor = ( heap_index - 1 ) / 2; PointType_CMP tmp = heap[ heap_index ]; while ( heap_index > 0 ) { if ( heap[ ancestor ] < tmp ) { heap[ heap_index ] = heap[ ancestor ]; heap_index = ancestor; ancestor = ( heap_index - 1 ) / 2; } else break; } heap[ heap_index ] = tmp; return; } }; private: // Multi-thread Tree Rebuild bool termination_flag = false; bool rebuild_flag = false; pthread_t rebuild_thread; pthread_mutex_t termination_flag_mutex_lock, rebuild_ptr_mutex_lock, working_flag_mutex, search_flag_mutex; pthread_mutex_t rebuild_logger_mutex_lock, points_deleted_rebuild_mutex_lock; // queue<Operation_Logger_Type> Rebuild_Logger; MANUAL_Q< Operation_Logger_Type > Rebuild_Logger; PointVector Rebuild_PCL_Storage; KD_TREE_NODE ** Rebuild_Ptr = nullptr; int search_mutex_counter = 0; static void * multi_thread_ptr( void *arg ); void multi_thread_rebuild(); void start_thread(); void stop_thread(); void run_operation( KD_TREE_NODE **root, Operation_Logger_Type operation ); // KD Tree Functions and augmented variables int Treesize_tmp = 0, Validnum_tmp = 0; float alpha_bal_tmp = 0.5, alpha_del_tmp = 0.0; float delete_criterion_param = 0.5f; float balance_criterion_param = 0.7f; float downsample_size = 0.2f; bool Delete_Storage_Disabled = false; KD_TREE_NODE *STATIC_ROOT_NODE = nullptr; PointVector Points_deleted; PointVector Downsample_Storage; PointVector Multithread_Points_deleted; void InitTreeNode( KD_TREE_NODE *root ); void Test_Lock_States( KD_TREE_NODE *root ); void BuildTree( KD_TREE_NODE **root, int l, int r, PointVector &Storage ); void Rebuild( KD_TREE_NODE **root ); int Delete_by_range( KD_TREE_NODE **root, BoxPointType boxpoint, bool allow_rebuild, bool is_downsample ); void Delete_by_point( KD_TREE_NODE **root, PointType point, bool allow_rebuild ); void Add_by_point( KD_TREE_NODE **root, PointType point, bool allow_rebuild, int father_axis ); void Add_by_range( KD_TREE_NODE **root, BoxPointType boxpoint, bool allow_rebuild ); void Search( KD_TREE_NODE *root, int k_nearest, PointType point, MANUAL_HEAP &q, double max_dist ); // priority_queue<PointType_CMP> void Search_by_range( KD_TREE_NODE *root, BoxPointType boxpoint, PointVector &Storage ); void Search_by_radius( KD_TREE_NODE *root, PointType point, float radius, PointVector &Storage ); bool Criterion_Check( KD_TREE_NODE *root ); void Push_Down( KD_TREE_NODE *root ); void Update( KD_TREE_NODE *root ); void delete_tree_nodes( KD_TREE_NODE **root ); void downsample( KD_TREE_NODE **root ); bool same_point( PointType a, PointType b ); float calc_dist( PointType a, PointType b ); float calc_box_dist( KD_TREE_NODE *node, PointType point ); static bool point_cmp_x( PointType a, PointType b ); static bool point_cmp_y( PointType a, PointType b ); static bool point_cmp_z( PointType a, PointType b ); public: KD_TREE( float delete_param = 0.5, float balance_param = 0.6, float box_length = 0.2 ); ~KD_TREE(); void Set_delete_criterion_param( float delete_param ); void Set_balance_criterion_param( float balance_param ); void set_downsample_param( float box_length ); void InitializeKDTree( float delete_param = 0.5, float balance_param = 0.7, float box_length = 0.2 ); int size(); int validnum(); void root_alpha( float &alpha_bal, float &alpha_del ); void Build( PointVector point_cloud ); void Nearest_Search( PointType point, int k_nearest, PointVector &Nearest_Points, vector< float > &Point_Distance, double max_dist = INFINITY ); void Box_Search( const BoxPointType &Box_of_Point, PointVector &Storage ); void Radius_Search( PointType point, const float radius, PointVector &Storage ); int Add_Points( PointVector &PointToAdd, bool downsample_on ); int Add_Point( PointType &PointToAdd, bool downsample_on ); void Add_Point_Boxes( vector< BoxPointType > &BoxPoints ); void Delete_Points( PointVector &PointToDel ); int Delete_Point_Boxes( vector< BoxPointType > &BoxPoints ); void flatten( KD_TREE_NODE *root, PointVector &Storage, delete_point_storage_set storage_type = delete_point_storage_set::NOT_RECORD); void acquire_removed_points( PointVector &removed_points ); BoxPointType tree_range(); PointVector PCL_Storage; KD_TREE_NODE *Root_Node = nullptr; int max_queue_size = 0; };
Unknown
3D
hku-mars/ImMesh
include/ikd-Tree/ikd_Tree.cpp
.cpp
73,438
1,828
#include "ikd_Tree.h" /* Description: ikd-Tree: an incremental k-d tree for robotic applications Author: Yixi Cai email: yixicai@connect.hku.hk */ template < typename PointType > KD_TREE< PointType >::KD_TREE( float delete_param, float balance_param, float box_length ) { delete_criterion_param = delete_param; balance_criterion_param = balance_param; downsample_size = box_length; Rebuild_Logger.clear(); termination_flag = false; start_thread(); } template < typename PointType > KD_TREE< PointType >::~KD_TREE() { stop_thread(); Delete_Storage_Disabled = true; delete_tree_nodes( &Root_Node ); PointVector().swap( PCL_Storage ); Rebuild_Logger.clear(); } template < typename PointType > void KD_TREE< PointType >::Set_delete_criterion_param( float delete_param ) { delete_criterion_param = delete_param; } template < typename PointType > void KD_TREE< PointType >::Set_balance_criterion_param( float balance_param ) { balance_criterion_param = balance_param; } template < typename PointType > void KD_TREE< PointType >::set_downsample_param( float downsample_param ) { downsample_size = downsample_param; } template < typename PointType > void KD_TREE< PointType >::InitializeKDTree( float delete_param, float balance_param, float box_length ) { Set_delete_criterion_param( delete_param ); Set_balance_criterion_param( balance_param ); set_downsample_param( box_length ); } template < typename PointType > void KD_TREE< PointType >::InitTreeNode( KD_TREE_NODE *root ) { root->point.x = 0.0f; root->point.y = 0.0f; root->point.z = 0.0f; root->node_range_x[ 0 ] = 0.0f; root->node_range_x[ 1 ] = 0.0f; root->node_range_y[ 0 ] = 0.0f; root->node_range_y[ 1 ] = 0.0f; root->node_range_z[ 0 ] = 0.0f; root->node_range_z[ 1 ] = 0.0f; root->division_axis = 0; root->father_ptr = nullptr; root->left_son_ptr = nullptr; root->right_son_ptr = nullptr; root->TreeSize = 0; root->invalid_point_num = 0; root->down_del_num = 0; root->point_deleted = false; root->tree_deleted = false; root->need_push_down_to_left = false; root->need_push_down_to_right = false; root->point_downsample_deleted = false; root->working_flag = false; pthread_mutex_init( &( root->push_down_mutex_lock ), NULL ); } template < typename PointType > int KD_TREE< PointType >::size() { int s = 0; if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { if ( Root_Node != nullptr ) { return Root_Node->TreeSize; } else { return 0; } } else { if ( !pthread_mutex_trylock( &working_flag_mutex ) ) { s = Root_Node->TreeSize; pthread_mutex_unlock( &working_flag_mutex ); return s; } else { return Treesize_tmp; } } } template < typename PointType > BoxPointType KD_TREE< PointType >::tree_range() { BoxPointType range; if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { if ( Root_Node != nullptr ) { range.vertex_min[ 0 ] = Root_Node->node_range_x[ 0 ]; range.vertex_min[ 1 ] = Root_Node->node_range_y[ 0 ]; range.vertex_min[ 2 ] = Root_Node->node_range_z[ 0 ]; range.vertex_max[ 0 ] = Root_Node->node_range_x[ 1 ]; range.vertex_max[ 1 ] = Root_Node->node_range_y[ 1 ]; range.vertex_max[ 2 ] = Root_Node->node_range_z[ 1 ]; } else { memset( &range, 0, sizeof( range ) ); } } else { if ( !pthread_mutex_trylock( &working_flag_mutex ) ) { range.vertex_min[ 0 ] = Root_Node->node_range_x[ 0 ]; range.vertex_min[ 1 ] = Root_Node->node_range_y[ 0 ]; range.vertex_min[ 2 ] = Root_Node->node_range_z[ 0 ]; range.vertex_max[ 0 ] = Root_Node->node_range_x[ 1 ]; range.vertex_max[ 1 ] = Root_Node->node_range_y[ 1 ]; range.vertex_max[ 2 ] = Root_Node->node_range_z[ 1 ]; pthread_mutex_unlock( &working_flag_mutex ); } else { memset( &range, 0, sizeof( range ) ); } } return range; } template < typename PointType > int KD_TREE< PointType >::validnum() { int s = 0; if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { if ( Root_Node != nullptr ) return ( Root_Node->TreeSize - Root_Node->invalid_point_num ); else return 0; } else { if ( !pthread_mutex_trylock( &working_flag_mutex ) ) { s = Root_Node->TreeSize - Root_Node->invalid_point_num; pthread_mutex_unlock( &working_flag_mutex ); return s; } else { return -1; } } } template < typename PointType > void KD_TREE< PointType >::root_alpha( float &alpha_bal, float &alpha_del ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { alpha_bal = Root_Node->alpha_bal; alpha_del = Root_Node->alpha_del; return; } else { if ( !pthread_mutex_trylock( &working_flag_mutex ) ) { alpha_bal = Root_Node->alpha_bal; alpha_del = Root_Node->alpha_del; pthread_mutex_unlock( &working_flag_mutex ); return; } else { alpha_bal = alpha_bal_tmp; alpha_del = alpha_del_tmp; return; } } } template < typename PointType > void KD_TREE< PointType >::start_thread() { pthread_mutex_init( &termination_flag_mutex_lock, NULL ); pthread_mutex_init( &rebuild_ptr_mutex_lock, NULL ); pthread_mutex_init( &rebuild_logger_mutex_lock, NULL ); pthread_mutex_init( &points_deleted_rebuild_mutex_lock, NULL ); pthread_mutex_init( &working_flag_mutex, NULL ); pthread_mutex_init( &search_flag_mutex, NULL ); pthread_create( &rebuild_thread, NULL, multi_thread_ptr, ( void * ) this ); // printf( "Multi thread started \n" ); } template < typename PointType > void KD_TREE< PointType >::stop_thread() { pthread_mutex_lock( &termination_flag_mutex_lock ); termination_flag = true; pthread_mutex_unlock( &termination_flag_mutex_lock ); if ( rebuild_thread ) pthread_join( rebuild_thread, NULL ); pthread_mutex_destroy( &termination_flag_mutex_lock ); pthread_mutex_destroy( &rebuild_logger_mutex_lock ); pthread_mutex_destroy( &rebuild_ptr_mutex_lock ); pthread_mutex_destroy( &points_deleted_rebuild_mutex_lock ); pthread_mutex_destroy( &working_flag_mutex ); pthread_mutex_destroy( &search_flag_mutex ); } template < typename PointType > void *KD_TREE< PointType >::multi_thread_ptr( void *arg ) { KD_TREE *handle = ( KD_TREE * ) arg; handle->multi_thread_rebuild(); return nullptr; } template < typename PointType > void KD_TREE< PointType >::multi_thread_rebuild() { bool terminated = false; KD_TREE_NODE *father_ptr, **new_node_ptr; pthread_mutex_lock( &termination_flag_mutex_lock ); terminated = termination_flag; pthread_mutex_unlock( &termination_flag_mutex_lock ); while ( !terminated ) { pthread_mutex_lock( &rebuild_ptr_mutex_lock ); pthread_mutex_lock( &working_flag_mutex ); if ( Rebuild_Ptr != nullptr ) { /* Traverse and copy */ if ( !Rebuild_Logger.empty() ) { printf( "\n\n\n\n\n\n\n\n\n\n\n ERROR!!! \n\n\n\n\n\n\n\n\n" ); } rebuild_flag = true; if ( *Rebuild_Ptr == Root_Node ) { Treesize_tmp = Root_Node->TreeSize; Validnum_tmp = Root_Node->TreeSize - Root_Node->invalid_point_num; alpha_bal_tmp = Root_Node->alpha_bal; alpha_del_tmp = Root_Node->alpha_del; } KD_TREE_NODE *old_root_node = ( *Rebuild_Ptr ); father_ptr = ( *Rebuild_Ptr )->father_ptr; PointVector().swap( Rebuild_PCL_Storage ); // Lock Search pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter != 0 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter = -1; pthread_mutex_unlock( &search_flag_mutex ); // Lock deleted points cache pthread_mutex_lock( &points_deleted_rebuild_mutex_lock ); flatten( *Rebuild_Ptr, Rebuild_PCL_Storage, MULTI_THREAD_REC ); // Unlock deleted points cache pthread_mutex_unlock( &points_deleted_rebuild_mutex_lock ); // Unlock Search pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter = 0; pthread_mutex_unlock( &search_flag_mutex ); pthread_mutex_unlock( &working_flag_mutex ); /* Rebuild and update missed operations*/ Operation_Logger_Type Operation; KD_TREE_NODE * new_root_node = nullptr; if ( int( Rebuild_PCL_Storage.size() ) > 0 ) { BuildTree( &new_root_node, 0, Rebuild_PCL_Storage.size() - 1, Rebuild_PCL_Storage ); // Rebuild has been done. Updates the blocked operations into the new tree pthread_mutex_lock( &working_flag_mutex ); pthread_mutex_lock( &rebuild_logger_mutex_lock ); int tmp_counter = 0; while ( !Rebuild_Logger.empty() ) { Operation = Rebuild_Logger.front(); max_queue_size = max( max_queue_size, Rebuild_Logger.size() ); Rebuild_Logger.pop(); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); pthread_mutex_unlock( &working_flag_mutex ); run_operation( &new_root_node, Operation ); tmp_counter++; if ( tmp_counter % 10 == 0 ) usleep( 1 ); pthread_mutex_lock( &working_flag_mutex ); pthread_mutex_lock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } /* Replace to original tree*/ // pthread_mutex_lock(&working_flag_mutex); pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter != 0 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter = -1; pthread_mutex_unlock( &search_flag_mutex ); if ( father_ptr->left_son_ptr == *Rebuild_Ptr ) { father_ptr->left_son_ptr = new_root_node; } else if ( father_ptr->right_son_ptr == *Rebuild_Ptr ) { father_ptr->right_son_ptr = new_root_node; } else { throw "Error: Father ptr incompatible with current node\n"; } if ( new_root_node != nullptr ) new_root_node->father_ptr = father_ptr; ( *Rebuild_Ptr ) = new_root_node; int valid_old = old_root_node->TreeSize - old_root_node->invalid_point_num; int valid_new = new_root_node->TreeSize - new_root_node->invalid_point_num; if ( father_ptr == STATIC_ROOT_NODE ) Root_Node = STATIC_ROOT_NODE->left_son_ptr; KD_TREE_NODE *update_root = *Rebuild_Ptr; while ( update_root != nullptr && update_root != Root_Node ) { update_root = update_root->father_ptr; if ( update_root->working_flag ) break; if ( update_root == update_root->father_ptr->left_son_ptr && update_root->father_ptr->need_push_down_to_left ) break; if ( update_root == update_root->father_ptr->right_son_ptr && update_root->father_ptr->need_push_down_to_right ) break; Update( update_root ); } pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter = 0; pthread_mutex_unlock( &search_flag_mutex ); Rebuild_Ptr = nullptr; pthread_mutex_unlock( &working_flag_mutex ); rebuild_flag = false; /* Delete discarded tree nodes */ delete_tree_nodes( &old_root_node ); } else { pthread_mutex_unlock( &working_flag_mutex ); } pthread_mutex_unlock( &rebuild_ptr_mutex_lock ); pthread_mutex_lock( &termination_flag_mutex_lock ); terminated = termination_flag; pthread_mutex_unlock( &termination_flag_mutex_lock ); usleep( 100 ); } printf( "Rebuild thread terminated normally\n" ); } template < typename PointType > void KD_TREE< PointType >::run_operation( KD_TREE_NODE **root, Operation_Logger_Type operation ) { switch ( operation.op ) { case ADD_POINT: Add_by_point( root, operation.point, false, ( *root )->division_axis ); break; case ADD_BOX: Add_by_range( root, operation.boxpoint, false ); break; case DELETE_POINT: Delete_by_point( root, operation.point, false ); break; case DELETE_BOX: Delete_by_range( root, operation.boxpoint, false, false ); break; case DOWNSAMPLE_DELETE: Delete_by_range( root, operation.boxpoint, false, true ); break; case PUSH_DOWN: ( *root )->tree_downsample_deleted |= operation.tree_downsample_deleted; ( *root )->point_downsample_deleted |= operation.tree_downsample_deleted; ( *root )->tree_deleted = operation.tree_deleted || ( *root )->tree_downsample_deleted; ( *root )->point_deleted = ( *root )->tree_deleted || ( *root )->point_downsample_deleted; if ( operation.tree_downsample_deleted ) ( *root )->down_del_num = ( *root )->TreeSize; if ( operation.tree_deleted ) ( *root )->invalid_point_num = ( *root )->TreeSize; else ( *root )->invalid_point_num = ( *root )->down_del_num; ( *root )->need_push_down_to_left = true; ( *root )->need_push_down_to_right = true; break; default: break; } } template < typename PointType > void KD_TREE< PointType >::Build( PointVector point_cloud ) { if ( Root_Node != nullptr ) { delete_tree_nodes( &Root_Node ); } if ( point_cloud.size() == 0 ) return; STATIC_ROOT_NODE = new KD_TREE_NODE; InitTreeNode( STATIC_ROOT_NODE ); BuildTree( &STATIC_ROOT_NODE->left_son_ptr, 0, point_cloud.size() - 1, point_cloud ); Update( STATIC_ROOT_NODE ); STATIC_ROOT_NODE->TreeSize = 0; Root_Node = STATIC_ROOT_NODE->left_son_ptr; } template < typename PointType > void KD_TREE< PointType >::Nearest_Search( PointType point, int k_nearest, PointVector &Nearest_Points, vector< float > &Point_Distance, double max_dist ) { MANUAL_HEAP q( 2 * k_nearest ); q.clear(); vector< float >().swap( Point_Distance ); if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { Search( Root_Node, k_nearest, point, q, max_dist ); } else { pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter == -1 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter += 1; pthread_mutex_unlock( &search_flag_mutex ); Search( Root_Node, k_nearest, point, q, max_dist ); pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter -= 1; pthread_mutex_unlock( &search_flag_mutex ); } int k_found = min( k_nearest, int( q.size() ) ); PointVector().swap( Nearest_Points ); vector< float >().swap( Point_Distance ); for ( int i = 0; i < k_found; i++ ) { Nearest_Points.insert( Nearest_Points.begin(), q.top().point ); Point_Distance.insert( Point_Distance.begin(), q.top().dist ); q.pop(); } return; } template < typename PointType > void KD_TREE< PointType >::Box_Search( const BoxPointType &Box_of_Point, PointVector &Storage ) { Storage.clear(); Search_by_range( Root_Node, Box_of_Point, Storage ); } template < typename PointType > void KD_TREE< PointType >::Radius_Search( PointType point, const float radius, PointVector &Storage ) { Storage.clear(); Search_by_radius( Root_Node, point, radius, Storage ); } template < typename PointType > int KD_TREE< PointType >::Add_Points( PointVector &PointToAdd, bool downsample_on ) { int NewPointSize = PointToAdd.size(); int tree_size = size(); BoxPointType Box_of_Point; PointType downsample_result, mid_point; bool downsample_switch = downsample_on && DOWNSAMPLE_SWITCH; float min_dist, tmp_dist; int tmp_counter = 0; for ( int i = 0; i < PointToAdd.size(); i++ ) { if ( Root_Node == nullptr ) { PointVector pts_vec{ PointToAdd[ 0 ] }; Build( pts_vec ); continue; } if ( downsample_switch ) { Box_of_Point.vertex_min[ 0 ] = floor( PointToAdd[ i ].x / downsample_size ) * downsample_size; Box_of_Point.vertex_max[ 0 ] = Box_of_Point.vertex_min[ 0 ] + downsample_size; Box_of_Point.vertex_min[ 1 ] = floor( PointToAdd[ i ].y / downsample_size ) * downsample_size; Box_of_Point.vertex_max[ 1 ] = Box_of_Point.vertex_min[ 1 ] + downsample_size; Box_of_Point.vertex_min[ 2 ] = floor( PointToAdd[ i ].z / downsample_size ) * downsample_size; Box_of_Point.vertex_max[ 2 ] = Box_of_Point.vertex_min[ 2 ] + downsample_size; mid_point.x = Box_of_Point.vertex_min[ 0 ] + ( Box_of_Point.vertex_max[ 0 ] - Box_of_Point.vertex_min[ 0 ] ) / 2.0; mid_point.y = Box_of_Point.vertex_min[ 1 ] + ( Box_of_Point.vertex_max[ 1 ] - Box_of_Point.vertex_min[ 1 ] ) / 2.0; mid_point.z = Box_of_Point.vertex_min[ 2 ] + ( Box_of_Point.vertex_max[ 2 ] - Box_of_Point.vertex_min[ 2 ] ) / 2.0; PointVector().swap( Downsample_Storage ); Search_by_range( Root_Node, Box_of_Point, Downsample_Storage ); min_dist = calc_dist( PointToAdd[ i ], mid_point ); downsample_result = PointToAdd[ i ]; for ( int index = 0; index < Downsample_Storage.size(); index++ ) { tmp_dist = calc_dist( Downsample_Storage[ index ], mid_point ); if ( tmp_dist < min_dist ) { min_dist = tmp_dist; downsample_result = Downsample_Storage[ index ]; } } if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { if ( Downsample_Storage.size() > 1 || same_point( PointToAdd[ i ], downsample_result ) ) { if ( Downsample_Storage.size() > 0 ) Delete_by_range( &Root_Node, Box_of_Point, true, true ); Add_by_point( &Root_Node, downsample_result, true, Root_Node->division_axis ); tmp_counter++; } } else { if ( Downsample_Storage.size() > 1 || same_point( PointToAdd[ i ], downsample_result ) ) { Operation_Logger_Type operation_delete, operation; operation_delete.boxpoint = Box_of_Point; operation_delete.op = DOWNSAMPLE_DELETE; operation.point = downsample_result; operation.op = ADD_POINT; pthread_mutex_lock( &working_flag_mutex ); if ( Downsample_Storage.size() > 0 ) Delete_by_range( &Root_Node, Box_of_Point, false, true ); Add_by_point( &Root_Node, downsample_result, false, Root_Node->division_axis ); tmp_counter++; if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); if ( Downsample_Storage.size() > 0 ) Rebuild_Logger.push( operation_delete ); Rebuild_Logger.push( operation ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); }; } } else { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { Add_by_point( &Root_Node, PointToAdd[ i ], true, Root_Node->division_axis ); } else { Operation_Logger_Type operation; operation.point = PointToAdd[ i ]; operation.op = ADD_POINT; pthread_mutex_lock( &working_flag_mutex ); Add_by_point( &Root_Node, PointToAdd[ i ], false, Root_Node->division_axis ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( operation ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } } return tmp_counter; } template < typename PointType > int KD_TREE< PointType >::Add_Point( PointType &PointToAdd, bool downsample_on ) { PointVector pt_vec{PointToAdd}; return Add_Points(pt_vec, downsample_on); } template < typename PointType > void KD_TREE< PointType >::Add_Point_Boxes( vector< BoxPointType > &BoxPoints ) { for ( int i = 0; i < BoxPoints.size(); i++ ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { Add_by_range( &Root_Node, BoxPoints[ i ], true ); } else { Operation_Logger_Type operation; operation.boxpoint = BoxPoints[ i ]; operation.op = ADD_BOX; pthread_mutex_lock( &working_flag_mutex ); Add_by_range( &Root_Node, BoxPoints[ i ], false ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( operation ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } return; } template < typename PointType > void KD_TREE< PointType >::Delete_Points( PointVector &PointToDel ) { for ( int i = 0; i < PointToDel.size(); i++ ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { Delete_by_point( &Root_Node, PointToDel[ i ], true ); } else { Operation_Logger_Type operation; operation.point = PointToDel[ i ]; operation.op = DELETE_POINT; pthread_mutex_lock( &working_flag_mutex ); Delete_by_point( &Root_Node, PointToDel[ i ], false ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( operation ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } return; } template < typename PointType > int KD_TREE< PointType >::Delete_Point_Boxes( vector< BoxPointType > &BoxPoints ) { int tmp_counter = 0; for ( int i = 0; i < BoxPoints.size(); i++ ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != Root_Node ) { tmp_counter += Delete_by_range( &Root_Node, BoxPoints[ i ], true, false ); } else { Operation_Logger_Type operation; operation.boxpoint = BoxPoints[ i ]; operation.op = DELETE_BOX; pthread_mutex_lock( &working_flag_mutex ); tmp_counter += Delete_by_range( &Root_Node, BoxPoints[ i ], false, false ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( operation ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } return tmp_counter; } template < typename PointType > void KD_TREE< PointType >::acquire_removed_points( PointVector &removed_points ) { pthread_mutex_lock( &points_deleted_rebuild_mutex_lock ); for ( int i = 0; i < Points_deleted.size(); i++ ) { removed_points.push_back( Points_deleted[ i ] ); } for ( int i = 0; i < Multithread_Points_deleted.size(); i++ ) { removed_points.push_back( Multithread_Points_deleted[ i ] ); } Points_deleted.clear(); Multithread_Points_deleted.clear(); pthread_mutex_unlock( &points_deleted_rebuild_mutex_lock ); return; } template < typename PointType > void KD_TREE< PointType >::BuildTree( KD_TREE_NODE **root, int l, int r, PointVector &Storage ) { if ( l > r ) return; *root = new KD_TREE_NODE; InitTreeNode( *root ); int mid = ( l + r ) >> 1; int div_axis = 0; int i; // Find the best division Axis float min_value[ 3 ] = { INFINITY, INFINITY, INFINITY }; float max_value[ 3 ] = { -INFINITY, -INFINITY, -INFINITY }; float dim_range[ 3 ] = { 0, 0, 0 }; for ( i = l; i <= r; i++ ) { min_value[ 0 ] = min( min_value[ 0 ], Storage[ i ].x ); min_value[ 1 ] = min( min_value[ 1 ], Storage[ i ].y ); min_value[ 2 ] = min( min_value[ 2 ], Storage[ i ].z ); max_value[ 0 ] = max( max_value[ 0 ], Storage[ i ].x ); max_value[ 1 ] = max( max_value[ 1 ], Storage[ i ].y ); max_value[ 2 ] = max( max_value[ 2 ], Storage[ i ].z ); } // Select the longest dimension as division axis for ( i = 0; i < 3; i++ ) dim_range[ i ] = max_value[ i ] - min_value[ i ]; for ( i = 1; i < 3; i++ ) if ( dim_range[ i ] > dim_range[ div_axis ] ) div_axis = i; // Divide by the division axis and recursively build. ( *root )->division_axis = div_axis; switch ( div_axis ) { case 0: nth_element( begin( Storage ) + l, begin( Storage ) + mid, begin( Storage ) + r + 1, point_cmp_x ); break; case 1: nth_element( begin( Storage ) + l, begin( Storage ) + mid, begin( Storage ) + r + 1, point_cmp_y ); break; case 2: nth_element( begin( Storage ) + l, begin( Storage ) + mid, begin( Storage ) + r + 1, point_cmp_z ); break; default: nth_element( begin( Storage ) + l, begin( Storage ) + mid, begin( Storage ) + r + 1, point_cmp_x ); break; } ( *root )->point = Storage[ mid ]; KD_TREE_NODE *left_son = nullptr, *right_son = nullptr; BuildTree( &left_son, l, mid - 1, Storage ); BuildTree( &right_son, mid + 1, r, Storage ); ( *root )->left_son_ptr = left_son; ( *root )->right_son_ptr = right_son; Update( ( *root ) ); return; } template < typename PointType > void KD_TREE< PointType >::Rebuild( KD_TREE_NODE **root ) { KD_TREE_NODE *father_ptr; if ( ( *root )->TreeSize >= Multi_Thread_Rebuild_Point_Num ) { if ( !pthread_mutex_trylock( &rebuild_ptr_mutex_lock ) ) { if ( Rebuild_Ptr == nullptr || ( ( *root )->TreeSize > ( *Rebuild_Ptr )->TreeSize ) ) { Rebuild_Ptr = root; } pthread_mutex_unlock( &rebuild_ptr_mutex_lock ); } } else { father_ptr = ( *root )->father_ptr; int size_rec = ( *root )->TreeSize; PCL_Storage.clear(); flatten( *root, PCL_Storage, DELETE_POINTS_REC ); delete_tree_nodes( root ); BuildTree( root, 0, PCL_Storage.size() - 1, PCL_Storage ); if ( *root != nullptr ) ( *root )->father_ptr = father_ptr; if ( *root == Root_Node ) STATIC_ROOT_NODE->left_son_ptr = *root; } return; } template < typename PointType > int KD_TREE< PointType >::Delete_by_range( KD_TREE_NODE **root, BoxPointType boxpoint, bool allow_rebuild, bool is_downsample ) { if ( ( *root ) == nullptr || ( *root )->tree_deleted ) return 0; ( *root )->working_flag = true; Push_Down( *root ); int tmp_counter = 0; if ( boxpoint.vertex_max[ 0 ] <= ( *root )->node_range_x[ 0 ] || boxpoint.vertex_min[ 0 ] > ( *root )->node_range_x[ 1 ] ) return 0; if ( boxpoint.vertex_max[ 1 ] <= ( *root )->node_range_y[ 0 ] || boxpoint.vertex_min[ 1 ] > ( *root )->node_range_y[ 1 ] ) return 0; if ( boxpoint.vertex_max[ 2 ] <= ( *root )->node_range_z[ 0 ] || boxpoint.vertex_min[ 2 ] > ( *root )->node_range_z[ 1 ] ) return 0; if ( boxpoint.vertex_min[ 0 ] <= ( *root )->node_range_x[ 0 ] && boxpoint.vertex_max[ 0 ] > ( *root )->node_range_x[ 1 ] && boxpoint.vertex_min[ 1 ] <= ( *root )->node_range_y[ 0 ] && boxpoint.vertex_max[ 1 ] > ( *root )->node_range_y[ 1 ] && boxpoint.vertex_min[ 2 ] <= ( *root )->node_range_z[ 0 ] && boxpoint.vertex_max[ 2 ] > ( *root )->node_range_z[ 1 ] ) { ( *root )->tree_deleted = true; ( *root )->point_deleted = true; ( *root )->need_push_down_to_left = true; ( *root )->need_push_down_to_right = true; tmp_counter = ( *root )->TreeSize - ( *root )->invalid_point_num; ( *root )->invalid_point_num = ( *root )->TreeSize; if ( is_downsample ) { ( *root )->tree_downsample_deleted = true; ( *root )->point_downsample_deleted = true; ( *root )->down_del_num = ( *root )->TreeSize; } return tmp_counter; } if ( !( *root )->point_deleted && boxpoint.vertex_min[ 0 ] <= ( *root )->point.x && boxpoint.vertex_max[ 0 ] > ( *root )->point.x && boxpoint.vertex_min[ 1 ] <= ( *root )->point.y && boxpoint.vertex_max[ 1 ] > ( *root )->point.y && boxpoint.vertex_min[ 2 ] <= ( *root )->point.z && boxpoint.vertex_max[ 2 ] > ( *root )->point.z ) { ( *root )->point_deleted = true; tmp_counter += 1; if ( is_downsample ) ( *root )->point_downsample_deleted = true; } Operation_Logger_Type delete_box_log; struct timespec Timeout; if ( is_downsample ) delete_box_log.op = DOWNSAMPLE_DELETE; else delete_box_log.op = DELETE_BOX; delete_box_log.boxpoint = boxpoint; if ( ( Rebuild_Ptr == nullptr ) || ( *root )->left_son_ptr != *Rebuild_Ptr ) { tmp_counter += Delete_by_range( &( ( *root )->left_son_ptr ), boxpoint, allow_rebuild, is_downsample ); } else { pthread_mutex_lock( &working_flag_mutex ); tmp_counter += Delete_by_range( &( ( *root )->left_son_ptr ), boxpoint, false, is_downsample ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( delete_box_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } if ( ( Rebuild_Ptr == nullptr ) || ( *root )->right_son_ptr != *Rebuild_Ptr ) { tmp_counter += Delete_by_range( &( ( *root )->right_son_ptr ), boxpoint, allow_rebuild, is_downsample ); } else { pthread_mutex_lock( &working_flag_mutex ); tmp_counter += Delete_by_range( &( ( *root )->right_son_ptr ), boxpoint, false, is_downsample ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( delete_box_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } Update( *root ); if ( Rebuild_Ptr != nullptr && *Rebuild_Ptr == *root && ( *root )->TreeSize < Multi_Thread_Rebuild_Point_Num ) Rebuild_Ptr = nullptr; bool need_rebuild = allow_rebuild & Criterion_Check( ( *root ) ); if ( need_rebuild ) Rebuild( root ); if ( ( *root ) != nullptr ) ( *root )->working_flag = false; return tmp_counter; } template < typename PointType > void KD_TREE< PointType >::Delete_by_point( KD_TREE_NODE **root, PointType point, bool allow_rebuild ) { if ( ( *root ) == nullptr || ( *root )->tree_deleted ) return; ( *root )->working_flag = true; Push_Down( *root ); if ( same_point( ( *root )->point, point ) && !( *root )->point_deleted ) { ( *root )->point_deleted = true; ( *root )->invalid_point_num += 1; if ( ( *root )->invalid_point_num == ( *root )->TreeSize ) ( *root )->tree_deleted = true; return; } Operation_Logger_Type delete_log; struct timespec Timeout; delete_log.op = DELETE_POINT; delete_log.point = point; if ( ( ( *root )->division_axis == 0 && point.x < ( *root )->point.x ) || ( ( *root )->division_axis == 1 && point.y < ( *root )->point.y ) || ( ( *root )->division_axis == 2 && point.z < ( *root )->point.z ) ) { if ( ( Rebuild_Ptr == nullptr ) || ( *root )->left_son_ptr != *Rebuild_Ptr ) { Delete_by_point( &( *root )->left_son_ptr, point, allow_rebuild ); } else { pthread_mutex_lock( &working_flag_mutex ); Delete_by_point( &( *root )->left_son_ptr, point, false ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( delete_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } else { if ( ( Rebuild_Ptr == nullptr ) || ( *root )->right_son_ptr != *Rebuild_Ptr ) { Delete_by_point( &( *root )->right_son_ptr, point, allow_rebuild ); } else { pthread_mutex_lock( &working_flag_mutex ); Delete_by_point( &( *root )->right_son_ptr, point, false ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( delete_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } Update( *root ); if ( Rebuild_Ptr != nullptr && *Rebuild_Ptr == *root && ( *root )->TreeSize < Multi_Thread_Rebuild_Point_Num ) Rebuild_Ptr = nullptr; bool need_rebuild = allow_rebuild & Criterion_Check( ( *root ) ); if ( need_rebuild ) Rebuild( root ); if ( ( *root ) != nullptr ) ( *root )->working_flag = false; return; } template < typename PointType > void KD_TREE< PointType >::Add_by_range( KD_TREE_NODE **root, BoxPointType boxpoint, bool allow_rebuild ) { if ( ( *root ) == nullptr ) return; ( *root )->working_flag = true; Push_Down( *root ); if ( boxpoint.vertex_max[ 0 ] <= ( *root )->node_range_x[ 0 ] || boxpoint.vertex_min[ 0 ] > ( *root )->node_range_x[ 1 ] ) return; if ( boxpoint.vertex_max[ 1 ] <= ( *root )->node_range_y[ 0 ] || boxpoint.vertex_min[ 1 ] > ( *root )->node_range_y[ 1 ] ) return; if ( boxpoint.vertex_max[ 2 ] <= ( *root )->node_range_z[ 0 ] || boxpoint.vertex_min[ 2 ] > ( *root )->node_range_z[ 1 ] ) return; if ( boxpoint.vertex_min[ 0 ] <= ( *root )->node_range_x[ 0 ] && boxpoint.vertex_max[ 0 ] > ( *root )->node_range_x[ 1 ] && boxpoint.vertex_min[ 1 ] <= ( *root )->node_range_y[ 0 ] && boxpoint.vertex_max[ 1 ] > ( *root )->node_range_y[ 1 ] && boxpoint.vertex_min[ 2 ] <= ( *root )->node_range_z[ 0 ] && boxpoint.vertex_max[ 2 ] > ( *root )->node_range_z[ 1 ] ) { ( *root )->tree_deleted = false || ( *root )->tree_downsample_deleted; ( *root )->point_deleted = false || ( *root )->point_downsample_deleted; ( *root )->need_push_down_to_left = true; ( *root )->need_push_down_to_right = true; ( *root )->invalid_point_num = ( *root )->down_del_num; return; } if ( boxpoint.vertex_min[ 0 ] <= ( *root )->point.x && boxpoint.vertex_max[ 0 ] > ( *root )->point.x && boxpoint.vertex_min[ 1 ] <= ( *root )->point.y && boxpoint.vertex_max[ 1 ] > ( *root )->point.y && boxpoint.vertex_min[ 2 ] <= ( *root )->point.z && boxpoint.vertex_max[ 2 ] > ( *root )->point.z ) { ( *root )->point_deleted = ( *root )->point_downsample_deleted; } Operation_Logger_Type add_box_log; struct timespec Timeout; add_box_log.op = ADD_BOX; add_box_log.boxpoint = boxpoint; if ( ( Rebuild_Ptr == nullptr ) || ( *root )->left_son_ptr != *Rebuild_Ptr ) { Add_by_range( &( ( *root )->left_son_ptr ), boxpoint, allow_rebuild ); } else { pthread_mutex_lock( &working_flag_mutex ); Add_by_range( &( ( *root )->left_son_ptr ), boxpoint, false ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( add_box_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } if ( ( Rebuild_Ptr == nullptr ) || ( *root )->right_son_ptr != *Rebuild_Ptr ) { Add_by_range( &( ( *root )->right_son_ptr ), boxpoint, allow_rebuild ); } else { pthread_mutex_lock( &working_flag_mutex ); Add_by_range( &( ( *root )->right_son_ptr ), boxpoint, false ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( add_box_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } Update( *root ); if ( Rebuild_Ptr != nullptr && *Rebuild_Ptr == *root && ( *root )->TreeSize < Multi_Thread_Rebuild_Point_Num ) Rebuild_Ptr = nullptr; bool need_rebuild = allow_rebuild & Criterion_Check( ( *root ) ); if ( need_rebuild ) Rebuild( root ); if ( ( *root ) != nullptr ) ( *root )->working_flag = false; return; } template < typename PointType > void KD_TREE< PointType >::Add_by_point( KD_TREE_NODE **root, PointType point, bool allow_rebuild, int father_axis ) { if ( *root == nullptr ) { *root = new KD_TREE_NODE; InitTreeNode( *root ); ( *root )->point = point; ( *root )->division_axis = ( father_axis + 1 ) % 3; Update( *root ); return; } ( *root )->working_flag = true; Operation_Logger_Type add_log; struct timespec Timeout; add_log.op = ADD_POINT; add_log.point = point; Push_Down( *root ); if ( ( ( *root )->division_axis == 0 && point.x < ( *root )->point.x ) || ( ( *root )->division_axis == 1 && point.y < ( *root )->point.y ) || ( ( *root )->division_axis == 2 && point.z < ( *root )->point.z ) ) { if ( ( Rebuild_Ptr == nullptr ) || ( *root )->left_son_ptr != *Rebuild_Ptr ) { Add_by_point( &( *root )->left_son_ptr, point, allow_rebuild, ( *root )->division_axis ); } else { pthread_mutex_lock( &working_flag_mutex ); Add_by_point( &( *root )->left_son_ptr, point, false, ( *root )->division_axis ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( add_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } else { if ( ( Rebuild_Ptr == nullptr ) || ( *root )->right_son_ptr != *Rebuild_Ptr ) { Add_by_point( &( *root )->right_son_ptr, point, allow_rebuild, ( *root )->division_axis ); } else { pthread_mutex_lock( &working_flag_mutex ); Add_by_point( &( *root )->right_son_ptr, point, false, ( *root )->division_axis ); if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( add_log ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } pthread_mutex_unlock( &working_flag_mutex ); } } Update( *root ); if ( Rebuild_Ptr != nullptr && *Rebuild_Ptr == *root && ( *root )->TreeSize < Multi_Thread_Rebuild_Point_Num ) Rebuild_Ptr = nullptr; bool need_rebuild = allow_rebuild & Criterion_Check( ( *root ) ); if ( need_rebuild ) Rebuild( root ); if ( ( *root ) != nullptr ) ( *root )->working_flag = false; return; } template < typename PointType > void KD_TREE< PointType >::Search( KD_TREE_NODE *root, int k_nearest, PointType point, MANUAL_HEAP &q, double max_dist ) { if ( root == nullptr || root->tree_deleted ) return; double cur_dist = calc_box_dist( root, point ); double max_dist_sqr = max_dist * max_dist; if ( cur_dist > max_dist_sqr ) return; int retval; if ( root->need_push_down_to_left || root->need_push_down_to_right ) { retval = pthread_mutex_trylock( &( root->push_down_mutex_lock ) ); if ( retval == 0 ) { Push_Down( root ); pthread_mutex_unlock( &( root->push_down_mutex_lock ) ); } else { pthread_mutex_lock( &( root->push_down_mutex_lock ) ); pthread_mutex_unlock( &( root->push_down_mutex_lock ) ); } } if ( !root->point_deleted ) { float dist = calc_dist( point, root->point ); if ( dist <= max_dist_sqr && ( q.size() < k_nearest || dist < q.top().dist ) ) { if ( q.size() >= k_nearest ) q.pop(); PointType_CMP current_point{ root->point, dist }; q.push( current_point ); } } int cur_search_counter; float dist_left_node = calc_box_dist( root->left_son_ptr, point ); float dist_right_node = calc_box_dist( root->right_son_ptr, point ); if ( q.size() < k_nearest || dist_left_node < q.top().dist && dist_right_node < q.top().dist ) { if ( dist_left_node <= dist_right_node ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->left_son_ptr ) { Search( root->left_son_ptr, k_nearest, point, q, max_dist ); } else { pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter == -1 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter += 1; pthread_mutex_unlock( &search_flag_mutex ); Search( root->left_son_ptr, k_nearest, point, q, max_dist ); pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter -= 1; pthread_mutex_unlock( &search_flag_mutex ); } if ( q.size() < k_nearest || dist_right_node < q.top().dist ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->right_son_ptr ) { Search( root->right_son_ptr, k_nearest, point, q, max_dist ); } else { pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter == -1 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter += 1; pthread_mutex_unlock( &search_flag_mutex ); Search( root->right_son_ptr, k_nearest, point, q, max_dist ); pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter -= 1; pthread_mutex_unlock( &search_flag_mutex ); } } } else { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->right_son_ptr ) { Search( root->right_son_ptr, k_nearest, point, q, max_dist ); } else { pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter == -1 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter += 1; pthread_mutex_unlock( &search_flag_mutex ); Search( root->right_son_ptr, k_nearest, point, q, max_dist ); pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter -= 1; pthread_mutex_unlock( &search_flag_mutex ); } if ( q.size() < k_nearest || dist_left_node < q.top().dist ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->left_son_ptr ) { Search( root->left_son_ptr, k_nearest, point, q, max_dist ); } else { pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter == -1 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter += 1; pthread_mutex_unlock( &search_flag_mutex ); Search( root->left_son_ptr, k_nearest, point, q, max_dist ); pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter -= 1; pthread_mutex_unlock( &search_flag_mutex ); } } } } else { if ( dist_left_node < q.top().dist ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->left_son_ptr ) { Search( root->left_son_ptr, k_nearest, point, q, max_dist ); } else { pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter == -1 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter += 1; pthread_mutex_unlock( &search_flag_mutex ); Search( root->left_son_ptr, k_nearest, point, q, max_dist ); pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter -= 1; pthread_mutex_unlock( &search_flag_mutex ); } } if ( dist_right_node < q.top().dist ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->right_son_ptr ) { Search( root->right_son_ptr, k_nearest, point, q, max_dist ); } else { pthread_mutex_lock( &search_flag_mutex ); while ( search_mutex_counter == -1 ) { pthread_mutex_unlock( &search_flag_mutex ); usleep( 1 ); pthread_mutex_lock( &search_flag_mutex ); } search_mutex_counter += 1; pthread_mutex_unlock( &search_flag_mutex ); Search( root->right_son_ptr, k_nearest, point, q, max_dist ); pthread_mutex_lock( &search_flag_mutex ); search_mutex_counter -= 1; pthread_mutex_unlock( &search_flag_mutex ); } } } return; } template < typename PointType > void KD_TREE< PointType >::Search_by_range( KD_TREE_NODE *root, BoxPointType boxpoint, PointVector &Storage ) { if ( root == nullptr ) return; Push_Down( root ); if ( boxpoint.vertex_max[ 0 ] <= root->node_range_x[ 0 ] || boxpoint.vertex_min[ 0 ] > root->node_range_x[ 1 ] ) return; if ( boxpoint.vertex_max[ 1 ] <= root->node_range_y[ 0 ] || boxpoint.vertex_min[ 1 ] > root->node_range_y[ 1 ] ) return; if ( boxpoint.vertex_max[ 2 ] <= root->node_range_z[ 0 ] || boxpoint.vertex_min[ 2 ] > root->node_range_z[ 1 ] ) return; if ( boxpoint.vertex_min[ 0 ] <= root->node_range_x[ 0 ] && boxpoint.vertex_max[ 0 ] > root->node_range_x[ 1 ] && boxpoint.vertex_min[ 1 ] <= root->node_range_y[ 0 ] && boxpoint.vertex_max[ 1 ] > root->node_range_y[ 1 ] && boxpoint.vertex_min[ 2 ] <= root->node_range_z[ 0 ] && boxpoint.vertex_max[ 2 ] > root->node_range_z[ 1 ] ) { flatten( root, Storage, NOT_RECORD ); return; } if ( boxpoint.vertex_min[ 0 ] <= root->point.x && boxpoint.vertex_max[ 0 ] > root->point.x && boxpoint.vertex_min[ 1 ] <= root->point.y && boxpoint.vertex_max[ 1 ] > root->point.y && boxpoint.vertex_min[ 2 ] <= root->point.z && boxpoint.vertex_max[ 2 ] > root->point.z ) { if ( !root->point_deleted ) Storage.push_back( root->point ); } if ( ( Rebuild_Ptr == nullptr ) || root->left_son_ptr != *Rebuild_Ptr ) { Search_by_range( root->left_son_ptr, boxpoint, Storage ); } else { pthread_mutex_lock( &search_flag_mutex ); Search_by_range( root->left_son_ptr, boxpoint, Storage ); pthread_mutex_unlock( &search_flag_mutex ); } if ( ( Rebuild_Ptr == nullptr ) || root->right_son_ptr != *Rebuild_Ptr ) { Search_by_range( root->right_son_ptr, boxpoint, Storage ); } else { pthread_mutex_lock( &search_flag_mutex ); Search_by_range( root->right_son_ptr, boxpoint, Storage ); pthread_mutex_unlock( &search_flag_mutex ); } return; } template < typename PointType > void KD_TREE< PointType >::Search_by_radius( KD_TREE_NODE *root, PointType point, float radius, PointVector &Storage ) { if ( root == nullptr ) return; Push_Down( root ); PointType range_center; range_center.x = ( root->node_range_x[ 0 ] + root->node_range_x[ 1 ] ) * 0.5; range_center.y = ( root->node_range_y[ 0 ] + root->node_range_y[ 1 ] ) * 0.5; range_center.z = ( root->node_range_z[ 0 ] + root->node_range_z[ 1 ] ) * 0.5; float dist = sqrt( calc_dist( range_center, point ) ); if ( dist > radius + sqrt( root->radius_sq ) ) return; if ( dist <= radius - sqrt( root->radius_sq ) ) { flatten( root, Storage, NOT_RECORD ); return; } if ( !root->point_deleted && calc_dist( root->point, point ) <= radius * radius ) { Storage.push_back( root->point ); } if ( ( Rebuild_Ptr == nullptr ) || root->left_son_ptr != *Rebuild_Ptr ) { Search_by_radius( root->left_son_ptr, point, radius, Storage ); } else { pthread_mutex_lock( &search_flag_mutex ); Search_by_radius( root->left_son_ptr, point, radius, Storage ); pthread_mutex_unlock( &search_flag_mutex ); } if ( ( Rebuild_Ptr == nullptr ) || root->right_son_ptr != *Rebuild_Ptr ) { Search_by_radius( root->right_son_ptr, point, radius, Storage ); } else { pthread_mutex_lock( &search_flag_mutex ); Search_by_radius( root->right_son_ptr, point, radius, Storage ); pthread_mutex_unlock( &search_flag_mutex ); } return; } template < typename PointType > bool KD_TREE< PointType >::Criterion_Check( KD_TREE_NODE *root ) { if ( root->TreeSize <= Minimal_Unbalanced_Tree_Size ) { return false; } float balance_evaluation = 0.0f; float delete_evaluation = 0.0f; KD_TREE_NODE *son_ptr = root->left_son_ptr; if ( son_ptr == nullptr ) son_ptr = root->right_son_ptr; delete_evaluation = float( root->invalid_point_num ) / root->TreeSize; balance_evaluation = float( son_ptr->TreeSize ) / ( root->TreeSize - 1 ); if ( delete_evaluation > delete_criterion_param ) { return true; } if ( balance_evaluation > balance_criterion_param || balance_evaluation < 1 - balance_criterion_param ) { return true; } return false; } template < typename PointType > void KD_TREE< PointType >::Push_Down( KD_TREE_NODE *root ) { if ( root == nullptr ) return; Operation_Logger_Type operation; operation.op = PUSH_DOWN; operation.tree_deleted = root->tree_deleted; operation.tree_downsample_deleted = root->tree_downsample_deleted; if ( root->need_push_down_to_left && root->left_son_ptr != nullptr ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->left_son_ptr ) { root->left_son_ptr->tree_downsample_deleted |= root->tree_downsample_deleted; root->left_son_ptr->point_downsample_deleted |= root->tree_downsample_deleted; root->left_son_ptr->tree_deleted = root->tree_deleted || root->left_son_ptr->tree_downsample_deleted; root->left_son_ptr->point_deleted = root->left_son_ptr->tree_deleted || root->left_son_ptr->point_downsample_deleted; if ( root->tree_downsample_deleted ) root->left_son_ptr->down_del_num = root->left_son_ptr->TreeSize; if ( root->tree_deleted ) root->left_son_ptr->invalid_point_num = root->left_son_ptr->TreeSize; else root->left_son_ptr->invalid_point_num = root->left_son_ptr->down_del_num; root->left_son_ptr->need_push_down_to_left = true; root->left_son_ptr->need_push_down_to_right = true; root->need_push_down_to_left = false; } else { pthread_mutex_lock( &working_flag_mutex ); root->left_son_ptr->tree_downsample_deleted |= root->tree_downsample_deleted; root->left_son_ptr->point_downsample_deleted |= root->tree_downsample_deleted; root->left_son_ptr->tree_deleted = root->tree_deleted || root->left_son_ptr->tree_downsample_deleted; root->left_son_ptr->point_deleted = root->left_son_ptr->tree_deleted || root->left_son_ptr->point_downsample_deleted; if ( root->tree_downsample_deleted ) root->left_son_ptr->down_del_num = root->left_son_ptr->TreeSize; if ( root->tree_deleted ) root->left_son_ptr->invalid_point_num = root->left_son_ptr->TreeSize; else root->left_son_ptr->invalid_point_num = root->left_son_ptr->down_del_num; root->left_son_ptr->need_push_down_to_left = true; root->left_son_ptr->need_push_down_to_right = true; if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( operation ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } root->need_push_down_to_left = false; pthread_mutex_unlock( &working_flag_mutex ); } } if ( root->need_push_down_to_right && root->right_son_ptr != nullptr ) { if ( Rebuild_Ptr == nullptr || *Rebuild_Ptr != root->right_son_ptr ) { root->right_son_ptr->tree_downsample_deleted |= root->tree_downsample_deleted; root->right_son_ptr->point_downsample_deleted |= root->tree_downsample_deleted; root->right_son_ptr->tree_deleted = root->tree_deleted || root->right_son_ptr->tree_downsample_deleted; root->right_son_ptr->point_deleted = root->right_son_ptr->tree_deleted || root->right_son_ptr->point_downsample_deleted; if ( root->tree_downsample_deleted ) root->right_son_ptr->down_del_num = root->right_son_ptr->TreeSize; if ( root->tree_deleted ) root->right_son_ptr->invalid_point_num = root->right_son_ptr->TreeSize; else root->right_son_ptr->invalid_point_num = root->right_son_ptr->down_del_num; root->right_son_ptr->need_push_down_to_left = true; root->right_son_ptr->need_push_down_to_right = true; root->need_push_down_to_right = false; } else { pthread_mutex_lock( &working_flag_mutex ); root->right_son_ptr->tree_downsample_deleted |= root->tree_downsample_deleted; root->right_son_ptr->point_downsample_deleted |= root->tree_downsample_deleted; root->right_son_ptr->tree_deleted = root->tree_deleted || root->right_son_ptr->tree_downsample_deleted; root->right_son_ptr->point_deleted = root->right_son_ptr->tree_deleted || root->right_son_ptr->point_downsample_deleted; if ( root->tree_downsample_deleted ) root->right_son_ptr->down_del_num = root->right_son_ptr->TreeSize; if ( root->tree_deleted ) root->right_son_ptr->invalid_point_num = root->right_son_ptr->TreeSize; else root->right_son_ptr->invalid_point_num = root->right_son_ptr->down_del_num; root->right_son_ptr->need_push_down_to_left = true; root->right_son_ptr->need_push_down_to_right = true; if ( rebuild_flag ) { pthread_mutex_lock( &rebuild_logger_mutex_lock ); Rebuild_Logger.push( operation ); pthread_mutex_unlock( &rebuild_logger_mutex_lock ); } root->need_push_down_to_right = false; pthread_mutex_unlock( &working_flag_mutex ); } } return; } template < typename PointType > void KD_TREE< PointType >::Update( KD_TREE_NODE *root ) { KD_TREE_NODE *left_son_ptr = root->left_son_ptr; KD_TREE_NODE *right_son_ptr = root->right_son_ptr; float tmp_range_x[ 2 ] = { INFINITY, -INFINITY }; float tmp_range_y[ 2 ] = { INFINITY, -INFINITY }; float tmp_range_z[ 2 ] = { INFINITY, -INFINITY }; // Update Tree Size if ( left_son_ptr != nullptr && right_son_ptr != nullptr ) { root->TreeSize = left_son_ptr->TreeSize + right_son_ptr->TreeSize + 1; root->invalid_point_num = left_son_ptr->invalid_point_num + right_son_ptr->invalid_point_num + ( root->point_deleted ? 1 : 0 ); root->down_del_num = left_son_ptr->down_del_num + right_son_ptr->down_del_num + ( root->point_downsample_deleted ? 1 : 0 ); root->tree_downsample_deleted = left_son_ptr->tree_downsample_deleted & right_son_ptr->tree_downsample_deleted & root->point_downsample_deleted; root->tree_deleted = left_son_ptr->tree_deleted && right_son_ptr->tree_deleted && root->point_deleted; if ( root->tree_deleted || ( !left_son_ptr->tree_deleted && !right_son_ptr->tree_deleted && !root->point_deleted ) ) { tmp_range_x[ 0 ] = min( min( left_son_ptr->node_range_x[ 0 ], right_son_ptr->node_range_x[ 0 ] ), root->point.x ); tmp_range_x[ 1 ] = max( max( left_son_ptr->node_range_x[ 1 ], right_son_ptr->node_range_x[ 1 ] ), root->point.x ); tmp_range_y[ 0 ] = min( min( left_son_ptr->node_range_y[ 0 ], right_son_ptr->node_range_y[ 0 ] ), root->point.y ); tmp_range_y[ 1 ] = max( max( left_son_ptr->node_range_y[ 1 ], right_son_ptr->node_range_y[ 1 ] ), root->point.y ); tmp_range_z[ 0 ] = min( min( left_son_ptr->node_range_z[ 0 ], right_son_ptr->node_range_z[ 0 ] ), root->point.z ); tmp_range_z[ 1 ] = max( max( left_son_ptr->node_range_z[ 1 ], right_son_ptr->node_range_z[ 1 ] ), root->point.z ); } else { if ( !left_son_ptr->tree_deleted ) { tmp_range_x[ 0 ] = min( tmp_range_x[ 0 ], left_son_ptr->node_range_x[ 0 ] ); tmp_range_x[ 1 ] = max( tmp_range_x[ 1 ], left_son_ptr->node_range_x[ 1 ] ); tmp_range_y[ 0 ] = min( tmp_range_y[ 0 ], left_son_ptr->node_range_y[ 0 ] ); tmp_range_y[ 1 ] = max( tmp_range_y[ 1 ], left_son_ptr->node_range_y[ 1 ] ); tmp_range_z[ 0 ] = min( tmp_range_z[ 0 ], left_son_ptr->node_range_z[ 0 ] ); tmp_range_z[ 1 ] = max( tmp_range_z[ 1 ], left_son_ptr->node_range_z[ 1 ] ); } if ( !right_son_ptr->tree_deleted ) { tmp_range_x[ 0 ] = min( tmp_range_x[ 0 ], right_son_ptr->node_range_x[ 0 ] ); tmp_range_x[ 1 ] = max( tmp_range_x[ 1 ], right_son_ptr->node_range_x[ 1 ] ); tmp_range_y[ 0 ] = min( tmp_range_y[ 0 ], right_son_ptr->node_range_y[ 0 ] ); tmp_range_y[ 1 ] = max( tmp_range_y[ 1 ], right_son_ptr->node_range_y[ 1 ] ); tmp_range_z[ 0 ] = min( tmp_range_z[ 0 ], right_son_ptr->node_range_z[ 0 ] ); tmp_range_z[ 1 ] = max( tmp_range_z[ 1 ], right_son_ptr->node_range_z[ 1 ] ); } if ( !root->point_deleted ) { tmp_range_x[ 0 ] = min( tmp_range_x[ 0 ], root->point.x ); tmp_range_x[ 1 ] = max( tmp_range_x[ 1 ], root->point.x ); tmp_range_y[ 0 ] = min( tmp_range_y[ 0 ], root->point.y ); tmp_range_y[ 1 ] = max( tmp_range_y[ 1 ], root->point.y ); tmp_range_z[ 0 ] = min( tmp_range_z[ 0 ], root->point.z ); tmp_range_z[ 1 ] = max( tmp_range_z[ 1 ], root->point.z ); } } } else if ( left_son_ptr != nullptr ) { root->TreeSize = left_son_ptr->TreeSize + 1; root->invalid_point_num = left_son_ptr->invalid_point_num + ( root->point_deleted ? 1 : 0 ); root->down_del_num = left_son_ptr->down_del_num + ( root->point_downsample_deleted ? 1 : 0 ); root->tree_downsample_deleted = left_son_ptr->tree_downsample_deleted & root->point_downsample_deleted; root->tree_deleted = left_son_ptr->tree_deleted && root->point_deleted; if ( root->tree_deleted || ( !left_son_ptr->tree_deleted && !root->point_deleted ) ) { tmp_range_x[ 0 ] = min( left_son_ptr->node_range_x[ 0 ], root->point.x ); tmp_range_x[ 1 ] = max( left_son_ptr->node_range_x[ 1 ], root->point.x ); tmp_range_y[ 0 ] = min( left_son_ptr->node_range_y[ 0 ], root->point.y ); tmp_range_y[ 1 ] = max( left_son_ptr->node_range_y[ 1 ], root->point.y ); tmp_range_z[ 0 ] = min( left_son_ptr->node_range_z[ 0 ], root->point.z ); tmp_range_z[ 1 ] = max( left_son_ptr->node_range_z[ 1 ], root->point.z ); } else { if ( !left_son_ptr->tree_deleted ) { tmp_range_x[ 0 ] = min( tmp_range_x[ 0 ], left_son_ptr->node_range_x[ 0 ] ); tmp_range_x[ 1 ] = max( tmp_range_x[ 1 ], left_son_ptr->node_range_x[ 1 ] ); tmp_range_y[ 0 ] = min( tmp_range_y[ 0 ], left_son_ptr->node_range_y[ 0 ] ); tmp_range_y[ 1 ] = max( tmp_range_y[ 1 ], left_son_ptr->node_range_y[ 1 ] ); tmp_range_z[ 0 ] = min( tmp_range_z[ 0 ], left_son_ptr->node_range_z[ 0 ] ); tmp_range_z[ 1 ] = max( tmp_range_z[ 1 ], left_son_ptr->node_range_z[ 1 ] ); } if ( !root->point_deleted ) { tmp_range_x[ 0 ] = min( tmp_range_x[ 0 ], root->point.x ); tmp_range_x[ 1 ] = max( tmp_range_x[ 1 ], root->point.x ); tmp_range_y[ 0 ] = min( tmp_range_y[ 0 ], root->point.y ); tmp_range_y[ 1 ] = max( tmp_range_y[ 1 ], root->point.y ); tmp_range_z[ 0 ] = min( tmp_range_z[ 0 ], root->point.z ); tmp_range_z[ 1 ] = max( tmp_range_z[ 1 ], root->point.z ); } } } else if ( right_son_ptr != nullptr ) { root->TreeSize = right_son_ptr->TreeSize + 1; root->invalid_point_num = right_son_ptr->invalid_point_num + ( root->point_deleted ? 1 : 0 ); root->down_del_num = right_son_ptr->down_del_num + ( root->point_downsample_deleted ? 1 : 0 ); root->tree_downsample_deleted = right_son_ptr->tree_downsample_deleted & root->point_downsample_deleted; root->tree_deleted = right_son_ptr->tree_deleted && root->point_deleted; if ( root->tree_deleted || ( !right_son_ptr->tree_deleted && !root->point_deleted ) ) { tmp_range_x[ 0 ] = min( right_son_ptr->node_range_x[ 0 ], root->point.x ); tmp_range_x[ 1 ] = max( right_son_ptr->node_range_x[ 1 ], root->point.x ); tmp_range_y[ 0 ] = min( right_son_ptr->node_range_y[ 0 ], root->point.y ); tmp_range_y[ 1 ] = max( right_son_ptr->node_range_y[ 1 ], root->point.y ); tmp_range_z[ 0 ] = min( right_son_ptr->node_range_z[ 0 ], root->point.z ); tmp_range_z[ 1 ] = max( right_son_ptr->node_range_z[ 1 ], root->point.z ); } else { if ( !right_son_ptr->tree_deleted ) { tmp_range_x[ 0 ] = min( tmp_range_x[ 0 ], right_son_ptr->node_range_x[ 0 ] ); tmp_range_x[ 1 ] = max( tmp_range_x[ 1 ], right_son_ptr->node_range_x[ 1 ] ); tmp_range_y[ 0 ] = min( tmp_range_y[ 0 ], right_son_ptr->node_range_y[ 0 ] ); tmp_range_y[ 1 ] = max( tmp_range_y[ 1 ], right_son_ptr->node_range_y[ 1 ] ); tmp_range_z[ 0 ] = min( tmp_range_z[ 0 ], right_son_ptr->node_range_z[ 0 ] ); tmp_range_z[ 1 ] = max( tmp_range_z[ 1 ], right_son_ptr->node_range_z[ 1 ] ); } if ( !root->point_deleted ) { tmp_range_x[ 0 ] = min( tmp_range_x[ 0 ], root->point.x ); tmp_range_x[ 1 ] = max( tmp_range_x[ 1 ], root->point.x ); tmp_range_y[ 0 ] = min( tmp_range_y[ 0 ], root->point.y ); tmp_range_y[ 1 ] = max( tmp_range_y[ 1 ], root->point.y ); tmp_range_z[ 0 ] = min( tmp_range_z[ 0 ], root->point.z ); tmp_range_z[ 1 ] = max( tmp_range_z[ 1 ], root->point.z ); } } } else { root->TreeSize = 1; root->invalid_point_num = ( root->point_deleted ? 1 : 0 ); root->down_del_num = ( root->point_downsample_deleted ? 1 : 0 ); root->tree_downsample_deleted = root->point_downsample_deleted; root->tree_deleted = root->point_deleted; tmp_range_x[ 0 ] = root->point.x; tmp_range_x[ 1 ] = root->point.x; tmp_range_y[ 0 ] = root->point.y; tmp_range_y[ 1 ] = root->point.y; tmp_range_z[ 0 ] = root->point.z; tmp_range_z[ 1 ] = root->point.z; } memcpy( root->node_range_x, tmp_range_x, sizeof( tmp_range_x ) ); memcpy( root->node_range_y, tmp_range_y, sizeof( tmp_range_y ) ); memcpy( root->node_range_z, tmp_range_z, sizeof( tmp_range_z ) ); float x_L = ( root->node_range_x[ 1 ] - root->node_range_x[ 0 ] ) * 0.5; float y_L = ( root->node_range_y[ 1 ] - root->node_range_y[ 0 ] ) * 0.5; float z_L = ( root->node_range_z[ 1 ] - root->node_range_z[ 0 ] ) * 0.5; root->radius_sq = x_L * x_L + y_L * y_L + z_L * z_L; if ( left_son_ptr != nullptr ) left_son_ptr->father_ptr = root; if ( right_son_ptr != nullptr ) right_son_ptr->father_ptr = root; if ( root == Root_Node && root->TreeSize > 3 ) { KD_TREE_NODE *son_ptr = root->left_son_ptr; if ( son_ptr == nullptr ) son_ptr = root->right_son_ptr; float tmp_bal = float( son_ptr->TreeSize ) / ( root->TreeSize - 1 ); root->alpha_del = float( root->invalid_point_num ) / root->TreeSize; root->alpha_bal = ( tmp_bal >= 0.5 - EPSS ) ? tmp_bal : 1 - tmp_bal; } return; } template < typename PointType > void KD_TREE< PointType >::flatten( KD_TREE_NODE *root, PointVector &Storage, delete_point_storage_set storage_type ) { if ( root == nullptr ) return; Push_Down( root ); if ( !root->point_deleted ) { Storage.push_back( root->point ); } flatten( root->left_son_ptr, Storage, storage_type ); flatten( root->right_son_ptr, Storage, storage_type ); switch ( storage_type ) { case NOT_RECORD: break; case DELETE_POINTS_REC: if ( root->point_deleted && !root->point_downsample_deleted ) { Points_deleted.push_back( root->point ); } break; case MULTI_THREAD_REC: if ( root->point_deleted && !root->point_downsample_deleted ) { Multithread_Points_deleted.push_back( root->point ); } break; default: break; } return; } template < typename PointType > void KD_TREE< PointType >::delete_tree_nodes( KD_TREE_NODE **root ) { if ( *root == nullptr ) return; Push_Down( *root ); delete_tree_nodes( &( *root )->left_son_ptr ); delete_tree_nodes( &( *root )->right_son_ptr ); pthread_mutex_destroy( &( *root )->push_down_mutex_lock ); delete *root; *root = nullptr; return; } template < typename PointType > bool KD_TREE< PointType >::same_point( PointType a, PointType b ) { return ( fabs( a.x - b.x ) < EPSS && fabs( a.y - b.y ) < EPSS && fabs( a.z - b.z ) < EPSS ); } template < typename PointType > float KD_TREE< PointType >::calc_dist( PointType a, PointType b ) { float dist = 0.0f; dist = ( a.x - b.x ) * ( a.x - b.x ) + ( a.y - b.y ) * ( a.y - b.y ) + ( a.z - b.z ) * ( a.z - b.z ); return dist; } template < typename PointType > float KD_TREE< PointType >::calc_box_dist( KD_TREE_NODE *node, PointType point ) { if ( node == nullptr ) return INFINITY; float min_dist = 0.0; if ( point.x < node->node_range_x[ 0 ] ) min_dist += ( point.x - node->node_range_x[ 0 ] ) * ( point.x - node->node_range_x[ 0 ] ); if ( point.x > node->node_range_x[ 1 ] ) min_dist += ( point.x - node->node_range_x[ 1 ] ) * ( point.x - node->node_range_x[ 1 ] ); if ( point.y < node->node_range_y[ 0 ] ) min_dist += ( point.y - node->node_range_y[ 0 ] ) * ( point.y - node->node_range_y[ 0 ] ); if ( point.y > node->node_range_y[ 1 ] ) min_dist += ( point.y - node->node_range_y[ 1 ] ) * ( point.y - node->node_range_y[ 1 ] ); if ( point.z < node->node_range_z[ 0 ] ) min_dist += ( point.z - node->node_range_z[ 0 ] ) * ( point.z - node->node_range_z[ 0 ] ); if ( point.z > node->node_range_z[ 1 ] ) min_dist += ( point.z - node->node_range_z[ 1 ] ) * ( point.z - node->node_range_z[ 1 ] ); return min_dist; } template < typename PointType > bool KD_TREE< PointType >::point_cmp_x( PointType a, PointType b ) { return a.x < b.x; } template < typename PointType > bool KD_TREE< PointType >::point_cmp_y( PointType a, PointType b ) { return a.y < b.y; } template < typename PointType > bool KD_TREE< PointType >::point_cmp_z( PointType a, PointType b ) { return a.z < b.z; } // manual queue template < typename T > void MANUAL_Q< T >::clear() { head = 0; tail = 0; counter = 0; is_empty = true; return; } template < typename T > void MANUAL_Q< T >::pop() { if ( counter == 0 ) return; head++; head %= Q_LEN; counter--; if ( counter == 0 ) is_empty = true; return; } template < typename T > T MANUAL_Q< T >::front() { return q[ head ]; } template < typename T > T MANUAL_Q< T >::back() { return q[ tail ]; } template < typename T > void MANUAL_Q< T >::push( T op ) { q[ tail ] = op; counter++; if ( is_empty ) is_empty = false; tail++; tail %= Q_LEN; } template < typename T > bool MANUAL_Q< T >::empty() { return is_empty; } template < typename T > int MANUAL_Q< T >::size() { return counter; } template class KD_TREE< ikdTree_PointType >; template class KD_TREE< pcl::PointXYZ >; template class KD_TREE< pcl::PointXYZI >; template class KD_TREE< pcl::PointXYZINormal >;
C++
3D
hku-mars/ImMesh
src/voxel_loc.hpp
.hpp
6,640
178
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "common_lib.h" #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/StdVector> #include <csignal> #include <fstream> #include <math.h> #include <mutex> #include <omp.h> #include <pcl/common/io.h> #include <ros/ros.h> #include <so3_math.h> #include <thread> #include <unistd.h> #include <unordered_map> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> // int layer_size[3] = {8, 5, 10}; // float eigen_value_array[3] = {0.0025, 0.0025, 0.0005}; typedef struct ptpl { Eigen::Vector3d point; Eigen::Vector3d normal; Eigen::Vector3d center; Eigen::Matrix< double, 6, 6 > plane_var; int layer; double d; double eigen_value; bool is_valid; } ptpl; typedef struct Point_with_var { Eigen::Vector3d m_point; Eigen::Vector3d m_point_world; Eigen::Matrix3d m_var; } Point_with_var; struct M_POINT { float xyz[ 3 ]; float intensity; int count = 0; }; typedef struct Plane { pcl::PointXYZINormal m_p_center; Eigen::Vector3d m_center; Eigen::Vector3d m_normal; Eigen::Matrix3d m_covariance; Eigen::Matrix< double, 6, 6 > m_plane_var; float m_radius = 0; float m_min_eigen_value = 1; float m_d = 0; int m_points_size = 0; bool m_is_plane = false; bool m_is_init = false; int m_id; bool m_is_update = false; } Plane; class VOXEL_LOC { public: int64_t x, y, z; VOXEL_LOC( int64_t vx = 0, int64_t vy = 0, int64_t vz = 0 ) : x( vx ), y( vy ), z( vz ) {} bool operator==( const VOXEL_LOC &other ) const { return ( x == other.x && y == other.y && z == other.z ); } }; // Hash value namespace std { template <> struct hash< VOXEL_LOC > { int64_t operator()( const VOXEL_LOC &s ) const { using std::hash; using std::size_t; return ( ( ( ( s.z ) * HASH_P ) % MAX_N + ( s.y ) ) * HASH_P ) % MAX_N + ( s.x ); } }; } // namespace std class OctoTree { public: std::vector< Point_with_var > m_temp_points_; Plane * m_plane_ptr_; int m_layer_; int m_max_layer_; int m_octo_state_; // 0 is end of tree, 1 is not OctoTree * m_leaves_[ 8 ]; double m_voxel_center_[ 3 ]; // x, y, z std::vector< int > m_layer_init_num_; float m_quater_length_; float m_planer_threshold_; int m_update_size_threshold_; int m_octo_init_size_; int m_max_points_size_; int m_new_points_; bool m_init_octo_; bool m_update_enable_; OctoTree( int max_layer, int layer, std::vector< int > layer_init_num, int max_point_size, float planer_threshold ) : m_max_layer_( max_layer ), m_layer_( layer ), m_layer_init_num_( layer_init_num ), m_max_points_size_( max_point_size ), m_planer_threshold_( planer_threshold ) { m_temp_points_.clear(); m_octo_state_ = 0; m_new_points_ = 0; // when new points num > 5, do a update m_update_size_threshold_ = 5; m_init_octo_ = false; m_update_enable_ = true; m_octo_init_size_ = m_layer_init_num_[ m_layer_ ]; for ( int i = 0; i < 8; i++ ) { m_leaves_[ i ] = nullptr; } m_plane_ptr_ = new Plane; } void init_plane( const std::vector< Point_with_var > &points, Plane *plane ); void init_octo_tree(); void cut_octo_tree(); void UpdateOctoTree( const Point_with_var &pv ); void updatePlane(); };
Unknown
3D
hku-mars/ImMesh
src/voxel_loc.cpp
.cpp
15,967
368
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "voxel_loc.hpp" int g_plane_id = 0; int g_max_layer = 4; int g_max_points = 1000; void OctoTree::init_plane( const std::vector< Point_with_var > &points, Plane *plane ) { plane->m_plane_var = Eigen::Matrix< double, 6, 6 >::Zero(); plane->m_covariance = Eigen::Matrix3d::Zero(); plane->m_center = Eigen::Vector3d::Zero(); plane->m_normal = Eigen::Vector3d::Zero(); plane->m_points_size = points.size(); plane->m_radius = 0; for ( auto pv : points ) { plane->m_covariance += pv.m_point * pv.m_point.transpose(); plane->m_center += pv.m_point; } plane->m_center = plane->m_center / plane->m_points_size; plane->m_covariance = plane->m_covariance / plane->m_points_size - plane->m_center * plane->m_center.transpose(); Eigen::EigenSolver< Eigen::Matrix3d > es( plane->m_covariance ); Eigen::Matrix3cd evecs = es.eigenvectors(); Eigen::Vector3cd evals = es.eigenvalues(); Eigen::Vector3d evalsReal; evalsReal = evals.real(); Eigen::Matrix3f::Index evalsMin, evalsMax; evalsReal.rowwise().sum().minCoeff( &evalsMin ); evalsReal.rowwise().sum().maxCoeff( &evalsMax ); int evalsMid = 3 - evalsMin - evalsMax; Eigen::Vector3d evecMin = evecs.real().col( evalsMin ); Eigen::Vector3d evecMid = evecs.real().col( evalsMid ); Eigen::Vector3d evecMax = evecs.real().col( evalsMax ); Eigen::Matrix3d J_Q; J_Q << 1.0 / plane->m_points_size, 0, 0, 0, 1.0 / plane->m_points_size, 0, 0, 0, 1.0 / plane->m_points_size; // && evalsReal(evalsMid) > 0.05 //&& evalsReal(evalsMid) > 0.01 if ( evalsReal( evalsMin ) < m_planer_threshold_ ) { for ( int i = 0; i < points.size(); i++ ) { Eigen::Matrix< double, 6, 3 > J; Eigen::Matrix3d F; for ( int m = 0; m < 3; m++ ) { if ( m != ( int ) evalsMin ) { Eigen::Matrix< double, 1, 3 > F_m = ( points[ i ].m_point - plane->m_center ).transpose() / ( ( plane->m_points_size ) * ( evalsReal[ evalsMin ] - evalsReal[ m ] ) ) * ( evecs.real().col( m ) * evecs.real().col( evalsMin ).transpose() + evecs.real().col( evalsMin ) * evecs.real().col( m ).transpose() ); F.row( m ) = F_m; } else { Eigen::Matrix< double, 1, 3 > F_m; F_m << 0, 0, 0; F.row( m ) = F_m; } } J.block< 3, 3 >( 0, 0 ) = evecs.real() * F; J.block< 3, 3 >( 3, 0 ) = J_Q; plane->m_plane_var += J * points[ i ].m_var * J.transpose(); } plane->m_normal << evecs.real()( 0, evalsMin ), evecs.real()( 1, evalsMin ), evecs.real()( 2, evalsMin ); plane->m_min_eigen_value = evalsReal( evalsMin ); plane->m_radius = sqrt( evalsReal( evalsMax ) ); plane->m_d = -( plane->m_normal( 0 ) * plane->m_center( 0 ) + plane->m_normal( 1 ) * plane->m_center( 1 ) + plane->m_normal( 2 ) * plane->m_center( 2 ) ); plane->m_p_center.x = plane->m_center( 0 ); plane->m_p_center.y = plane->m_center( 1 ); plane->m_p_center.z = plane->m_center( 2 ); plane->m_p_center.normal_x = plane->m_normal( 0 ); plane->m_p_center.normal_y = plane->m_normal( 1 ); plane->m_p_center.normal_z = plane->m_normal( 2 ); plane->m_is_plane = true; plane->m_is_update = true; if ( !plane->m_is_init ) { plane->m_id = g_plane_id; g_plane_id++; plane->m_is_init = true; } // Calc Normal and center covariance } else { if ( !plane->m_is_init ) { plane->m_id = g_plane_id; g_plane_id++; plane->m_is_init = true; } plane->m_is_update = true; plane->m_is_plane = false; } } void OctoTree::init_octo_tree() { if ( m_temp_points_.size() > m_octo_init_size_ ) { init_plane( m_temp_points_, m_plane_ptr_ ); if ( m_plane_ptr_->m_is_plane == true ) { m_octo_state_ = 0; } else { m_octo_state_ = 1; cut_octo_tree(); } m_init_octo_ = true; m_new_points_ = 0; // m_temp_points_.clear(); } } void OctoTree::cut_octo_tree() { if ( m_layer_ >= m_max_layer_ ) { m_octo_state_ = 0; return; } for ( size_t i = 0; i < m_temp_points_.size(); i++ ) { int xyz[ 3 ] = { 0, 0, 0 }; if ( m_temp_points_[ i ].m_point[ 0 ] > m_voxel_center_[ 0 ] ) { xyz[ 0 ] = 1; } if ( m_temp_points_[ i ].m_point[ 1 ] > m_voxel_center_[ 1 ] ) { xyz[ 1 ] = 1; } if ( m_temp_points_[ i ].m_point[ 2 ] > m_voxel_center_[ 2 ] ) { xyz[ 2 ] = 1; } int leafnum = 4 * xyz[ 0 ] + 2 * xyz[ 1 ] + xyz[ 2 ]; if ( m_leaves_[ leafnum ] == nullptr ) { m_leaves_[ leafnum ] = new OctoTree( m_max_layer_, m_layer_ + 1, m_layer_init_num_, m_max_points_size_, m_planer_threshold_ ); m_leaves_[ leafnum ]->m_voxel_center_[ 0 ] = m_voxel_center_[ 0 ] + ( 2 * xyz[ 0 ] - 1 ) * m_quater_length_; m_leaves_[ leafnum ]->m_voxel_center_[ 1 ] = m_voxel_center_[ 1 ] + ( 2 * xyz[ 1 ] - 1 ) * m_quater_length_; m_leaves_[ leafnum ]->m_voxel_center_[ 2 ] = m_voxel_center_[ 2 ] + ( 2 * xyz[ 2 ] - 1 ) * m_quater_length_; m_leaves_[ leafnum ]->m_quater_length_ = m_quater_length_ / 2; } m_leaves_[ leafnum ]->m_temp_points_.push_back( m_temp_points_[ i ] ); m_leaves_[ leafnum ]->m_new_points_++; } for ( uint i = 0; i < 8; i++ ) { if ( m_leaves_[ i ] != nullptr ) { if ( m_leaves_[ i ]->m_temp_points_.size() > m_leaves_[ i ]->m_octo_init_size_ ) { init_plane( m_leaves_[ i ]->m_temp_points_, m_leaves_[ i ]->m_plane_ptr_ ); if ( m_leaves_[ i ]->m_plane_ptr_->m_is_plane ) { m_leaves_[ i ]->m_octo_state_ = 0; } else { m_leaves_[ i ]->m_octo_state_ = 1; m_leaves_[ i ]->cut_octo_tree(); } m_leaves_[ i ]->m_init_octo_ = true; m_leaves_[ i ]->m_new_points_ = 0; // leaves_[i]->temp_points_.clear(); } } } } void OctoTree::UpdateOctoTree( const Point_with_var &pv ) { if ( !m_init_octo_ ) { m_new_points_++; m_temp_points_.push_back( pv ); if ( m_temp_points_.size() > m_octo_init_size_ ) { init_octo_tree(); } } else { if ( m_plane_ptr_->m_is_plane ) { if ( m_update_enable_ ) { m_new_points_++; m_temp_points_.push_back( pv ); if ( m_new_points_ > m_update_size_threshold_ ) { init_plane( m_temp_points_, m_plane_ptr_ ); m_new_points_ = 0; } if ( m_temp_points_.size() >= m_max_points_size_ ) { m_update_enable_ = false; std::vector< Point_with_var >().swap( m_temp_points_ ); m_new_points_ = 0; } } } else { if ( m_layer_ < m_max_layer_ ) { if ( m_temp_points_.size() != 0 ) { std::vector< Point_with_var >().swap( m_temp_points_ ); } int xyz[ 3 ] = { 0, 0, 0 }; if ( pv.m_point[ 0 ] > m_voxel_center_[ 0 ] ) { xyz[ 0 ] = 1; } if ( pv.m_point[ 1 ] > m_voxel_center_[ 1 ] ) { xyz[ 1 ] = 1; } if ( pv.m_point[ 2 ] > m_voxel_center_[ 2 ] ) { xyz[ 2 ] = 1; } int leafnum = 4 * xyz[ 0 ] + 2 * xyz[ 1 ] + xyz[ 2 ]; if ( m_leaves_[ leafnum ] != nullptr ) { m_leaves_[ leafnum ]->UpdateOctoTree( pv ); } else { m_leaves_[ leafnum ] = new OctoTree( m_max_layer_, m_layer_ + 1, m_layer_init_num_, m_max_points_size_, m_planer_threshold_ ); m_leaves_[ leafnum ]->m_voxel_center_[ 0 ] = m_voxel_center_[ 0 ] + ( 2 * xyz[ 0 ] - 1 ) * m_quater_length_; m_leaves_[ leafnum ]->m_voxel_center_[ 1 ] = m_voxel_center_[ 1 ] + ( 2 * xyz[ 1 ] - 1 ) * m_quater_length_; m_leaves_[ leafnum ]->m_voxel_center_[ 2 ] = m_voxel_center_[ 2 ] + ( 2 * xyz[ 2 ] - 1 ) * m_quater_length_; m_leaves_[ leafnum ]->m_quater_length_ = m_quater_length_ / 2; m_leaves_[ leafnum ]->UpdateOctoTree( pv ); } } else { if ( m_update_enable_ ) { m_new_points_++; m_temp_points_.push_back( pv ); if ( m_new_points_ > m_update_size_threshold_ ) { init_plane( m_temp_points_, m_plane_ptr_ ); m_new_points_ = 0; } if ( m_temp_points_.size() > g_max_points ) { m_update_enable_ = false; std::vector< Point_with_var >().swap( m_temp_points_ ); // m_temp_points_.clear(); } } } } } } void OctoTree::updatePlane() { if ( m_temp_points_.size() >= m_update_size_threshold_ ) { Eigen::Matrix3d old_covariance = m_plane_ptr_->m_covariance; Eigen::Vector3d old_center = m_plane_ptr_->m_center; Eigen::Matrix3d sum_ppt = ( m_plane_ptr_->m_covariance + m_plane_ptr_->m_center * m_plane_ptr_->m_center.transpose() ) * m_plane_ptr_->m_points_size; Eigen::Vector3d sum_p = m_plane_ptr_->m_center * m_plane_ptr_->m_points_size; for ( size_t i = 0; i < m_temp_points_.size(); i++ ) { const Point_with_var &pv = m_temp_points_[ i ]; sum_ppt += pv.m_point * pv.m_point.transpose(); sum_p += pv.m_point; } m_plane_ptr_->m_points_size = m_plane_ptr_->m_points_size + m_temp_points_.size(); m_plane_ptr_->m_center = sum_p / m_plane_ptr_->m_points_size; m_plane_ptr_->m_covariance = sum_ppt / m_plane_ptr_->m_points_size - m_plane_ptr_->m_center * m_plane_ptr_->m_center.transpose(); Eigen::EigenSolver< Eigen::Matrix3d > es( m_plane_ptr_->m_covariance ); Eigen::Matrix3cd evecs = es.eigenvectors(); Eigen::Vector3cd evals = es.eigenvalues(); Eigen::Vector3d evalsReal; //注意这里定义的MatrixXd里没有c evalsReal = evals.real(); //获取特征值实数部分 Eigen::Matrix3f::Index evalsMin, evalsMax; evalsReal.rowwise().sum().minCoeff( &evalsMin ); evalsReal.rowwise().sum().maxCoeff( &evalsMax ); // std::cout << "min eigen value:" << evalsReal(evalsMin) << // std::endl; if ( evalsReal( evalsMin ) < m_planer_threshold_ ) { m_plane_ptr_->m_normal << evecs.real()( 0, evalsMin ), evecs.real()( 1, evalsMin ), evecs.real()( 2, evalsMin ); m_plane_ptr_->m_min_eigen_value = evalsReal( evalsMin ); m_plane_ptr_->m_radius = sqrt( evalsReal( evalsMax ) ); m_plane_ptr_->m_d = -( m_plane_ptr_->m_normal( 0 ) * m_plane_ptr_->m_center( 0 ) + m_plane_ptr_->m_normal( 1 ) * m_plane_ptr_->m_center( 1 ) + m_plane_ptr_->m_normal( 2 ) * m_plane_ptr_->m_center( 2 ) ); m_plane_ptr_->m_p_center.x = m_plane_ptr_->m_center( 0 ); m_plane_ptr_->m_p_center.y = m_plane_ptr_->m_center( 1 ); m_plane_ptr_->m_p_center.z = m_plane_ptr_->m_center( 2 ); m_plane_ptr_->m_p_center.normal_x = m_plane_ptr_->m_normal( 0 ); m_plane_ptr_->m_p_center.normal_y = m_plane_ptr_->m_normal( 1 ); m_plane_ptr_->m_p_center.normal_z = m_plane_ptr_->m_normal( 2 ); m_plane_ptr_->m_is_plane = true; // m_temp_points_.clear(); m_new_points_ = 0; m_plane_ptr_->m_is_update = true; } else { // plane_ptr_->is_plane = false; m_plane_ptr_->m_is_update = true; m_plane_ptr_->m_covariance = old_covariance; m_plane_ptr_->m_center = old_center; m_plane_ptr_->m_points_size = m_plane_ptr_->m_points_size - m_temp_points_.size(); // m_temp_points_.clear(); m_new_points_ = 0; } } }
C++
3D
hku-mars/ImMesh
src/ImMesh_node.cpp
.cpp
21,817
537
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <stdio.h> #include <Eigen/Core> #include <csignal> #include <fstream> #include <math.h> #include <mutex> #include <omp.h> #include <ros/ros.h> #include <so3_math.h> #include <thread> #include <unistd.h> #include "IMU_Processing.h" #include <nav_msgs/Odometry.h> #include <nav_msgs/Path.h> #include <pcl/filters/voxel_grid.h> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <sensor_msgs/PointCloud2.h> #include <tf/transform_broadcaster.h> #include <tf/transform_datatypes.h> #include "preprocess.h" #include <geometry_msgs/Vector3.h> #include <livox_ros_driver/CustomMsg.h> #include <opencv2/opencv.hpp> #include "voxel_mapping.hpp" #include "tools/tools_color_printf.hpp" #include "tools/tools_data_io.hpp" #include "tools/tools_logger.hpp" #include "tools/tools_color_printf.hpp" #include "tools/tools_eigen.hpp" #include "tools/tools_random.hpp" #include "tools/lib_sophus/so3.hpp" #include "tools/lib_sophus/se3.hpp" #include "mesh_rec_display.hpp" #include "mesh_rec_geometry.hpp" double g_maximum_pe_error = 40; double g_initial_camera_exp_tim = 1.0; double g_max_incidence_angle = 90; Common_tools::Timer g_cost_time_logger; Eigen::Matrix3d g_camera_K; std::string data_path_file = std::string( Common_tools::get_home_folder() ).append( "/ImMesh_output/" ); int appending_pts_frame = ( int ) 5e3; double threshold_scale = 1.0; // normal double region_size = 10.0; // normal double minimum_pts = 0.1 * threshold_scale; double g_meshing_voxel_size = 0.4 * threshold_scale; GL_camera g_gl_camera; bool g_if_automatic_save_mesh = false; float g_alpha = 1.0; extern std::vector< vec_3 > pts_of_maps; bool show_background_color = false; float camera_focus = 2000; Global_map g_map_rgb_pts_mesh( 0 ); Triangle_manager g_triangles_manager; std::vector< Image_frame > g_image_frame_vec; std::vector< GLuint > g_texture_id_vec; long img_width = 0, img_heigh = 0; LiDAR_frame_pts_and_pose_vec g_eigen_vec_vec; bool g_flag_pause = false; int if_first_call = 1; std::string g_debug_string; int g_current_frame = -1; // GUI settting bool g_display_mesh = true; int g_enable_mesh_rec = true; int g_save_to_offline_bin = false; int g_display_face = 1; bool g_draw_LiDAR_point = true; float g_draw_path_size = 2.0; float g_display_camera_size = 1.0; float g_ply_smooth_factor = 1.0; int g_ply_smooth_k = 20.0; bool g_display_main_window = true; bool g_display_camera_pose_window = false; bool g_display_help_win = false; bool g_follow_cam = true; bool g_mesh_if_color = false; bool g_if_draw_z_plane = true; bool g_if_draw_wireframe = false; bool g_if_draw_depth = false; bool g_if_depth_bind_cam = true; bool g_force_refresh_triangle = false; extern Common_tools::Axis_shader g_axis_shader; extern Common_tools::Ground_plane_shader g_ground_plane_shader; ImVec4 g_mesh_color = ImVec4( 1.0, 1.0, 1.0, 1.0 ); Voxel_mapping voxel_mapping; void print_help_window( bool *if_display_help_win ) { ImGui::Begin( "--- Help ---", if_display_help_win ); ImGui::Text( "[H] | Display/Close main windows" ); ImGui::Text( "[C] | Show/Close camera pose windows" ); ImGui::Text( "[T] | Follow the camera" ); ImGui::Text( "[D] | Show/close the depth image" ); ImGui::Text( "[L] | Show/close the LiDAR points" ); ImGui::Text( "[M] | Show/close the mesh" ); ImGui::Text( "[S] | Save camera view" ); ImGui::Text( "[Z] | Load camera view" ); ImGui::Text( "[+/-] | Increase/Decrease the line width" ); ImGui::Text( "[F1] | Display help window" ); ImGui::Text( "[Space] | To pause the program" ); ImGui::Text( "[Esc] | Exit the program" ); ImGui::End(); } void get_last_avr_pose( int current_frame_idx, Eigen::Quaterniond &q_avr, vec_3 &t_vec ) { const int win_ssd = 1; mat_3_3 lidar_frame_to_camera_frame; // Clang-format off lidar_frame_to_camera_frame << 0, 0, -1, -1, 0, 0, 0, 1, 0; // Clang-format on q_avr = Eigen::Quaterniond::Identity(); t_vec = vec_3::Zero(); if ( current_frame_idx < 1 ) { return; } int frame_count = 0; int frame_s = std::max( 0, current_frame_idx - win_ssd ); vec_3 log_angle_acc = vec_3( 0, 0, 0 ); Eigen::Quaterniond q_first; for ( int frame_idx = frame_s; frame_idx < current_frame_idx; frame_idx++ ) { if ( g_eigen_vec_vec[ frame_idx ].second.size() != 0 ) { Eigen::Quaterniond pose_q( g_eigen_vec_vec[ frame_idx ].second.head< 4 >() ); pose_q.normalize(); if ( frame_count == 0 ) { q_first = pose_q; } q_avr = q_avr * pose_q; log_angle_acc += Sophus::SO3d( q_first.inverse() * pose_q ).log(); t_vec = t_vec + g_eigen_vec_vec[ frame_idx ].second.block( 4, 0, 3, 1 ); frame_count++; } } t_vec = t_vec / frame_count; q_avr = q_first * Sophus::SO3d::exp( log_angle_acc / frame_count ).unit_quaternion(); q_avr.normalize(); q_avr = q_avr * Eigen::Quaterniond( lidar_frame_to_camera_frame ); } int main( int argc, char **argv ) { // Setup window pcl::console::setVerbosityLevel( pcl::console::L_ALWAYS ); Common_tools::printf_software_version(); printf_program( "ImMesh: An Immediate LiDAR Localization and Meshing Framework" ); ros::init( argc, argv, "laserMapping" ); voxel_mapping.init_ros_node(); GLFWwindow *window = g_gl_camera.init_openGL_and_ImGUI( "ImMesh: An Immediate LiDAR Localization and Meshing Framework", 1, voxel_mapping.m_GUI_font_size ); if ( !gladLoadGLLoader( ( GLADloadproc ) glfwGetProcAddress ) ) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } Common_tools::Point_cloud_shader g_pt_shader; init_openGL_shader(); if ( window == nullptr ) { cout << "Window == nullptr" << endl; return 0; } g_enable_mesh_rec = voxel_mapping.m_if_enable_mesh_rec; cout << "Offline point cloud name: " << ANSI_COLOR_GREEN_BOLD << voxel_mapping.m_pointcloud_file_name << ANSI_COLOR_RESET << endl; if ( Common_tools::if_file_exist( voxel_mapping.m_pointcloud_file_name ) ) { pcl::PointCloud< pcl::PointXYZI > offline_pts; cout << "Loading data..." ; fflush( stdout ); pcl::io::loadPCDFile( voxel_mapping.m_pointcloud_file_name, offline_pts ); cout << " total of pts = " << offline_pts.points.size() << endl; cout << "g_map_rgb_pts_mesh.m_minimum_pts_size = " << g_map_rgb_pts_mesh.m_minimum_pts_size << endl; reconstruct_mesh_from_pointcloud( offline_pts.makeShared() ); } else if(voxel_mapping.m_pointcloud_file_name.length() > 5) { cout << ANSI_COLOR_RED_BOLD << "Offline point cloud file: " << voxel_mapping.m_pointcloud_file_name <<" NOT exist!!!, Please check!!!" << ANSI_COLOR_RESET << endl; while(1); } cout << "====Loading parameter=====" << endl; threshold_scale = voxel_mapping.m_meshing_distance_scale; minimum_pts = voxel_mapping.m_meshing_points_minimum_scale * voxel_mapping.m_meshing_distance_scale; g_meshing_voxel_size = voxel_mapping.m_meshing_voxel_resolution * voxel_mapping.m_meshing_distance_scale; appending_pts_frame = voxel_mapping.m_meshing_number_of_pts_append_to_map; region_size = voxel_mapping.m_meshing_region_size * voxel_mapping.m_meshing_distance_scale; g_display_mesh = voxel_mapping.m_if_draw_mesh; scope_color( ANSI_COLOR_YELLOW_BOLD ); cout << "=========Meshing config ========= " << endl; cout << "Threshold scale = " << threshold_scale << endl; cout << "Minimum pts distance = " << minimum_pts << endl; cout << "Voxel size = " << g_meshing_voxel_size << endl; cout << "Region size = " << region_size << endl; g_current_frame = -3e8; g_triangles_manager.m_pointcloud_map = &g_map_rgb_pts_mesh; g_map_rgb_pts_mesh.set_minimum_dis( minimum_pts ); g_map_rgb_pts_mesh.set_voxel_resolution( g_meshing_voxel_size ); g_triangles_manager.m_region_size = region_size; g_map_rgb_pts_mesh.m_recent_visited_voxel_activated_time = 0; cout << "==== Loading parameter end =====" << endl; std::thread thr_mapping = std::thread( &Voxel_mapping::service_LiDAR_update, &voxel_mapping ); std::thread thr = std::thread( service_refresh_and_synchronize_triangle, 100 ); std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); Common_tools::Timer disp_tim; g_flag_pause = false; std::string gl_camera_file_name = Common_tools::get_home_folder().append( "/ImMeshing.gl_camera" ); g_gl_camera.load_camera( gl_camera_file_name ); g_gl_camera.m_gl_cam.m_camera_z_far = 1500; g_gl_camera.m_gl_cam.m_camera_z_near = 0.1; // Rasterization configuration Cam_view m_depth_view_camera; m_depth_view_camera.m_display_w = 640; m_depth_view_camera.m_display_h = 480; m_depth_view_camera.m_camera_focus = 400; m_depth_view_camera.m_maximum_disp_depth = 150.0; m_depth_view_camera.m_draw_depth_pts_size = 2; m_depth_view_camera.m_draw_LiDAR_pts_size = m_depth_view_camera.m_draw_depth_pts_size; m_depth_view_camera.m_if_draw_depth_pts = true; vec_3 ext_rot_angle = vec_3( 0, 0, 0 ); while ( !glfwWindowShouldClose( window ) ) { g_gl_camera.draw_frame_start(); Eigen::Quaterniond q_last_avr; vec_3 t_last_avr; get_last_avr_pose( g_current_frame, q_last_avr, t_last_avr ); if ( g_if_draw_depth ) { Common_tools::Timer tim; tim.tic(); m_depth_view_camera.m_camera_z_far = g_gl_camera.m_gl_cam.m_camera_z_far; m_depth_view_camera.m_camera_z_near = g_gl_camera.m_gl_cam.m_camera_z_near; if ( g_if_depth_bind_cam ) m_depth_view_camera.set_camera_pose( q_last_avr.toRotationMatrix(), t_last_avr ); else m_depth_view_camera.set_camera_pose( g_gl_camera.m_gl_cam.m_camera_rot, g_gl_camera.m_gl_cam.m_camera_pos ); m_depth_view_camera.set_gl_matrix(); draw_triangle( m_depth_view_camera ); m_depth_view_camera.read_depth(); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); m_depth_view_camera.draw_depth_image(); g_gl_camera.set_gl_camera_pose_matrix(); if(m_depth_view_camera.m_if_draw_depth_pts) { g_draw_LiDAR_point = true; } } if ( g_display_main_window ) { ImGui::Begin( "ImMesh's Main_windows", &g_display_main_window ); // Create a window called "Hello, world!" and append into it. ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.75f), "ImMesh: An Immediate LiDAR Localization and Meshing Framework"); ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.75f), "Github: "); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "https://github.com/hku-mars/ImMesh"); ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 0.75f), "Author: "); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.5f, 0.5f, 1.0f, 1.0f), "Jiarong Lin & Chongjian Yuan"); if (ImGui::TreeNode("Help")) { ImGui::Text( "[H] | Display/Close main windows" ); ImGui::Text( "[C] | Show/Close camera pose windows" ); ImGui::Text( "[T] | Follow the camera" ); ImGui::Text( "[D] | Show/close the depth image" ); ImGui::Text( "[L] | Show/close the LiDAR points" ); ImGui::Text( "[M] | Show/close the mesh" ); ImGui::Text( "[S] | Save camera view" ); ImGui::Text( "[Z] | Load camera view" ); ImGui::Text( "[+/-] | Increase/Decrease the line width" ); ImGui::Text( "[F1] | Display help window" ); ImGui::Text( "[Space]| To pause the program" ); ImGui::Text( "[Esc] | Exit the program" ); ImGui::TreePop(); ImGui::Separator(); } ImGui::SetNextItemOpen(true, 1); // ImGui::SetNextTreeNodeOpen(); if (ImGui::TreeNode("Draw Online reconstructed mesh options:")) { ImGui::RadioButton("Draw mesh's Facet", &g_display_face, 1); ImGui::RadioButton("Draw mesh's Wireframe", &g_display_face, 0); if(ImGui::Checkbox( "Draw mesh with color", &g_mesh_if_color )) { g_force_refresh_triangle = true; } ImGui::TreePop(); ImGui::Separator(); } if (ImGui::TreeNode("LiDAR pointcloud reinforcement")) { ImGui::Checkbox( "Enable", &g_if_draw_depth ); if(g_if_draw_depth) { ImGui::Checkbox( "If depth in sensor frame", &g_if_depth_bind_cam ); } ImGui::SliderInt( "Reinforced point size", &m_depth_view_camera.m_draw_depth_pts_size, 0, 10 ); ImGui::SliderInt( "LiDAR point size", &m_depth_view_camera.m_draw_LiDAR_pts_size, 0, 10 ); ImGui::TreePop(); ImGui::Separator(); } ImGui::Checkbox( "Move follow camera", &g_follow_cam ); ImGui::Checkbox( "Mapping pause", &g_flag_pause ); ImGui::Checkbox( "Draw LiDAR point", &g_draw_LiDAR_point ); if(g_draw_LiDAR_point) { ImGui::SliderInt( "LiDAR point size", & m_depth_view_camera.m_draw_LiDAR_pts_size, 0, 10 ); } ImGui::Checkbox( "Axis and Z_plane", &g_if_draw_z_plane ); ImGui::SliderFloat( "Path width", &g_draw_path_size, 1.0, 10.0f ); ImGui::SliderFloat( "Camera size", &g_display_camera_size, 0.01, 10.0, "%lf", ImGuiSliderFlags_Logarithmic ); if ( ImGui::Button( " Save Mesh to PLY file " ) ) { int temp_flag = g_flag_pause; g_flag_pause = true; Common_tools::create_dir( data_path_file ); save_to_ply_file( std::string( data_path_file ).append( "/rec_mesh.ply" ), g_ply_smooth_factor, g_ply_smooth_k ); g_flag_pause = temp_flag; } if ( ImGui::Button( "Load Camera view" ) ) { g_gl_camera.load_camera( gl_camera_file_name ); } if ( ImGui::Button( "Save Camera view" ) ) { cout << "Save view to " << gl_camera_file_name << endl; g_gl_camera.save_camera( gl_camera_file_name ); } ImGui::Checkbox( "Show OpenGL camera paras", &g_display_camera_pose_window ); ImGui::Text( "Refresh rate %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate ); if ( ImGui::Button( " Exit Program " ) ) // Buttons return true when clicked (most widgets return true when edited/activated) glfwSetWindowShouldClose( window, 1 ); ImGui::End(); } if(g_draw_LiDAR_point) { if ( m_depth_view_camera.m_if_draw_depth_pts ) { if ( m_depth_view_camera.m_draw_LiDAR_pts_size > 0 ) { display_current_LiDAR_pts( g_current_frame, m_depth_view_camera.m_draw_LiDAR_pts_size, vec_4f( 1.0, 1.0, 1.0, 0.85 ) ); } display_reinforced_LiDAR_pts( m_depth_view_camera.m_depth_pts_vec, m_depth_view_camera.m_draw_depth_pts_size, vec_3f( 1.0, 0.0, 1.0 ) ); } } if ( g_follow_cam ) { if ( g_current_frame > 1 ) { g_gl_camera.tracking_camera( Eigen::Quaterniond::Identity(), t_last_avr ); } } if ( g_display_help_win ) { // display help window print_help_window( &g_display_help_win ); } if ( g_display_camera_pose_window ) { g_gl_camera.draw_camera_window( g_display_camera_pose_window ); } if ( g_if_draw_z_plane ) { g_axis_shader.draw( g_gl_camera.m_gl_cam.m_glm_projection_mat, Common_tools::eigen2glm( g_gl_camera.m_gl_cam.m_camera_pose_mat44_inverse ) ); g_ground_plane_shader.draw( g_gl_camera.m_gl_cam.m_glm_projection_mat, Common_tools::eigen2glm( g_gl_camera.m_gl_cam.m_camera_pose_mat44_inverse ) ); } if ( g_display_mesh ) { draw_triangle( g_gl_camera.m_gl_cam ); } if ( g_current_frame >= 0 ) { draw_camera_pose( g_current_frame, g_draw_path_size, g_display_camera_size ); draw_camera_trajectory( g_current_frame + 1, g_draw_path_size); } // For Key-board control if ( g_gl_camera.if_press_key( "H" ) ) { g_display_main_window = !g_display_main_window; } if ( g_gl_camera.if_press_key( "C" ) ) { g_display_camera_pose_window = !g_display_camera_pose_window; } if ( g_gl_camera.if_press_key( "F" ) ) { g_display_face = !g_display_face; } if ( g_gl_camera.if_press_key( "Space" ) ) { g_flag_pause = !g_flag_pause; } if ( g_gl_camera.if_press_key( "S" ) ) { g_gl_camera.save_camera( gl_camera_file_name ); } if ( g_gl_camera.if_press_key( "Z" ) ) { g_gl_camera.load_camera( gl_camera_file_name ); } if ( g_gl_camera.if_press_key( "D" ) ) { g_if_draw_depth = !g_if_draw_depth; } if ( g_gl_camera.if_press_key( "M" ) ) { g_display_mesh = !g_display_mesh; } if ( g_gl_camera.if_press_key( "T" ) ) { g_follow_cam = !g_follow_cam; if ( g_current_frame > 1 ) { g_gl_camera.set_last_tracking_camera_pos( q_last_avr, t_last_avr ); } } if ( g_gl_camera.if_press_key( "Escape" ) ) { glfwSetWindowShouldClose( window, 1 ); } if ( g_gl_camera.if_press_key( "F1" ) ) { g_display_help_win = !g_display_help_win; } g_gl_camera.set_gl_camera_pose_matrix(); g_gl_camera.draw_frame_finish(); } // Cleanup ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwDestroyWindow( window ); glfwTerminate(); return 0; }
C++
3D
hku-mars/ImMesh
src/voxel_mapping_common.cpp
.cpp
31,511
727
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "voxel_mapping.hpp" void Voxel_mapping::kitti_log( FILE *fp ) { // Eigen::Matrix4d T_lidar_to_cam; // T_lidar_to_cam << 0.00042768, -0.999967, -0.0080845, -0.01198, -0.00721062, // 0.0080811998, -0.99994131, -0.0540398, 0.999973864, 0.00048594, // -0.0072069, -0.292196, 0, 0, 0, 1.0; double time_stamp = 0; Eigen::Matrix4d T_lidar_to_cam; T_lidar_to_cam << 0.00554604, -0.999971, -0.00523653, 0.0316362, -0.000379382, 0.00523451, -0.999986, 0.0380934, 0.999985, 0.00554795, -0.000350341, 0.409066, 0, 0, 0, 1; // V3D rot_ang(Log(state.rot_end)); MD( 4, 4 ) T; T.block< 3, 3 >( 0, 0 ) = state.rot_end; T.block< 3, 1 >( 0, 3 ) = state.pos_end; T( 3, 0 ) = 0; T( 3, 1 ) = 0; T( 3, 2 ) = 0; T( 3, 3 ) = 1; T = T_lidar_to_cam * T * T_lidar_to_cam.inverse(); Eigen::Matrix3d camera_rotation = T.block< 3, 3 >( 0, 0 ); Eigen::Vector3d camera_translation = T.block< 3, 1 >( 0, 3 ); Eigen::Quaterniond q( camera_rotation ); fprintf( fp, "%lf %lf %lf %lf %lf %lf %lf %lf\n", m_last_timestamp_lidar, camera_translation[ 0 ], camera_translation[ 1 ], camera_translation[ 2 ], q.x(), q.y(), q.z(), q.w() ); fflush( fp ); } void Voxel_mapping::SigHandle( int sig ) { m_flg_exit = true; ROS_WARN( "catch sig %d", sig ); m_sig_buffer.notify_all(); } void Voxel_mapping::dump_lio_state_to_log( FILE *fp ) { #ifdef USE_IKFOM // state_ikfom write_state = kf.get_x(); V3D rot_ang( Log( state_point.rot.toRotationMatrix() ) ); fprintf( fp, "%lf ", LidarMeasures.lidar_beg_time - first_lidar_time ); fprintf( fp, "%lf %lf %lf ", rot_ang( 0 ), rot_ang( 1 ), rot_ang( 2 ) ); // Angle fprintf( fp, "%lf %lf %lf ", state_point.pos( 0 ), state_point.pos( 1 ), state_point.pos( 2 ) ); // Pos fprintf( fp, "%lf %lf %lf ", 0.0, 0.0, 0.0 ); // omega fprintf( fp, "%lf %lf %lf ", state_point.vel( 0 ), state_point.vel( 1 ), state_point.vel( 2 ) ); // Vel fprintf( fp, "%lf %lf %lf ", 0.0, 0.0, 0.0 ); // Acc fprintf( fp, "%lf %lf %lf ", state_point.bg( 0 ), state_point.bg( 1 ), state_point.bg( 2 ) ); // Bias_g fprintf( fp, "%lf %lf %lf ", state_point.ba( 0 ), state_point.ba( 1 ), state_point.ba( 2 ) ); // Bias_a fprintf( fp, "%lf %lf %lf ", state_point.grav[ 0 ], state_point.grav[ 1 ], state_point.grav[ 2 ] ); // Bias_a fprintf( fp, "\r\n" ); fflush( fp ); #else V3D rot_ang( Log( state.rot_end ) ); fprintf( fp, "%lf ", m_Lidar_Measures.lidar_beg_time - m_first_lidar_time ); fprintf( fp, "%lf %lf %lf ", rot_ang( 0 ), rot_ang( 1 ), rot_ang( 2 ) ); // Angle fprintf( fp, "%lf %lf %lf ", state.pos_end( 0 ), state.pos_end( 1 ), state.pos_end( 2 ) ); // Pos fprintf( fp, "%lf %lf %lf ", 0.0, 0.0, 0.0 ); // omega fprintf( fp, "%lf %lf %lf ", state.vel_end( 0 ), state.vel_end( 1 ), state.vel_end( 2 ) ); // Vel fprintf( fp, "%lf %lf %lf ", 0.0, 0.0, 0.0 ); // Acc fprintf( fp, "%lf %lf %lf ", state.bias_g( 0 ), state.bias_g( 1 ), state.bias_g( 2 ) ); // Bias_g fprintf( fp, "%lf %lf %lf ", state.bias_a( 0 ), state.bias_a( 1 ), state.bias_a( 2 ) ); // Bias_a fprintf( fp, "%lf %lf %lf ", state.gravity( 0 ), state.gravity( 1 ), state.gravity( 2 ) ); // Bias_a fprintf( fp, "\r\n" ); fflush( fp ); #endif } void Voxel_mapping::pointBodyToWorld( const PointType &pi, PointType &po ) { V3D p_body( pi.x, pi.y, pi.z ); V3D p_global( state.rot_end * ( m_extR * p_body + m_extT ) + state.pos_end ); po.x = p_global( 0 ); po.y = p_global( 1 ); po.z = p_global( 2 ); po.intensity = pi.intensity; } void Voxel_mapping::frameBodyToWorld( const PointCloudXYZI::Ptr &pi, PointCloudXYZI::Ptr &po ) { int pi_size = pi->points.size(); po->resize( pi_size ); for ( int i = 0; i < pi_size; i++ ) { /* transform to world frame */ pointBodyToWorld( pi->points[ i ], po->points[ i ] ); } } void Voxel_mapping::get_NED_transform() { if ( false ) { V3D grav_vec( -0.0463686846197, -0.194593831897, 0.996038079262 ); double gravity_correct_ang = std::acos( grav_vec.dot( V3D( 0, 0, 9.8 ) ) / ( grav_vec.norm() * 9.8 ) ); AngleAxisd gravity_correct_vec( gravity_correct_ang, ( grav_vec.cross( V3D( 0, 0, 9.8 ) ) ).normalized() ); // gravity_correct_vec = gravity_correct_vec / gravity_correct_vec.norm() * // gravity_correct_ang; _gravity_correct_rotM = gravity_correct_vec.toRotationMatrix(); Eigen::Quaterniond _gravity_correct_q; _gravity_correct_q.x() = 0.0983599; _gravity_correct_q.y() = 0.00420122; _gravity_correct_q.z() = -0.377381; _gravity_correct_q.w() = 0.92081; _gravity_correct_rotM = _gravity_correct_q.toRotationMatrix().transpose(); cout << "gravity_correct_rotM: " << _gravity_correct_rotM << endl; cout << "corrected gravity: " << grav_vec.transpose() * _gravity_correct_rotM.transpose() << endl; } } void Voxel_mapping::RGBpointBodyToWorld( PointType const *const pi, PointType *const po ) { V3D p_body( pi->x, pi->y, pi->z ); #ifdef USE_IKFOM // state_ikfom transfer_state = kf.get_x(); V3D p_global( state_point.rot * ( state_point.offset_R_L_I * p_body + state_point.offset_T_L_I ) + state_point.pos ); #else V3D p_global( state.rot_end * ( m_extR * p_body + m_extT ) + state.pos_end ); #endif p_global = _gravity_correct_rotM * p_global; po->x = p_global( 0 ); po->y = p_global( 1 ); po->z = p_global( 2 ); po->intensity = pi->intensity; float intensity = pi->intensity; intensity = intensity - floor( intensity ); int reflection_map = intensity * 10000; } void Voxel_mapping::RGBpointBodyLidarToIMU( PointType const *const pi, PointType *const po ) { V3D p_body_lidar( pi->x, pi->y, pi->z ); #ifdef USE_IKFOM // state_ikfom transfer_state = kf.get_x(); V3D p_body_imu( state_point.offset_R_L_I * p_body_lidar + state_point.offset_T_L_I ); #else V3D p_body_imu( m_extR * p_body_lidar + m_extT ); #endif po->x = p_body_imu( 0 ); po->y = p_body_imu( 1 ); po->z = p_body_imu( 2 ); po->intensity = pi->intensity; } void Voxel_mapping::points_cache_collect() { PointVector points_history; m_ikdtree.acquire_removed_points( points_history ); m_points_cache_size = points_history.size(); } void Voxel_mapping::laser_map_fov_segment() { m_cub_need_rm.clear(); m_kdtree_delete_counter = 0; m_kdtree_delete_time = 0.0; pointBodyToWorld( m_XAxis_Point_body, m_XAxis_Point_world ); #ifdef USE_IKFOM // state_ikfom fov_state = kf.get_x(); // V3D pos_LiD = fov_state.pos + fov_state.rot * fov_state.offset_T_L_I; V3D pos_LiD = pos_lid; #else V3D pos_LiD = state.pos_end; #endif if ( !m_localmap_Initialized ) { // if (cube_len <= 2.0 * MOV_THRESHOLD * DETECTION_RANGE) throw // std::invalid_argument("[Error]: Local Map Size is too small! Please // change parameter \"cube_side_length\" to larger than %d in the launch // file.\n"); for ( int i = 0; i < 3; i++ ) { m_LocalMap_Points.vertex_min[ i ] = pos_LiD( i ) - m_cube_len / 2.0; m_LocalMap_Points.vertex_max[ i ] = pos_LiD( i ) + m_cube_len / 2.0; } m_localmap_Initialized = true; return; } // printf("Local Map is (%0.2f,%0.2f) (%0.2f,%0.2f) (%0.2f,%0.2f)\n", // LocalMap_Points.vertex_min[0],LocalMap_Points.vertex_max[0],LocalMap_Points.vertex_min[1],LocalMap_Points.vertex_max[1],LocalMap_Points.vertex_min[2],LocalMap_Points.vertex_max[2]); float dist_to_map_edge[ 3 ][ 2 ]; bool need_move = false; for ( int i = 0; i < 3; i++ ) { dist_to_map_edge[ i ][ 0 ] = fabs( pos_LiD( i ) - m_LocalMap_Points.vertex_min[ i ] ); dist_to_map_edge[ i ][ 1 ] = fabs( pos_LiD( i ) - m_LocalMap_Points.vertex_max[ i ] ); if ( dist_to_map_edge[ i ][ 0 ] <= MOV_THRESHOLD * DETECTION_RANGE || dist_to_map_edge[ i ][ 1 ] <= MOV_THRESHOLD * DETECTION_RANGE ) need_move = true; } if ( !need_move ) return; BoxPointType New_LocalMap_Points, tmp_boxpoints; New_LocalMap_Points = m_LocalMap_Points; float mov_dist = max( ( m_cube_len - 2.0 * MOV_THRESHOLD * DETECTION_RANGE ) * 0.5 * 0.9, double( DETECTION_RANGE * ( MOV_THRESHOLD - 1 ) ) ); for ( int i = 0; i < 3; i++ ) { tmp_boxpoints = m_LocalMap_Points; if ( dist_to_map_edge[ i ][ 0 ] <= MOV_THRESHOLD * DETECTION_RANGE ) { New_LocalMap_Points.vertex_max[ i ] -= mov_dist; New_LocalMap_Points.vertex_min[ i ] -= mov_dist; tmp_boxpoints.vertex_min[ i ] = m_LocalMap_Points.vertex_max[ i ] - mov_dist; m_cub_need_rm.push_back( tmp_boxpoints ); // printf("Delete Box is (%0.2f,%0.2f) (%0.2f,%0.2f) (%0.2f,%0.2f)\n", // tmp_boxpoints.vertex_min[0],tmp_boxpoints.vertex_max[0],tmp_boxpoints.vertex_min[1],tmp_boxpoints.vertex_max[1],tmp_boxpoints.vertex_min[2],tmp_boxpoints.vertex_max[2]); } else if ( dist_to_map_edge[ i ][ 1 ] <= MOV_THRESHOLD * DETECTION_RANGE ) { New_LocalMap_Points.vertex_max[ i ] += mov_dist; New_LocalMap_Points.vertex_min[ i ] += mov_dist; tmp_boxpoints.vertex_max[ i ] = m_LocalMap_Points.vertex_min[ i ] + mov_dist; m_cub_need_rm.push_back( tmp_boxpoints ); // printf("Delete Box is (%0.2f,%0.2f) (%0.2f,%0.2f) (%0.2f,%0.2f)\n", // tmp_boxpoints.vertex_min[0],tmp_boxpoints.vertex_max[0],tmp_boxpoints.vertex_min[1],tmp_boxpoints.vertex_max[1],tmp_boxpoints.vertex_min[2],tmp_boxpoints.vertex_max[2]); } } m_LocalMap_Points = New_LocalMap_Points; points_cache_collect(); double delete_begin = omp_get_wtime(); if ( m_cub_need_rm.size() > 0 ) m_kdtree_delete_counter = m_ikdtree.Delete_Point_Boxes( m_cub_need_rm ); m_kdtree_delete_time = omp_get_wtime() - delete_begin; // printf( "Delete time: %0.6f, delete size: %d\n", m_kdtree_delete_time, m_kdtree_delete_counter ); // printf("Delete Box: %d\n",int(cub_needrm.size())); } void Voxel_mapping::standard_pcl_cbk( const sensor_msgs::PointCloud2::ConstPtr &msg ) { if ( !m_lidar_en ) return; m_mutex_buffer.lock(); // cout<<"got feature"<<endl; if ( msg->header.stamp.toSec() < m_last_timestamp_lidar ) { ROS_ERROR( "lidar loop back, clear buffer" ); m_lidar_buffer.clear(); } // ROS_INFO("get point cloud at time: %.6f", msg->header.stamp.toSec()); PointCloudXYZI::Ptr ptr( new PointCloudXYZI() ); m_p_pre->process( msg, ptr ); m_lidar_buffer.push_back( ptr ); m_time_buffer.push_back( msg->header.stamp.toSec() ); m_last_timestamp_lidar = msg->header.stamp.toSec(); m_mutex_buffer.unlock(); m_sig_buffer.notify_all(); } void Voxel_mapping::livox_pcl_cbk( const livox_ros_driver::CustomMsg::ConstPtr &msg ) { if ( !m_lidar_en ) return; m_mutex_buffer.lock(); // ROS_INFO( "get LiDAR, its header time: %.6f", msg->header.stamp.toSec() ); if ( msg->header.stamp.toSec() < m_last_timestamp_lidar ) { ROS_ERROR( "lidar loop back, clear buffer" ); m_lidar_buffer.clear(); } // ROS_INFO("get point cloud at time: %.6f", msg->header.stamp.toSec()); PointCloudXYZI::Ptr ptr( new PointCloudXYZI() ); m_p_pre->process( msg, ptr ); m_lidar_buffer.push_back( ptr ); m_time_buffer.push_back( msg->header.stamp.toSec() ); m_last_timestamp_lidar = msg->header.stamp.toSec(); m_mutex_buffer.unlock(); m_sig_buffer.notify_all(); } void Voxel_mapping::imu_cbk( const sensor_msgs::Imu::ConstPtr &msg_in ) { if ( !m_imu_en ) return; if ( m_last_timestamp_lidar < 0.0 ) return; m_publish_count++; // ROS_INFO("get imu at time: %.6f", msg_in->header.stamp.toSec()); sensor_msgs::Imu::Ptr msg( new sensor_msgs::Imu( *msg_in ) ); double timestamp = msg->header.stamp.toSec(); m_mutex_buffer.lock(); if ( m_last_timestamp_imu > 0.0 && timestamp < m_last_timestamp_imu ) { m_mutex_buffer.unlock(); m_sig_buffer.notify_all(); ROS_ERROR( "imu loop back \n" ); return; } // old 0.2 if ( m_last_timestamp_imu > 0.0 && timestamp > m_last_timestamp_imu + 0.4 ) { m_mutex_buffer.unlock(); m_sig_buffer.notify_all(); ROS_WARN( "imu time stamp Jumps %0.4lf seconds \n", timestamp - m_last_timestamp_imu ); return; } m_last_timestamp_imu = timestamp; m_imu_buffer.push_back( msg ); // cout<<"got imu: "<<timestamp<<" imu size "<<imu_buffer.size()<<endl; m_mutex_buffer.unlock(); m_sig_buffer.notify_all(); } bool Voxel_mapping::sync_packages( LidarMeasureGroup &meas ) { if ( !m_imu_en ) { if ( !m_lidar_buffer.empty() ) { meas.lidar = m_lidar_buffer.front(); meas.lidar_beg_time = m_time_buffer.front(); m_lidar_buffer.pop_front(); m_time_buffer.pop_front(); return true; } return false; } if ( m_lidar_buffer.empty() || m_imu_buffer.empty() ) { return false; } /*** push a lidar scan ***/ if ( !m_lidar_pushed ) { meas.lidar = m_lidar_buffer.front(); if ( meas.lidar->points.size() <= 1 ) { m_lidar_buffer.pop_front(); return false; } meas.lidar_beg_time = m_time_buffer.front(); m_lidar_end_time = meas.lidar_beg_time + meas.lidar->points.back().curvature / double( 1000 ); m_lidar_pushed = true; } if ( m_last_timestamp_imu < m_lidar_end_time ) { return false; } /*** push imu data, and pop from imu buffer ***/ // no img topic, means only has lidar topic if ( m_imu_en && m_last_timestamp_imu < m_lidar_end_time ) { // imu message needs to be larger than lidar_end_time, keep complete propagate. // ROS_ERROR("out sync"); return false; } struct MeasureGroup m; // standard method to keep imu message. if ( !m_imu_buffer.empty() ) { double imu_time = m_imu_buffer.front()->header.stamp.toSec(); m.imu.clear(); m_mutex_buffer.lock(); while ( ( !m_imu_buffer.empty() && ( imu_time < m_lidar_end_time ) ) ) { imu_time = m_imu_buffer.front()->header.stamp.toSec(); if ( imu_time > m_lidar_end_time ) break; m.imu.push_back( m_imu_buffer.front() ); m_imu_buffer.pop_front(); } } m_lidar_buffer.pop_front(); m_time_buffer.pop_front(); m_mutex_buffer.unlock(); m_sig_buffer.notify_all(); m_lidar_pushed = false; // sync one whole lidar scan. meas.is_lidar_end = true; // process lidar topic, so timestamp should be lidar scan end. meas.measures.push_back( m ); return true; } void Voxel_mapping::publish_voxel_point( const ros::Publisher &pubLaserCloudVoxel, const PointCloudXYZI::Ptr &pcl_wait_pub ) { uint size = pcl_wait_pub->points.size(); PointCloudXYZRGB::Ptr laserCloudWorldRGB( new PointCloudXYZRGB( size, 1 ) ); for ( int i = 0; i < size; i++ ) { PointTypeRGB pointRGB; pointRGB.x = pcl_wait_pub->points[ i ].x; pointRGB.y = pcl_wait_pub->points[ i ].y; pointRGB.z = pcl_wait_pub->points[ i ].z; V3D point( pointRGB.x, pointRGB.y, pointRGB.z ); V3F pixel = RGBFromVoxel( point, m_max_voxel_size, m_layer_size, m_min_eigen_value, m_feat_map ); pointRGB.r = pixel[ 0 ]; pointRGB.g = pixel[ 1 ]; pointRGB.b = pixel[ 2 ]; laserCloudWorldRGB->push_back( pointRGB ); } sensor_msgs::PointCloud2 laserCloudmsg; if ( m_img_en ) { cout << "RGB pointcloud size: " << laserCloudWorldRGB->size() << endl; pcl::toROSMsg( *laserCloudWorldRGB, laserCloudmsg ); } else { pcl::toROSMsg( *pcl_wait_pub, laserCloudmsg ); } laserCloudmsg.header.stamp = ros::Time::now(); //.fromSec(last_timestamp_lidar); laserCloudmsg.header.frame_id = "camera_init"; pubLaserCloudVoxel.publish( laserCloudmsg ); m_publish_count -= PUBFRAME_PERIOD; } void Voxel_mapping::publish_visual_world_map( const ros::Publisher &pubVisualCloud ) { PointCloudXYZI::Ptr laserCloudFullRes( m_map_cur_frame_point ); int size = laserCloudFullRes->points.size(); if ( size == 0 ) return; // PointCloudXYZI::Ptr laserCloudWorld( new PointCloudXYZI(size, 1)); // for (int i = 0; i < size; i++) // { // RGBpointBodyToWorld(&laserCloudFullRes->points[i], \ // &laserCloudWorld->coints[i]); // } // mutex_buffer_pointcloud.lock(); *m_pcl_visual_wait_pub = *laserCloudFullRes; if ( 1 ) // if(publish_count >= PUBFRAME_PERIOD) { sensor_msgs::PointCloud2 laserCloudmsg; pcl::toROSMsg( *m_pcl_visual_wait_pub, laserCloudmsg ); laserCloudmsg.header.stamp = ros::Time::now(); //.fromSec(last_timestamp_lidar); laserCloudmsg.header.frame_id = "camera_init"; pubVisualCloud.publish( laserCloudmsg ); m_publish_count -= PUBFRAME_PERIOD; // pcl_wait_pub->clear(); } // mutex_buffer_pointcloud.unlock(); } void Voxel_mapping::publish_visual_world_sub_map( const ros::Publisher &pubSubVisualCloud ) { PointCloudXYZI::Ptr laserCloudFullRes( m_sub_map_cur_frame_point ); int size = laserCloudFullRes->points.size(); if ( size == 0 ) return; // PointCloudXYZI::Ptr laserCloudWorld( new PointCloudXYZI(size, 1)); // for (int i = 0; i < size; i++) // { // RGBpointBodyToWorld(&laserCloudFullRes->points[i], \ // &laserCloudWorld->points[i]); // } // mutex_buffer_pointcloud.lock(); *m_sub_pcl_visual_wait_pub = *laserCloudFullRes; if ( 1 ) // if(publish_count >= PUBFRAME_PERIOD) { sensor_msgs::PointCloud2 laserCloudmsg; pcl::toROSMsg( *m_sub_pcl_visual_wait_pub, laserCloudmsg ); laserCloudmsg.header.stamp = ros::Time::now(); //.fromSec(last_timestamp_lidar); laserCloudmsg.header.frame_id = "camera_init"; pubSubVisualCloud.publish( laserCloudmsg ); m_publish_count -= PUBFRAME_PERIOD; // pcl_wait_pub->clear(); } // mutex_buffer_pointcloud.unlock(); } void Voxel_mapping::publish_effect_world( const ros::Publisher &pubLaserCloudEffect ) { PointCloudXYZI::Ptr laserCloudWorld( new PointCloudXYZI( m_effct_feat_num, 1 ) ); for ( int i = 0; i < m_effct_feat_num; i++ ) { RGBpointBodyToWorld( &m_laserCloudOri->points[ i ], &laserCloudWorld->points[ i ] ); } sensor_msgs::PointCloud2 laserCloudFullRes3; pcl::toROSMsg( *laserCloudWorld, laserCloudFullRes3 ); laserCloudFullRes3.header.stamp = ros::Time::now(); //.fromSec(last_timestamp_lidar); laserCloudFullRes3.header.frame_id = "camera_init"; pubLaserCloudEffect.publish( laserCloudFullRes3 ); } void Voxel_mapping::publish_map( const ros::Publisher &pubLaserCloudMap ) { sensor_msgs::PointCloud2 laserCloudMap; pcl::toROSMsg( *m_featsFromMap, laserCloudMap ); laserCloudMap.header.stamp = ros::Time::now(); laserCloudMap.header.frame_id = "camera_init"; pubLaserCloudMap.publish( laserCloudMap ); } void Voxel_mapping::publish_odometry( const ros::Publisher &pubOdomAftMapped ) { m_odom_aft_mapped.header.frame_id = "camera_init"; m_odom_aft_mapped.child_frame_id = "aft_mapped"; m_odom_aft_mapped.header.stamp = ros::Time::now(); //.ros::Time()fromSec(last_timestamp_lidar); set_pose_timestamp( m_odom_aft_mapped.pose.pose ); // odomAftMapped.twist.twist.linear.x = state_point.vel(0); // odomAftMapped.twist.twist.linear.y = state_point.vel(1); // odomAftMapped.twist.twist.linear.z = state_point.vel(2); // if (Measures.imu.size()>0) { // Vector3d tmp(Measures.imu.back()->angular_velocity.x, // Measures.imu.back()->angular_velocity.y,Measures.imu.back()->angular_velocity.z); // odomAftMapped.twist.twist.angular.x = tmp[0] - state_point.bg(0); // odomAftMapped.twist.twist.angular.y = tmp[1] - state_point.bg(1); // odomAftMapped.twist.twist.angular.z = tmp[2] - state_point.bg(2); // } // static tf::TransformBroadcaster br; // tf::Transform transform; // tf::Quaternion q; // transform.setOrigin(tf::Vector3(state.pos_end(0), state.pos_end(1), // state.pos_end(2))); q.setW(geoQuat.w); q.setX(geoQuat.x); // q.setY(geoQuat.y); // q.setZ(geoQuat.z); // transform.setRotation( q ); // br.sendTransform( tf::StampedTransform( transform, // odomAftMapped.header.stamp, "camera_init", "aft_mapped" ) ); pubOdomAftMapped.publish( m_odom_aft_mapped ); } void Voxel_mapping::publish_mavros( const ros::Publisher &mavros_pose_publisher ) { m_msg_body_pose.header.stamp = ros::Time::now(); m_msg_body_pose.header.frame_id = "camera_odom_frame"; set_pose_timestamp( m_msg_body_pose.pose ); mavros_pose_publisher.publish( m_msg_body_pose ); } void Voxel_mapping::publish_frame_world( const ros::Publisher &pubLaserCloudFullRes, const int point_skip ) { PointCloudXYZI::Ptr laserCloudFullRes( m_dense_map_en ? m_feats_undistort : m_feats_down_body ); int size = laserCloudFullRes->points.size(); PointCloudXYZI::Ptr laserCloudWorld( new PointCloudXYZI( size, 1 ) ); for ( int i = 0; i < size; i++ ) { RGBpointBodyToWorld( &laserCloudFullRes->points[ i ], &laserCloudWorld->points[ i ] ); } PointCloudXYZI::Ptr laserCloudWorldPub( new PointCloudXYZI ); for ( int i = 0; i < size; i += point_skip ) { laserCloudWorldPub->points.push_back( laserCloudWorld->points[ i ] ); } sensor_msgs::PointCloud2 laserCloudmsg; pcl::toROSMsg( *laserCloudWorldPub, laserCloudmsg ); laserCloudmsg.header.stamp = ros::Time::now(); //.fromSec(last_timestamp_lidar); laserCloudmsg.header.frame_id = "camera_init"; pubLaserCloudFullRes.publish( laserCloudmsg ); } void Voxel_mapping::publish_path( const ros::Publisher pubPath ) { set_pose_timestamp( m_msg_body_pose.pose ); m_msg_body_pose.header.stamp = ros::Time::now(); m_msg_body_pose.header.frame_id = "camera_init"; m_pub_path.poses.push_back( m_msg_body_pose ); pubPath.publish( m_pub_path ); } void Voxel_mapping::read_ros_parameters( ros::NodeHandle &nh ) { nh.param< int >( "dense_map_enable", m_dense_map_en, 1 ); nh.param< int >( "img_enable", m_img_en, 1 ); nh.param< int >( "lidar_enable", m_lidar_en, 1 ); nh.param< int >( "debug", m_debug, 0 ); nh.param< int >( "max_iteration", NUM_MAX_ITERATIONS, 4 ); nh.param< int >( "min_img_count", MIN_IMG_COUNT, 1000 ); nh.param< string >( "pc_name", m_pointcloud_file_name, " " ); nh.param< int >( "gui_font_size", m_GUI_font_size, 14 ); nh.param< double >( "cam_fx", cam_fx, 453.483063 ); nh.param< double >( "cam_fy", cam_fy, 453.254913 ); nh.param< double >( "cam_cx", cam_cx, 318.908851 ); nh.param< double >( "cam_cy", cam_cy, 234.238189 ); nh.param< double >( "laser_point_cov", LASER_POINT_COV, 0.001 ); nh.param< double >( "img_point_cov", IMG_POINT_COV, 10 ); nh.param< string >( "map_file_path", m_map_file_path, "" ); nh.param< string >( "common/lid_topic", m_lid_topic, "/livox/lidar" ); nh.param< string >( "common/imu_topic", m_imu_topic, "/livox/imu" ); nh.param< string >( "hilti/seq", m_hilti_seq_name, "01" ); nh.param< bool >( "hilti/en", m_hilti_en, false ); nh.param< string >( "camera/img_topic", m_img_topic, "/usb_cam/image_raw" ); nh.param< double >( "filter_size_corner", m_filter_size_corner_min, 0.5 ); nh.param< double >( "filter_size_surf", m_filter_size_surf_min, 0.5 ); nh.param< double >( "filter_size_map", m_filter_size_map_min, 0.5 ); nh.param< double >( "cube_side_length", m_cube_len, 200 ); nh.param< double >( "mapping/fov_degree", m_fov_deg, 180 ); nh.param< double >( "mapping/gyr_cov", m_gyr_cov, 1.0 ); nh.param< double >( "mapping/acc_cov", m_acc_cov, 1.0 ); nh.param< int >( "voxel/max_points_size", m_max_points_size, 100 ); nh.param< int >( "voxel/max_layer", m_max_layer, 2 ); nh.param< vector< int > >( "voxel/layer_init_size", m_layer_init_size, vector< int >() ); nh.param< int >( "mapping/imu_int_frame", m_imu_int_frame, 3 ); nh.param< bool >( "mapping/imu_en", m_imu_en, false ); nh.param< bool >( "voxel/voxel_map_en", m_use_new_map, false ); nh.param< bool >( "voxel/pub_plane_en", m_is_pub_plane_map, false ); nh.param< double >( "voxel/match_eigen_value", m_match_eigen_value, 0.0025 ); nh.param< int >( "voxel/layer", m_voxel_layer, 1 ); nh.param< double >( "voxel/match_s", m_match_s, 0.90 ); nh.param< double >( "voxel/voxel_size", m_max_voxel_size, 1.0 ); nh.param< double >( "voxel/min_eigen_value", m_min_eigen_value, 0.01 ); nh.param< double >( "voxel/sigma_num", m_sigma_num, 3 ); nh.param< double >( "voxel/beam_err", m_beam_err, 0.02 ); nh.param< double >( "voxel/dept_err", m_dept_err, 0.05 ); nh.param< double >( "preprocess/blind", m_p_pre->blind, 0.01 ); nh.param< double >( "image_save/rot_dist", m_keyf_rotd, 0.01 ); nh.param< double >( "image_save/pos_dist", m_keyf_posd, 0.01 ); nh.param< int >( "preprocess/lidar_type", m_p_pre->lidar_type, AVIA ); nh.param< int >( "preprocess/scan_line", m_p_pre->N_SCANS, 16 ); nh.param< int >( "preprocess/timestamp_unit", m_p_pre->time_unit, US ); nh.param< bool >( "preprocess/calib_laser", m_p_pre->calib_laser, false ); nh.param< int >( "point_filter_num", m_p_pre->point_filter_num, 2 ); nh.param< int >( "pcd_save/interval", m_pcd_save_interval, -1 ); nh.param< int >( "image_save/interval", m_img_save_interval, 1 ); nh.param< int >( "pcd_save/type", m_pcd_save_type, 0 ); nh.param< bool >( "pcd_save/pcd_save_en", m_pcd_save_en, false ); nh.param< bool >( "image_save/img_save_en", m_img_save_en, false ); nh.param< bool >( "feature_extract_enable", m_p_pre->feature_enabled, false ); nh.param< vector< double > >( "mapping/extrinsic_T", m_extrin_T, vector< double >() ); nh.param< vector< double > >( "mapping/extrinsic_R", m_extrin_R, vector< double >() ); nh.param< vector< double > >( "camera/Pcl", m_camera_extrin_T, vector< double >() ); nh.param< vector< double > >( "camera/Rcl", m_camera_extrin_R, vector< double >() ); nh.param< int >( "grid_size", m_grid_size, 40 ); nh.param< int >( "patch_size", m_patch_size, 4 ); nh.param< double >( "outlier_threshold", m_outlier_threshold, 100 ); nh.param< bool >( "publish/effect_point_pub", m_effect_point_pub, false ); nh.param< int >( "publish/pub_point_skip", m_pub_point_skip, 1 ); nh.param< double >( "meshing/distance_scale", m_meshing_distance_scale, 1.0 ); nh.param< double >( "meshing/points_minimum_scale", m_meshing_points_minimum_scale, 0.1 ); nh.param< double >( "meshing/voxel_resolution", m_meshing_voxel_resolution, 0.4 ); nh.param< double >( "meshing/region_size", m_meshing_region_size, 10.0 ); nh.param< int >( "meshing/if_draw_mesh", m_if_draw_mesh, 1.0 ); nh.param< int >( "meshing/enable_mesh_rec", m_if_enable_mesh_rec, 1 ); nh.param< int >( "meshing/maximum_thread_for_rec_mesh", m_meshing_maximum_thread_for_rec_mesh, 12 ); nh.param< int >( "meshing/number_of_pts_append_to_map", m_meshing_number_of_pts_append_to_map, 10000 ); m_p_pre->blind_sqr = m_p_pre->blind * m_p_pre->blind; cout << "Ranging cov:" << m_dept_err << " , angle cov:" << m_beam_err << std::endl; cout << "Meshing distance scale:" << m_meshing_distance_scale << " , points minimum scale:" << m_meshing_points_minimum_scale << std::endl; } void Voxel_mapping::transformLidar( const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr &input_cloud, pcl::PointCloud< pcl::PointXYZI >::Ptr &trans_cloud ) { trans_cloud->clear(); for ( size_t i = 0; i < input_cloud->size(); i++ ) { pcl::PointXYZINormal p_c = input_cloud->points[ i ]; Eigen::Vector3d p( p_c.x, p_c.y, p_c.z ); // p = rot * p + t; p = ( rot * ( m_extR * p + m_extT ) + t ); pcl::PointXYZI pi; pi.x = p( 0 ); pi.y = p( 1 ); pi.z = p( 2 ); pi.intensity = p_c.intensity; trans_cloud->points.push_back( pi ); } }
C++
3D
hku-mars/ImMesh
src/voxel_mapping.cpp
.cpp
96,235
2,051
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "voxel_mapping.hpp" double g_LiDAR_frame_start_time = 0; V3D Lidar_T_wrt_IMU = V3D::Zero(); M3D Lidar_R_wrt_IMU = M3D::Identity(); const bool intensity_contrast( PointType &x, PointType &y ) { return ( x.intensity > y.intensity ); }; const bool var_contrast( Point_with_var &x, Point_with_var &y ) { return ( x.m_var.diagonal().norm() < y.m_var.diagonal().norm() ); }; float calc_dist( PointType p1, PointType p2 ) { float d = ( p1.x - p2.x ) * ( p1.x - p2.x ) + ( p1.y - p2.y ) * ( p1.y - p2.y ) + ( p1.z - p2.z ) * ( p1.z - p2.z ); return d; } void mapJet( double v, double vmin, double vmax, uint8_t &r, uint8_t &g, uint8_t &b ) { r = 255; g = 255; b = 255; if ( v < vmin ) { v = vmin; } if ( v > vmax ) { v = vmax; } double dr, dg, db; if ( v < 0.1242 ) { db = 0.504 + ( ( 1. - 0.504 ) / 0.1242 ) * v; dg = dr = 0.; } else if ( v < 0.3747 ) { db = 1.; dr = 0.; dg = ( v - 0.1242 ) * ( 1. / ( 0.3747 - 0.1242 ) ); } else if ( v < 0.6253 ) { db = ( 0.6253 - v ) * ( 1. / ( 0.6253 - 0.3747 ) ); dg = 1.; dr = ( v - 0.3747 ) * ( 1. / ( 0.6253 - 0.3747 ) ); } else if ( v < 0.8758 ) { db = 0.; dr = 1.; dg = ( 0.8758 - v ) * ( 1. / ( 0.8758 - 0.6253 ) ); } else { db = 0.; dg = 0.; dr = 1. - ( v - 0.8758 ) * ( ( 1. - 0.504 ) / ( 1. - 0.8758 ) ); } r = ( uint8_t )( 255 * dr ); g = ( uint8_t )( 255 * dg ); b = ( uint8_t )( 255 * db ); } void buildVoxelMap( const std::vector< Point_with_var > &input_points, const float voxel_size, const int max_layer, const std::vector< int > &layer_init_num, const int max_points_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ) { uint plsize = input_points.size(); for ( uint i = 0; i < plsize; i++ ) { const Point_with_var p_v = input_points[ i ]; float loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = p_v.m_point[ j ] / voxel_size; if ( loc_xyz[ j ] < 0 ) { loc_xyz[ j ] -= 1.0; } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); auto iter = feat_map.find( position ); if ( iter != feat_map.end() ) { feat_map[ position ]->m_temp_points_.push_back( p_v ); feat_map[ position ]->m_new_points_++; } else { OctoTree *octo_tree = new OctoTree( max_layer, 0, layer_init_num, max_points_size, planer_threshold ); feat_map[ position ] = octo_tree; feat_map[ position ]->m_quater_length_ = voxel_size / 4; feat_map[ position ]->m_voxel_center_[ 0 ] = ( 0.5 + position.x ) * voxel_size; feat_map[ position ]->m_voxel_center_[ 1 ] = ( 0.5 + position.y ) * voxel_size; feat_map[ position ]->m_voxel_center_[ 2 ] = ( 0.5 + position.z ) * voxel_size; feat_map[ position ]->m_temp_points_.push_back( p_v ); feat_map[ position ]->m_new_points_++; feat_map[ position ]->m_layer_init_num_ = layer_init_num; } } for ( auto iter = feat_map.begin(); iter != feat_map.end(); ++iter ) { iter->second->init_octo_tree(); } } void BuildResidualListOMP( const unordered_map< VOXEL_LOC, OctoTree * > &voxel_map, const double voxel_size, const double sigma_num, const int max_layer, const std::vector< Point_with_var > &pv_list, std::vector< ptpl > &ptpl_list, std::vector< Eigen::Vector3d > &non_match ) { std::mutex mylock; ptpl_list.clear(); std::vector< ptpl > all_ptpl_list( pv_list.size() ); std::vector< bool > useful_ptpl( pv_list.size() ); std::vector< size_t > index( pv_list.size() ); for ( size_t i = 0; i < index.size(); ++i ) { index[ i ] = i; useful_ptpl[ i ] = false; } omp_set_num_threads( MP_PROC_NUM ); #pragma omp parallel for for ( int i = 0; i < index.size(); i++ ) { Point_with_var pv = pv_list[ i ]; float loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = pv.m_point_world[ j ] / voxel_size; if ( loc_xyz[ j ] < 0 ) { loc_xyz[ j ] -= 1.0; } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); auto iter = voxel_map.find( position ); if ( iter != voxel_map.end() ) { OctoTree *current_octo = iter->second; ptpl single_ptpl; bool is_sucess = false; double prob = 0; build_single_residual( pv, current_octo, 0, max_layer, sigma_num, is_sucess, prob, single_ptpl ); if ( !is_sucess ) { VOXEL_LOC near_position = position; if ( loc_xyz[ 0 ] > ( current_octo->m_voxel_center_[ 0 ] + current_octo->m_quater_length_ ) ) { near_position.x = near_position.x + 1; } else if ( loc_xyz[ 0 ] < ( current_octo->m_voxel_center_[ 0 ] - current_octo->m_quater_length_ ) ) { near_position.x = near_position.x - 1; } if ( loc_xyz[ 1 ] > ( current_octo->m_voxel_center_[ 1 ] + current_octo->m_quater_length_ ) ) { near_position.y = near_position.y + 1; } else if ( loc_xyz[ 1 ] < ( current_octo->m_voxel_center_[ 1 ] - current_octo->m_quater_length_ ) ) { near_position.y = near_position.y - 1; } if ( loc_xyz[ 2 ] > ( current_octo->m_voxel_center_[ 2 ] + current_octo->m_quater_length_ ) ) { near_position.z = near_position.z + 1; } else if ( loc_xyz[ 2 ] < ( current_octo->m_voxel_center_[ 2 ] - current_octo->m_quater_length_ ) ) { near_position.z = near_position.z - 1; } auto iter_near = voxel_map.find( near_position ); if ( iter_near != voxel_map.end() ) { build_single_residual( pv, iter_near->second, 0, max_layer, sigma_num, is_sucess, prob, single_ptpl ); } } if ( is_sucess ) { mylock.lock(); useful_ptpl[ i ] = true; all_ptpl_list[ i ] = single_ptpl; mylock.unlock(); } else { mylock.lock(); useful_ptpl[ i ] = false; mylock.unlock(); } } } for ( size_t i = 0; i < useful_ptpl.size(); i++ ) { if ( useful_ptpl[ i ] ) { ptpl_list.push_back( all_ptpl_list[ i ] ); } } } void build_single_residual( const Point_with_var &pv, const OctoTree *current_octo, const int current_layer, const int max_layer, const double sigma_num, bool &is_sucess, double &prob, ptpl &single_ptpl ) { double radius_k = 3; Eigen::Vector3d p_w = pv.m_point_world; if ( current_octo->m_plane_ptr_->m_is_plane ) { Plane & plane = *current_octo->m_plane_ptr_; Eigen::Vector3d p_world_to_center = p_w - plane.m_center; float dis_to_plane = fabs( plane.m_normal( 0 ) * p_w( 0 ) + plane.m_normal( 1 ) * p_w( 1 ) + plane.m_normal( 2 ) * p_w( 2 ) + plane.m_d ); float dis_to_center = ( plane.m_center( 0 ) - p_w( 0 ) ) * ( plane.m_center( 0 ) - p_w( 0 ) ) + ( plane.m_center( 1 ) - p_w( 1 ) ) * ( plane.m_center( 1 ) - p_w( 1 ) ) + ( plane.m_center( 2 ) - p_w( 2 ) ) * ( plane.m_center( 2 ) - p_w( 2 ) ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); if ( range_dis <= radius_k * plane.m_radius ) { Eigen::Matrix< double, 1, 6 > J_nq; J_nq.block< 1, 3 >( 0, 0 ) = p_w - plane.m_center; J_nq.block< 1, 3 >( 0, 3 ) = -plane.m_normal; double sigma_l = J_nq * plane.m_plane_var * J_nq.transpose(); sigma_l += plane.m_normal.transpose() * pv.m_var * plane.m_normal; if ( dis_to_plane < sigma_num * sqrt( sigma_l ) ) { is_sucess = true; double this_prob = 1.0 / ( sqrt( sigma_l ) ) * exp( -0.5 * dis_to_plane * dis_to_plane / sigma_l ); if ( this_prob > prob ) { prob = this_prob; single_ptpl.point = pv.m_point; single_ptpl.plane_var = plane.m_plane_var; single_ptpl.normal = plane.m_normal; single_ptpl.center = plane.m_center; single_ptpl.d = plane.m_d; single_ptpl.layer = current_layer; } return; } else { // is_sucess = false; return; } } else { // is_sucess = false; return; } } else { if ( current_layer < max_layer ) { for ( size_t leafnum = 0; leafnum < 8; leafnum++ ) { if ( current_octo->m_leaves_[ leafnum ] != nullptr ) { OctoTree *leaf_octo = current_octo->m_leaves_[ leafnum ]; build_single_residual( pv, leaf_octo, current_layer + 1, max_layer, sigma_num, is_sucess, prob, single_ptpl ); } } return; } else { // is_sucess = false; return; } } } void updateVoxelMap( const std::vector< Point_with_var > &input_points, const float voxel_size, const int max_layer, const std::vector< int > &layer_init_num, const int max_points_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ) { uint plsize = input_points.size(); for ( uint i = 0; i < plsize; i++ ) { const Point_with_var p_v = input_points[ i ]; float loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = p_v.m_point[ j ] / voxel_size; if ( loc_xyz[ j ] < 0 ) { loc_xyz[ j ] -= 1.0; } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); auto iter = feat_map.find( position ); if ( iter != feat_map.end() ) { feat_map[ position ]->UpdateOctoTree( p_v ); } else { OctoTree *octo_tree = new OctoTree( max_layer, 0, layer_init_num, max_points_size, planer_threshold ); feat_map[ position ] = octo_tree; feat_map[ position ]->m_quater_length_ = voxel_size / 4; feat_map[ position ]->m_voxel_center_[ 0 ] = ( 0.5 + position.x ) * voxel_size; feat_map[ position ]->m_voxel_center_[ 1 ] = ( 0.5 + position.y ) * voxel_size; feat_map[ position ]->m_voxel_center_[ 2 ] = ( 0.5 + position.z ) * voxel_size; feat_map[ position ]->UpdateOctoTree( p_v ); } } } V3F RGBFromVoxel( const V3D &input_point, const float voxel_size, const Eigen::Vector3d &layer_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ) { int64_t loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = floor( input_point[ j ] / voxel_size ); // if (loc_xyz[j] < 0) // { // loc_xyz[j] -= 1; // } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); int64_t ind = loc_xyz[ 0 ] + loc_xyz[ 1 ] + loc_xyz[ 2 ]; uint k( ( ind + 100000 ) % 3 ); V3F RGB( ( k == 0 ) * 255.0, ( k == 1 ) * 255.0, ( k == 2 ) * 255.0 ); // cout<<"RGB: "<<RGB.transpose()<<endl; return RGB; } void transformLidar( const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr &input_cloud, pcl::PointCloud< pcl::PointXYZI >::Ptr &trans_cloud ); void BuildPtplList( const unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const float match_eigen_value, const int layer, const float voxel_size, const float match_constraint, const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr input_cloud, std::vector< ptpl > &ptpl_list ) { // debug time double t_sum = 0; int match_plane_size = 0; int match_sub_plane_size = 0; for ( size_t i = 0; i < input_cloud->points.size(); i++ ) { pcl::PointXYZI p_c; p_c.x = input_cloud->points[ i ].x; p_c.y = input_cloud->points[ i ].y; p_c.z = input_cloud->points[ i ].z; p_c.intensity = input_cloud->points[ i ].intensity; pcl::PointXYZI p_w; Eigen::Vector3d p_cv( p_c.x, p_c.y, p_c.z ); Eigen::Vector3d p_wv( p_c.x, p_c.y, p_c.z ); p_wv = rot * ( p_cv ) + t; p_w.x = p_wv( 0 ); p_w.y = p_wv( 1 ); p_w.z = p_wv( 2 ); p_w.intensity = p_c.intensity; float loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = p_w.data[ j ] / voxel_size; if ( loc_xyz[ j ] < 0 ) { loc_xyz[ j ] -= 1.0; } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); auto iter = feat_map.find( position ); bool match_flag = false; float radius_k1 = 1.25; float radius_k2 = 1.25; if ( iter != feat_map.end() ) { if ( iter->second->m_octo_state_ == 0 && iter->second->m_plane_ptr_->m_is_plane && iter->second->m_plane_ptr_->m_min_eigen_value < match_eigen_value ) { // use new dis_threshold; Plane *plane = iter->second->m_plane_ptr_; float dis_to_plane = ( plane->m_normal( 0 ) * p_w.x + plane->m_normal( 1 ) * p_w.y + plane->m_normal( 2 ) * p_w.z + plane->m_d ); float dis_to_center = ( plane->m_center( 0 ) - p_w.x ) * ( plane->m_center( 0 ) - p_w.x ) + ( plane->m_center( 1 ) - p_w.y ) * ( plane->m_center( 1 ) - p_w.y ) + ( plane->m_center( 2 ) - p_w.z ) * ( plane->m_center( 2 ) - p_w.z ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); float s = 1 - 0.9 * fabs( dis_to_plane ) / sqrt( sqrt( p_c.x * p_c.x + p_c.y * p_c.y + p_c.z * p_c.z ) ); float dis_threshold = 3 * sqrt( iter->second->m_plane_ptr_->m_min_eigen_value ); // if (fabs(dis_to_plane) < dis_to_plane_threshold) { if ( s > match_constraint && range_dis < radius_k1 * iter->second->m_plane_ptr_->m_radius ) { // std::cout << "range dis: " << range_dis // << " plane radius: " << iter->second->plane_ptr_->radius // << std::endl; // if (fabs(dis_to_plane) < dis_threshold) { ptpl single_ptpl; single_ptpl.point << p_c.x, p_c.y, p_c.z; single_ptpl.normal << plane->m_normal( 0 ), plane->m_normal( 1 ), plane->m_normal( 2 ); single_ptpl.center = plane->m_center; single_ptpl.plane_var = plane->m_plane_var; single_ptpl.d = plane->m_d; single_ptpl.eigen_value = plane->m_min_eigen_value; ptpl_list.push_back( single_ptpl ); match_plane_size++; //} // std::cout << "3_sigma:" << dis_threshold // << " distance:" << dis_to_plane << std::endl; } } else { if ( layer >= 1 ) { float min_dis = 100; ptpl single_ptpl; for ( int j = 0; j < 8; j++ ) { if ( iter->second->m_leaves_[ j ] != nullptr ) { if ( iter->second->m_leaves_[ j ]->m_plane_ptr_->m_is_plane && iter->second->m_leaves_[ j ]->m_plane_ptr_->m_min_eigen_value < match_eigen_value ) { Plane *plane = iter->second->m_leaves_[ j ]->m_plane_ptr_; float dis_to_plane = ( plane->m_normal( 0 ) * p_w.x + plane->m_normal( 1 ) * p_w.y + plane->m_normal( 2 ) * p_w.z + plane->m_d ); float dis_to_center = ( plane->m_center( 0 ) - p_w.x ) * ( plane->m_center( 0 ) - p_w.x ) + ( plane->m_center( 1 ) - p_w.y ) * ( plane->m_center( 1 ) - p_w.y ) + ( plane->m_center( 2 ) - p_w.z ) * ( plane->m_center( 2 ) - p_w.z ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); float dis_threshold = 3 * sqrt( iter->second->m_leaves_[ j ]->m_plane_ptr_->m_min_eigen_value ); float s = 1 - 0.9 * fabs( dis_to_plane ) / sqrt( sqrt( p_c.x * p_c.x + p_c.y * p_c.y + p_c.z * p_c.z ) ); if ( s > match_constraint && range_dis < radius_k2 * iter->second->m_leaves_[ j ]->m_plane_ptr_->m_radius ) { // std::cout << "3_sigma:" << dis_threshold // << " distance:" << dis_to_plane << std::endl; // if (min_dis > dis_to_plane) { // if (fabs(dis_to_plane > dis_threshold)) { min_dis = dis_to_plane; single_ptpl.point << p_c.x, p_c.y, p_c.z; single_ptpl.normal << plane->m_normal( 0 ), plane->m_normal( 1 ), plane->m_normal( 2 ); single_ptpl.plane_var = plane->m_plane_var; single_ptpl.center = plane->m_center; single_ptpl.d = plane->m_d; single_ptpl.eigen_value = plane->m_min_eigen_value; // ptpl_list.push_back(single_ptpl); // match_sub_plane_size++; //} //} } } } } if ( min_dis != 100 ) { ptpl_list.push_back( single_ptpl ); match_sub_plane_size++; } } } } } // std::cout << "[ Matching ]: match plane size: " << match_plane_size << " , match sub plane size: " << match_sub_plane_size << std::endl; } void BuildResidualList( const unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const double voxel_size, const double sigma_num, const Point_with_var &pv, const M3D &rot, const V3D &t, const M3D &ext_R, const V3D &ext_T, ptpl &ptpl_list ) { float radius_k = 3; int match_index = -1; int match_plane = 0; int match_sub_plane = 0; int match_sub_sub_plane = 0; int check_plane = 0; int check_sub_plane = 0; int check_sub_sub_plane = 0; // ptpl_list.clear(); ptpl_list.is_valid = false; V3D p_w = rot * ( ext_R * pv.m_point + ext_T ) + t; if ( pv.m_point.norm() < 0 ) { return; } float loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = p_w[ j ] / voxel_size; if ( loc_xyz[ j ] < 0 ) { loc_xyz[ j ] -= 1.0; } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); auto iter = feat_map.find( position ); double current_layer = 0; if ( iter != feat_map.end() ) { OctoTree *current_octo = iter->second; ptpl single_ptpl; double max_prob = 0; if ( current_octo->m_plane_ptr_->m_is_plane ) { Plane &plane = *current_octo->m_plane_ptr_; float dis_to_plane = fabs( plane.m_normal( 0 ) * p_w( 0 ) + plane.m_normal( 1 ) * p_w( 1 ) + plane.m_normal( 2 ) * p_w( 2 ) + plane.m_d ); float dis_to_center = ( plane.m_center( 0 ) - p_w( 0 ) ) * ( plane.m_center( 0 ) - p_w( 0 ) ) + ( plane.m_center( 1 ) - p_w( 1 ) ) * ( plane.m_center( 1 ) - p_w( 1 ) ) + ( plane.m_center( 2 ) - p_w( 2 ) ) * ( plane.m_center( 2 ) - p_w( 2 ) ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); if ( range_dis <= radius_k * plane.m_radius ) { Eigen::Matrix< double, 1, 6 > J_nq; J_nq.block< 1, 3 >( 0, 0 ) = p_w - plane.m_center; J_nq.block< 1, 3 >( 0, 3 ) = -plane.m_normal; double sigma_l = J_nq * plane.m_plane_var * J_nq.transpose(); sigma_l += plane.m_normal.transpose() * pv.m_var * plane.m_normal; if ( dis_to_plane < sigma_num * sqrt( sigma_l ) ) { check_plane++; float prob = 1 / ( sqrt( 2 * M_PI ) * sqrt( sigma_l ) ) * exp( -0.5 * dis_to_plane * dis_to_plane / sigma_l ); if ( prob > max_prob ) { max_prob = prob; single_ptpl.point = pv.m_point; single_ptpl.plane_var = plane.m_plane_var; single_ptpl.normal = plane.m_normal; single_ptpl.center = plane.m_center; single_ptpl.d = plane.m_d; single_ptpl.eigen_value = plane.m_min_eigen_value; match_index = 0; } } } } else { for ( size_t leaf_i = 0; leaf_i < 8; leaf_i++ ) { // continue; OctoTree *leaf_octo = current_octo->m_leaves_[ leaf_i ]; if ( leaf_octo != nullptr ) { if ( leaf_octo->m_plane_ptr_->m_is_plane ) { Plane *plane = leaf_octo->m_plane_ptr_; float dis_to_plane = fabs( plane->m_normal( 0 ) * p_w( 0 ) + plane->m_normal( 1 ) * p_w( 1 ) + plane->m_normal( 2 ) * p_w( 2 ) + plane->m_d ); float dis_to_center = ( plane->m_center( 0 ) - p_w( 0 ) ) * ( plane->m_center( 0 ) - p_w( 0 ) ) + ( plane->m_center( 1 ) - p_w( 1 ) ) * ( plane->m_center( 1 ) - p_w( 1 ) ) + ( plane->m_center( 2 ) - p_w( 2 ) ) * ( plane->m_center( 2 ) - p_w( 2 ) ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); if ( range_dis <= radius_k * plane->m_radius ) { Eigen::Matrix< double, 1, 6 > J_nq; J_nq.block< 1, 3 >( 0, 0 ) = p_w - plane->m_center; J_nq.block< 1, 3 >( 0, 3 ) = -plane->m_normal; double sigma_l = J_nq * plane->m_plane_var * J_nq.transpose(); sigma_l += plane->m_normal.transpose() * pv.m_var * plane->m_normal; if ( dis_to_plane < sigma_num * sqrt( sigma_l ) ) { check_sub_plane++; float prob = 1 / ( sqrt( 2 * M_PI ) * sqrt( sigma_l ) ) * exp( -0.5 * dis_to_plane * dis_to_plane / sigma_l ); if ( prob > max_prob ) { max_prob = prob; single_ptpl.point = pv.m_point; single_ptpl.plane_var = plane->m_plane_var; single_ptpl.normal = plane->m_normal; single_ptpl.center = plane->m_center; single_ptpl.d = plane->m_d; single_ptpl.eigen_value = plane->m_min_eigen_value; match_index = 1; } } } } else { for ( size_t leaf_j = 0; leaf_j < 8; leaf_j++ ) { OctoTree *leaf_leaf_octo = leaf_octo->m_leaves_[ leaf_j ]; if ( leaf_leaf_octo != nullptr ) { if ( leaf_leaf_octo->m_plane_ptr_->m_is_plane ) { Plane *plane = leaf_leaf_octo->m_plane_ptr_; float dis_to_plane = fabs( plane->m_normal( 0 ) * p_w( 0 ) + plane->m_normal( 1 ) * p_w( 1 ) + plane->m_normal( 2 ) * p_w( 2 ) + plane->m_d ); float dis_to_center = ( plane->m_center( 0 ) - p_w( 0 ) ) * ( plane->m_center( 0 ) - p_w( 0 ) ) + ( plane->m_center( 1 ) - p_w( 1 ) ) * ( plane->m_center( 1 ) - p_w( 1 ) ) + ( plane->m_center( 2 ) - p_w( 2 ) ) * ( plane->m_center( 2 ) - p_w( 2 ) ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); if ( range_dis <= radius_k * plane->m_radius ) { Eigen::Matrix< double, 1, 6 > J_nq; J_nq.block< 1, 3 >( 0, 0 ) = p_w - plane->m_center; J_nq.block< 1, 3 >( 0, 3 ) = -plane->m_normal; double sigma_l = J_nq * plane->m_plane_var * J_nq.transpose(); sigma_l += plane->m_normal.transpose() * pv.m_var * plane->m_normal; if ( dis_to_plane < sigma_num * sqrt( sigma_l ) ) { check_sub_sub_plane++; float prob = 1 / ( sqrt( 2 * M_PI ) * sqrt( sigma_l ) ) * exp( -0.5 * dis_to_plane * dis_to_plane / sigma_l ); if ( prob > max_prob ) { max_prob = prob; single_ptpl.point = pv.m_point; single_ptpl.plane_var = plane->m_plane_var; single_ptpl.normal = plane->m_normal; single_ptpl.center = plane->m_center; single_ptpl.d = plane->m_d; single_ptpl.eigen_value = plane->m_min_eigen_value; match_index = 2; } } } } } } } } } } if ( max_prob > 0 ) { ptpl_list = ( single_ptpl ); ptpl_list.is_valid = true; if ( match_index == 0 ) { match_plane++; } else if ( match_index == 1 ) { match_sub_plane++; } else if ( match_index == 2 ) { match_sub_sub_plane++; } } else { ptpl_list.is_valid = false; } } } void BuildOptiList( const unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const float voxel_size, const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr input_cloud, const float sigma_num, const std::vector< Eigen::Matrix3d > var_list, std::vector< ptpl > &ptpl_list ) { int match_plane = 0; int match_sub_plane = 0; int match_sub_sub_plane = 0; ptpl_list.clear(); // old 1.25 float radius_k1 = 1.5; float radius_k2 = 1.5; float num_sigma = sigma_num * sigma_num; pcl::PointCloud< pcl::PointXYZI >::Ptr world_cloud( new pcl::PointCloud< pcl::PointXYZI > ); for ( size_t i = 0; i < input_cloud->points.size(); i++ ) { Eigen::Vector3d p_c( input_cloud->points[ i ].x, input_cloud->points[ i ].y, input_cloud->points[ i ].z ); Eigen::Vector3d p_w = rot * ( p_c + Lidar_T_wrt_IMU ) + t; float loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = p_w[ j ] / voxel_size; if ( loc_xyz[ j ] < 0 ) { loc_xyz[ j ] -= 1.0; } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); auto iter = feat_map.find( position ); if ( iter != feat_map.end() ) { if ( iter->second->m_octo_state_ == 0 && iter->second->m_plane_ptr_->m_is_plane ) { Plane *plane = iter->second->m_plane_ptr_; float dis_to_plane = fabs( plane->m_normal( 0 ) * p_w( 0 ) + plane->m_normal( 1 ) * p_w( 1 ) + plane->m_normal( 2 ) * p_w( 2 ) + plane->m_d ); float dis_to_center = ( plane->m_center( 0 ) - p_w( 0 ) ) * ( plane->m_center( 0 ) - p_w( 0 ) ) + ( plane->m_center( 1 ) - p_w( 1 ) ) * ( plane->m_center( 1 ) - p_w( 1 ) ) + ( plane->m_center( 2 ) - p_w( 2 ) ) * ( plane->m_center( 2 ) - p_w( 2 ) ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); Eigen::Vector3d pq = ( p_w - plane->m_center ); pq = pq * dis_to_plane / pq.norm(); if ( pq[ 0 ] * pq[ 0 ] < num_sigma * var_list[ i ]( 0, 0 ) && pq[ 1 ] * pq[ 1 ] < num_sigma * var_list[ i ]( 1, 1 ) && pq[ 2 ] * pq[ 2 ] < num_sigma * var_list[ i ]( 2, 2 ) && range_dis < radius_k1 * plane->m_radius ) { ptpl single_ptpl; single_ptpl.point = p_c; single_ptpl.normal = plane->m_normal; single_ptpl.d = plane->m_d; single_ptpl.eigen_value = plane->m_min_eigen_value; single_ptpl.center = plane->m_center; single_ptpl.plane_var = plane->m_plane_var; ptpl_list.push_back( single_ptpl ); match_plane++; } } else { for ( int j = 0; j < 8; j++ ) { if ( iter->second->m_leaves_[ j ] != nullptr ) { if ( iter->second->m_leaves_[ j ]->m_plane_ptr_->m_is_plane ) { Plane *plane = iter->second->m_leaves_[ j ]->m_plane_ptr_; float dis_to_plane = fabs( plane->m_normal( 0 ) * p_w( 0 ) + plane->m_normal( 1 ) * p_w( 1 ) + plane->m_normal( 2 ) * p_w( 2 ) + plane->m_d ); float dis_to_center = ( plane->m_center( 0 ) - p_w( 0 ) ) * ( plane->m_center( 0 ) - p_w( 0 ) ) + ( plane->m_center( 1 ) - p_w( 1 ) ) * ( plane->m_center( 1 ) - p_w( 1 ) ) + ( plane->m_center( 2 ) - p_w( 2 ) ) * ( plane->m_center( 2 ) - p_w( 2 ) ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); Eigen::Vector3d pq = ( p_w - plane->m_center ); // pq = pq * (dis_to_plane - sqrt(plane->min_eigen_value) / 2) / // pq.norm(); pq = pq * dis_to_plane / pq.norm(); if ( pq[ 0 ] * pq[ 0 ] < num_sigma * var_list[ i ]( 0, 0 ) && pq[ 1 ] * pq[ 1 ] < num_sigma * var_list[ i ]( 1, 1 ) && pq[ 2 ] * pq[ 2 ] < num_sigma * var_list[ i ]( 2, 2 ) && range_dis < radius_k2 * plane->m_radius ) { ptpl single_ptpl; single_ptpl.point = p_c; single_ptpl.normal = plane->m_normal; single_ptpl.center = plane->m_center; single_ptpl.d = plane->m_d; single_ptpl.eigen_value = plane->m_min_eigen_value; single_ptpl.plane_var = plane->m_plane_var; ptpl_list.push_back( single_ptpl ); match_sub_plane++; break; } } else { for ( int k = 0; k < 8; k++ ) { if ( iter->second->m_leaves_[ j ]->m_leaves_[ k ] != nullptr && iter->second->m_leaves_[ j ]->m_leaves_[ k ]->m_plane_ptr_->m_is_plane ) { Plane *plane = iter->second->m_leaves_[ j ]->m_leaves_[ k ]->m_plane_ptr_; float dis_to_plane = fabs( plane->m_normal( 0 ) * p_w( 0 ) + plane->m_normal( 1 ) * p_w( 1 ) + plane->m_normal( 2 ) * p_w( 2 ) + plane->m_d ); float dis_to_center = ( plane->m_center( 0 ) - p_w( 0 ) ) * ( plane->m_center( 0 ) - p_w( 0 ) ) + ( plane->m_center( 1 ) - p_w( 1 ) ) * ( plane->m_center( 1 ) - p_w( 1 ) ) + ( plane->m_center( 2 ) - p_w( 2 ) ) * ( plane->m_center( 2 ) - p_w( 2 ) ); float range_dis = sqrt( dis_to_center - dis_to_plane * dis_to_plane ); Eigen::Vector3d pq = ( p_w - plane->m_center ); // pq = pq * (dis_to_plane - sqrt(plane->min_eigen_value) / 2) // / // pq.norm(); pq = pq * dis_to_plane / pq.norm(); if ( pq[ 0 ] * pq[ 0 ] < num_sigma * var_list[ i ]( 0, 0 ) && pq[ 1 ] * pq[ 1 ] < num_sigma * var_list[ i ]( 1, 1 ) && pq[ 2 ] * pq[ 2 ] < num_sigma * var_list[ i ]( 2, 2 ) && range_dis < radius_k2 * plane->m_radius ) { ptpl single_ptpl; single_ptpl.point = p_c; single_ptpl.normal = plane->m_normal; single_ptpl.center = plane->m_center; single_ptpl.d = plane->m_d; single_ptpl.eigen_value = plane->m_min_eigen_value; single_ptpl.plane_var = plane->m_plane_var; ptpl_list.push_back( single_ptpl ); match_sub_sub_plane++; break; } } } } } } } } } // std::cout << "[ Matching ]: match plane size: " << match_plane << " , match sub plane size: " << match_sub_plane // << " ,match sub sub plane size:" << match_sub_sub_plane << std::endl; } void CalcQuation( const Eigen::Vector3d &vec, const int axis, geometry_msgs::Quaternion &q ) { Eigen::Vector3d x_body = vec; Eigen::Vector3d y_body( 1, 1, 0 ); if ( x_body( 2 ) != 0 ) { y_body( 2 ) = -( y_body( 0 ) * x_body( 0 ) + y_body( 1 ) * x_body( 1 ) ) / x_body( 2 ); } else { if ( x_body( 1 ) != 0 ) { y_body( 1 ) = -( y_body( 0 ) * x_body( 0 ) ) / x_body( 1 ); } else { y_body( 0 ) = 0; } } y_body.normalize(); Eigen::Vector3d z_body = x_body.cross( y_body ); Eigen::Matrix3d rot; rot << x_body( 0 ), x_body( 1 ), x_body( 2 ), y_body( 0 ), y_body( 1 ), y_body( 2 ), z_body( 0 ), z_body( 1 ), z_body( 2 ); Eigen::Matrix3d rotation = rot.transpose(); if ( axis == 2 ) { Eigen::Matrix3d rot_inc; rot_inc << 0, 0, 1, 0, 1, 0, -1, 0, 0; rotation = rotation * rot_inc; } Eigen::Quaterniond eq( rotation ); q.w = eq.w(); q.x = eq.x(); q.y = eq.y(); q.z = eq.z(); } void NormalToQuaternion( const Eigen::Vector3d &normal_vec, geometry_msgs::Quaternion &q ) { float CosY = normal_vec( 2 ) / sqrt( normal_vec( 0 ) * normal_vec( 0 ) + normal_vec( 1 ) * normal_vec( 1 ) ); float CosYDiv2 = sqrt( ( CosY + 1 ) / 2 ); if ( normal_vec( 0 ) < 0 ) CosYDiv2 = -CosYDiv2; float SinYDiv2 = sqrt( ( 1 - CosY ) / 2 ); float CosX = sqrt( ( normal_vec( 0 ) * normal_vec( 0 ) + normal_vec( 2 ) * normal_vec( 2 ) ) / ( normal_vec( 0 ) * normal_vec( 0 ) + normal_vec( 1 ) * normal_vec( 1 ) + normal_vec( 2 ) * normal_vec( 2 ) ) ); if ( normal_vec( 2 ) < 0 ) CosX = -CosX; float CosXDiv2 = sqrt( ( CosX + 1 ) / 2 ); if ( normal_vec( 1 ) < 0 ) CosXDiv2 = -CosXDiv2; float SinXDiv2 = sqrt( ( 1 - CosX ) / 2 ); q.w = CosXDiv2 * CosYDiv2; q.x = SinXDiv2 * CosYDiv2; q.y = CosXDiv2 * SinYDiv2; q.z = -SinXDiv2 * SinYDiv2; } void pubNormal( visualization_msgs::MarkerArray &normal_pub, const std::string normal_ns, const int normal_id, const pcl::PointXYZINormal normal_p, const float alpha, const Eigen::Vector3d rgb ) { visualization_msgs::Marker normal; normal.header.frame_id = "camera_init"; normal.header.stamp = ros::Time(); normal.ns = normal_ns; normal.id = normal_id; normal.type = visualization_msgs::Marker::ARROW; normal.action = visualization_msgs::Marker::ADD; normal.pose.position.x = normal_p.x; normal.pose.position.y = normal_p.y; normal.pose.position.z = normal_p.z; geometry_msgs::Quaternion q; Eigen::Vector3d normal_vec( normal_p.normal_x, normal_p.normal_y, normal_p.normal_z ); CalcQuation( normal_vec, 0, q ); normal.pose.orientation = q; normal.scale.x = 0.4; normal.scale.y = 0.05; normal.scale.z = 0.05; normal.color.a = alpha; // Don't forget to set the alpha! normal.color.r = rgb( 0 ); normal.color.g = rgb( 1 ); normal.color.b = rgb( 2 ); normal.lifetime = ros::Duration(); normal_pub.markers.push_back( normal ); // normal_pub.publish(normal); } void pubPlane( visualization_msgs::MarkerArray &plane_pub, const std::string plane_ns, const int plane_id, const pcl::PointXYZINormal normal_p, const float radius, const float min_eigen_value, const float alpha, const Eigen::Vector3d rgb ) { visualization_msgs::Marker plane; plane.header.frame_id = "camera_init"; plane.header.stamp = ros::Time(); plane.ns = plane_ns; plane.id = plane_id; plane.type = visualization_msgs::Marker::CYLINDER; plane.action = visualization_msgs::Marker::ADD; plane.pose.position.x = normal_p.x; plane.pose.position.y = normal_p.y; plane.pose.position.z = normal_p.z; geometry_msgs::Quaternion q; Eigen::Vector3d normal_vec( normal_p.normal_x, normal_p.normal_y, normal_p.normal_z ); CalcQuation( normal_vec, 2, q ); plane.pose.orientation = q; plane.scale.x = 2 * radius; plane.scale.y = 2 * radius; plane.scale.z = sqrt( min_eigen_value ); plane.color.a = alpha; plane.color.r = rgb( 0 ); plane.color.g = rgb( 1 ); plane.color.b = rgb( 2 ); plane.lifetime = ros::Duration(); plane_pub.markers.push_back( plane ); // plane_pub.publish(plane); } void pubPlaneMap( const std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const ros::Publisher &plane_map_pub, const V3D &position ) { int normal_id = 0; int plane_count = 0; int sub_plane_count = 0; int sub_sub_plane_count = 0; OctoTree *current_octo = nullptr; float plane_threshold = 0.0025; double max_trace = 0.25; double pow_num = 0.2; double dis_threshold = 100; ros::Rate loop( 500 ); float use_alpha = 1.0; int update_count = 0; int id = 0; visualization_msgs::MarkerArray voxel_plane; // visualization_msgs::MarkerArray voxel_norm; voxel_plane.markers.reserve( 1000000 ); for ( auto iter = feat_map.begin(); iter != feat_map.end(); iter++ ) { if ( iter->second->m_plane_ptr_->m_is_update ) { // V3D position_inc = position - iter->second->plane_ptr_->center; // if (position_inc.norm() > dis_threshold) { // continue; // } Eigen::Vector3d normal_rgb( 0.0, 1.0, 1.0 ); V3D plane_var = iter->second->m_plane_ptr_->m_plane_var.block< 3, 3 >( 0, 0 ).diagonal(); double trace = plane_var.sum(); // outfile << trace << "," << iter->second->plane_ptr_->points_size << "," // << 0 << std::endl; if ( trace >= max_trace ) { trace = max_trace; } trace = trace * ( 1.0 / max_trace ); // trace = (max_trace - trace) / max_trace; trace = pow( trace, pow_num ); uint8_t r, g, b; mapJet( trace, 0, 1, r, g, b ); Eigen::Vector3d plane_rgb( r / 256.0, g / 256.0, b / 256.0 ); // if (plane_var.norm() < 0.001) { // plane_rgb << 1, 0, 0; // } else if (plane_var.norm() < 0.005) { // plane_rgb << 0, 1, 0; // } else { // plane_rgb << 0, 0, 1; // } // plane_rgb << plane_var[0] / 0.0001, plane_var[1] / 0.0001, // plane_var[2] / 0.0001; // plane_rgb << fabs(iter->second->plane_ptr_->normal[0]), // fabs(iter->second->plane_ptr_->normal[1]), // fabs(iter->second->plane_ptr_->normal[2]); float alpha = 0.0; if ( iter->second->m_plane_ptr_->m_is_plane ) { alpha = use_alpha; } else { std::cout << "delete plane" << std::endl; } // pubNormal(plane_map_pub, "normal", iter->second->plane_ptr_->id, // iter->second->plane_ptr_->p_center, alpha, normal_rgb); // loop.sleep(); pubPlane( voxel_plane, "plane", iter->second->m_plane_ptr_->m_id, iter->second->m_plane_ptr_->m_p_center, 1.25 * iter->second->m_plane_ptr_->m_radius, iter->second->m_plane_ptr_->m_min_eigen_value, alpha, plane_rgb ); // loop.sleep(); iter->second->m_plane_ptr_->m_is_update = false; update_count++; plane_count++; } else { for ( uint i = 0; i < 8; i++ ) { if ( iter->second->m_leaves_[ i ] != nullptr ) { if ( iter->second->m_leaves_[ i ]->m_plane_ptr_->m_is_update ) { // std::cout << "plane var:" // << iter->second->leaves_[i] // ->plane_ptr_->plane_var.diagonal() // .transpose() // << std::endl; V3D position_inc = position - iter->second->m_leaves_[ i ]->m_plane_ptr_->m_center; // if (position_inc.norm() > dis_threshold) { // continue; // } Eigen::Vector3d normal_rgb( 112.0 / 255, 173.0 / 255, 71.0 / 255 ); V3D plane_var = iter->second->m_leaves_[ i ]->m_plane_ptr_->m_plane_var.block< 3, 3 >( 0, 0 ).diagonal(); double trace = plane_var.sum(); // outfile << trace << "," // << iter->second->leaves_[i]->plane_ptr_->points_size << // ",1" // << std::endl; if ( trace >= max_trace ) { trace = max_trace; } trace = trace * ( 1.0 / max_trace ); // trace = (max_trace - trace) / max_trace; trace = pow( trace, pow_num ); uint8_t r, g, b; mapJet( trace, 0, 1, r, g, b ); Eigen::Vector3d plane_rgb( r / 256.0, g / 256.0, b / 256.0 ); // plane_rgb << // fabs(iter->second->leaves_[i]->plane_ptr_->normal[0]), // fabs(iter->second->leaves_[i]->plane_ptr_->normal[1]), // fabs(iter->second->leaves_[i]->plane_ptr_->normal[2]); float alpha = 0.0; if ( iter->second->m_leaves_[ i ]->m_plane_ptr_->m_is_plane ) { alpha = use_alpha; } else { std::cout << "delete plane" << std::endl; } // pubNormal(plane_map_pub, "normal", // iter->second->leaves_[i]->plane_ptr_->id, // iter->second->leaves_[i]->plane_ptr_->p_center, alpha, // normal_rgb); // loop.sleep(); pubPlane( voxel_plane, "plane", iter->second->m_leaves_[ i ]->m_plane_ptr_->m_id, iter->second->m_leaves_[ i ]->m_plane_ptr_->m_p_center, 1.25 * iter->second->m_leaves_[ i ]->m_plane_ptr_->m_radius, iter->second->m_leaves_[ i ]->m_plane_ptr_->m_min_eigen_value, alpha, plane_rgb ); // loop.sleep(); iter->second->m_leaves_[ i ]->m_plane_ptr_->m_is_update = false; update_count++; sub_plane_count++; normal_id++; // loop.sleep(); } else { OctoTree *temp_octo_tree = iter->second->m_leaves_[ i ]; for ( uint j = 0; j < 8; j++ ) { if ( temp_octo_tree->m_leaves_[ j ] != nullptr ) { if ( temp_octo_tree->m_leaves_[ j ]->m_octo_state_ == 0 && temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_is_update ) { // std::cout << "plane var:" // << temp_octo_tree->leaves_[j] // ->plane_ptr_->plane_var.diagonal() // .transpose() // << std::endl; V3D position_inc = position - temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_center; // if (position_inc.norm() > dis_threshold) { // continue; // } if ( temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_is_plane ) { // std::cout << "subsubplane" << std::endl; Eigen::Vector3d normal_rgb( 1.0, 0.0, 0.0 ); V3D plane_var = temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_plane_var.block< 3, 3 >( 0, 0 ).diagonal(); double trace = plane_var.sum(); // outfile // << trace << "," // << // temp_octo_tree->leaves_[j]->plane_ptr_->points_size // << ",2" << std::endl; if ( trace >= max_trace ) { trace = max_trace; } trace = trace * ( 1.0 / max_trace ); // trace = (max_trace - trace) / max_trace; trace = pow( trace, pow_num ); uint8_t r, g, b; mapJet( trace, 0, 1, r, g, b ); Eigen::Vector3d plane_rgb( r / 256.0, g / 256.0, b / 256.0 ); float alpha = 0.0; if ( temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_is_plane ) { alpha = use_alpha; } // pubNormal(plane_map_pub, "normal", // iter->second->leaves_[i]->plane_ptr_->id, // temp_octo_tree->leaves_[j]->plane_ptr_->p_center, // alpha, normal_rgb); pubPlane( voxel_plane, "plane", temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_id, temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_p_center, temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_radius, temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_min_eigen_value, alpha, plane_rgb ); // loop.sleep(); temp_octo_tree->m_leaves_[ j ]->m_plane_ptr_->m_is_update = false; update_count++; } sub_sub_plane_count++; // loop.sleep(); } } } } } } } } plane_map_pub.publish( voxel_plane ); // plane_map_pub.publish(voxel_norm); loop.sleep(); cout << "[Map Info] Plane counts:" << plane_count << " Sub Plane counts:" << sub_plane_count << " Sub Sub Plane counts:" << sub_sub_plane_count << endl; cout << "[Map Info] Update plane counts:" << update_count << "total size: " << feat_map.size() << endl; } // Similar with PCL voxelgrid filter void down_sampling_voxel( pcl::PointCloud< pcl::PointXYZI > &pl_feat, double voxel_size ) { int intensity = rand() % 255; if ( voxel_size < 0.01 ) { return; } std::unordered_map< VOXEL_LOC, M_POINT > feat_map; uint plsize = pl_feat.size(); for ( uint i = 0; i < plsize; i++ ) { pcl::PointXYZI &p_c = pl_feat[ i ]; float loc_xyz[ 3 ]; for ( int j = 0; j < 3; j++ ) { loc_xyz[ j ] = p_c.data[ j ] / voxel_size; if ( loc_xyz[ j ] < 0 ) { loc_xyz[ j ] -= 1.0; } } VOXEL_LOC position( ( int64_t ) loc_xyz[ 0 ], ( int64_t ) loc_xyz[ 1 ], ( int64_t ) loc_xyz[ 2 ] ); auto iter = feat_map.find( position ); if ( iter != feat_map.end() ) { iter->second.xyz[ 0 ] += p_c.x; iter->second.xyz[ 1 ] += p_c.y; iter->second.xyz[ 2 ] += p_c.z; iter->second.intensity += p_c.intensity; iter->second.count++; } else { M_POINT anp; anp.xyz[ 0 ] = p_c.x; anp.xyz[ 1 ] = p_c.y; anp.xyz[ 2 ] = p_c.z; anp.intensity = p_c.intensity; anp.count = 1; feat_map[ position ] = anp; } } plsize = feat_map.size(); pl_feat.clear(); pl_feat.resize( plsize ); uint i = 0; for ( auto iter = feat_map.begin(); iter != feat_map.end(); ++iter ) { pl_feat[ i ].x = iter->second.xyz[ 0 ] / iter->second.count; pl_feat[ i ].y = iter->second.xyz[ 1 ] / iter->second.count; pl_feat[ i ].z = iter->second.xyz[ 2 ] / iter->second.count; pl_feat[ i ].intensity = iter->second.intensity / iter->second.count; i++; } } void calcBodyVar( Eigen::Vector3d &pb, const float range_inc, const float degree_inc, Eigen::Matrix3d &var ) { if ( pb[ 2 ] == 0 ) pb[ 2 ] = 0.0001; float range = sqrt( pb[ 0 ] * pb[ 0 ] + pb[ 1 ] * pb[ 1 ] + pb[ 2 ] * pb[ 2 ] ); float range_var = range_inc * range_inc; Eigen::Matrix2d direction_var; direction_var << pow( sin( DEG2RAD( degree_inc ) ), 2 ), 0, 0, pow( sin( DEG2RAD( degree_inc ) ), 2 ); Eigen::Vector3d direction( pb ); direction.normalize(); Eigen::Matrix3d direction_hat; direction_hat << 0, -direction( 2 ), direction( 1 ), direction( 2 ), 0, -direction( 0 ), -direction( 1 ), direction( 0 ), 0; Eigen::Vector3d base_vector1( 1, 1, -( direction( 0 ) + direction( 1 ) ) / direction( 2 ) ); base_vector1.normalize(); Eigen::Vector3d base_vector2 = base_vector1.cross( direction ); base_vector2.normalize(); Eigen::Matrix< double, 3, 2 > N; N << base_vector1( 0 ), base_vector2( 0 ), base_vector1( 1 ), base_vector2( 1 ), base_vector1( 2 ), base_vector2( 2 ); Eigen::Matrix< double, 3, 2 > A = range * direction_hat * N; var = direction * range_var * direction.transpose() + A * direction_var * A.transpose(); }; bool Voxel_mapping::voxel_map_init() { pcl::PointCloud< pcl::PointXYZI >::Ptr world_lidar( new pcl::PointCloud< pcl::PointXYZI > ); Eigen::Quaterniond q( state.rot_end ); // std::cout << "Begin build unorder map" << std::endl; transformLidar( state.rot_end, state.pos_end, m_feats_undistort, world_lidar ); std::vector< Point_with_var > pv_list; pv_list.reserve( world_lidar->size() ); for ( size_t i = 0; i < world_lidar->size(); i++ ) { Point_with_var pv; pv.m_point << world_lidar->points[ i ].x, world_lidar->points[ i ].y, world_lidar->points[ i ].z; V3D point_this( m_feats_undistort->points[ i ].x, m_feats_undistort->points[ i ].y, m_feats_undistort->points[ i ].z ); M3D var; calcBodyVar( point_this, m_dept_err, m_beam_err, var ); M3D point_crossmat; point_crossmat << SKEW_SYM_MATRX( point_this ); var = state.rot_end * var * state.rot_end.transpose() + ( -point_crossmat ) * state.cov.block< 3, 3 >( 0, 0 ) * ( -point_crossmat ).transpose() + state.cov.block< 3, 3 >( 3, 3 ); pv.m_var = var; pv_list.push_back( pv ); // if ( i % 300 == 3 ) // { // printf( "pw: %lf %lf %lf, var: %lf %lf %lf \n", world_lidar->points[ i ].x, world_lidar->points[ i ].y, // world_lidar->points[ i ].z, var( 0, 0 ), var( 1, 1 ), var( 2, 2 ) ); // } } buildVoxelMap( pv_list, m_max_voxel_size, m_max_layer, m_layer_init_size, m_max_points_size, m_min_eigen_value, m_feat_map ); // std::cout << "Build unorderMap,init points size:" << world_lidar->size() << std::endl; // std::cout << "params: " << pv_list.size() << " " << m_max_voxel_size << " [" << m_layer_size.transpose() << "] " << m_min_eigen_value << " " // << m_feat_map.size() << endl; // std::cout << "state: " << state.rot_end << " " << state.pos_end << endl; return true; } /*** EKF update ***/ void Voxel_mapping::lio_state_estimation( StatesGroup &state_propagat ) { m_point_selected_surf.resize( m_feats_down_size, true ); m_pointSearchInd_surf.resize( m_feats_down_size ); m_Nearest_Points.resize( m_feats_down_size ); m_cross_mat_list.clear(); m_cross_mat_list.reserve( m_feats_down_size ); m_body_cov_list.clear(); m_body_cov_list.reserve( m_feats_down_size ); if ( m_use_new_map ) { if ( m_feat_map.empty() ) { printf( "feat_map.empty!!" ); return; } for ( size_t i = 0; i < m_feats_down_body->size(); i++ ) { V3D point_this( m_feats_down_body->points[ i ].x, m_feats_down_body->points[ i ].y, m_feats_down_body->points[ i ].z ); if ( point_this[ 2 ] == 0 ) { point_this[ 2 ] = 0.001; } M3D var; calcBodyVar( point_this, m_dept_err, m_beam_err, var ); m_body_cov_list.push_back( var ); point_this = m_extR * point_this + m_extT; M3D point_crossmat; point_crossmat << SKEW_SYM_MATRX( point_this ); m_cross_mat_list.push_back( point_crossmat ); } } if ( !m_flg_EKF_inited ) return; m_point_selected_surf.resize( m_feats_down_size, true ); m_Nearest_Points.resize( m_feats_down_size ); int rematch_num = 0; bool nearest_search_en = true; // MD( DIM_STATE, DIM_STATE ) G, H_T_H, I_STATE; G.setZero(); H_T_H.setZero(); I_STATE.setIdentity(); for ( int iterCount = 0; iterCount < NUM_MAX_ITERATIONS; iterCount++ ) { m_laserCloudOri->clear(); // m_corr_normvect->clear(); // m_total_residual = 0.0; // std::vector< double > r_list; std::vector< ptpl > ptpl_list; // ptpl_list.reserve( m_feats_down_size ); if ( m_use_new_map ) { vector< Point_with_var > pv_list; pcl::PointCloud< pcl::PointXYZI >::Ptr world_lidar( new pcl::PointCloud< pcl::PointXYZI > ); transformLidar( state.rot_end, state.pos_end, m_feats_down_body, world_lidar ); M3D rot_var = state.cov.block< 3, 3 >( 0, 0 ); M3D t_var = state.cov.block< 3, 3 >( 3, 3 ); for ( size_t i = 0; i < m_feats_down_body->size(); i++ ) { Point_with_var pv; pv.m_point << m_feats_down_body->points[ i ].x, m_feats_down_body->points[ i ].y, m_feats_down_body->points[ i ].z; pv.m_point_world << world_lidar->points[ i ].x, world_lidar->points[ i ].y, world_lidar->points[ i ].z; M3D cov = m_body_cov_list[ i ]; M3D point_crossmat = m_cross_mat_list[ i ]; cov = state.rot_end * cov * state.rot_end.transpose() + ( -point_crossmat ) * rot_var * ( -point_crossmat.transpose() ) + t_var; pv.m_var = cov; pv_list.push_back( pv ); } // std::cout << "rot var:" << rot_var << std::endl; // std::cout << "t var:" << t_var << std::endl; auto scan_match_time_start = std::chrono::high_resolution_clock::now(); std::vector< V3D > non_match_list; // int m_max_layer = 4; BuildResidualListOMP( m_feat_map, m_max_voxel_size, 3.0, m_max_layer, pv_list, ptpl_list, non_match_list ); m_effct_feat_num = 0; int layer_match[ 4 ] = { 0 }; // int layer0 = 0; // int layer1 = 0; // int layer2 = 0; // int layer3 = 0; for ( int i = 0; i < ptpl_list.size(); i++ ) { PointType pi_body; PointType pi_world; PointType pl; pi_body.x = ptpl_list[ i ].point( 0 ); pi_body.y = ptpl_list[ i ].point( 1 ); pi_body.z = ptpl_list[ i ].point( 2 ); Eigen::Vector3d point_world; pointBodyToWorld( ptpl_list[ i ].point, point_world ); pl.x = ptpl_list[ i ].normal( 0 ); pl.y = ptpl_list[ i ].normal( 1 ); pl.z = ptpl_list[ i ].normal( 2 ); m_effct_feat_num++; float dis = ( point_world[ 0 ] * pl.x + point_world[ 1 ] * pl.y + point_world[ 2 ] * pl.z + ptpl_list[ i ].d ); pl.intensity = dis; m_laserCloudOri->push_back( pi_body ); m_corr_normvect->push_back( pl ); m_total_residual += fabs( dis ); layer_match[ ptpl_list[ i ].layer ]++; } auto scan_match_time_end = std::chrono::high_resolution_clock::now(); m_res_mean_last = m_total_residual / m_effct_feat_num; // for ( int k = 0; k < 4; k++ ) // { // std::cout << "layer " << k << ": " << layer_match[ k ] << std::endl; // } } else { /** Old map ICP **/ #ifdef MP_EN omp_set_num_threads( 10 ); #pragma omp parallel for #endif for ( int i = 0; i < m_feats_down_size; i++ ) { PointType &point_body = m_feats_down_body->points[ i ]; PointType &point_world = m_feats_down_world->points[ i ]; V3D p_body( point_body.x, point_body.y, point_body.z ); /* transform to world frame */ pointBodyToWorld( point_body, point_world ); vector< float > pointSearchSqDis( NUM_MATCH_POINTS ); #ifdef USE_ikdtree auto &points_near = m_Nearest_Points[ i ]; #else auto &points_near = pointSearchInd_surf[ i ]; #endif uint8_t search_flag = 0; double search_start = omp_get_wtime(); if ( nearest_search_en ) { /** Find the closest surfaces in the map **/ #ifdef USE_ikdtree #ifdef USE_ikdforest search_flag = ikdforest.Nearest_Search( point_world, NUM_MATCH_POINTS, points_near, pointSearchSqDis, first_lidar_time, 5 ); #else m_ikdtree.Nearest_Search( point_world, NUM_MATCH_POINTS, points_near, pointSearchSqDis ); #endif #else kdtreeSurfFromMap->nearestKSearch( point_world, NUM_MATCH_POINTS, points_near, pointSearchSqDis ); #endif m_point_selected_surf[ i ] = pointSearchSqDis[ NUM_MATCH_POINTS - 1 ] > 5 ? false : true; #ifdef USE_ikdforest point_selected_surf[ i ] = point_selected_surf[ i ] && ( search_flag == 0 ); #endif m_kdtree_search_time += omp_get_wtime() - search_start; m_kdtree_search_counter++; } if ( !m_point_selected_surf[ i ] || points_near.size() < NUM_MATCH_POINTS ) continue; VF( 4 ) pabcd; m_point_selected_surf[ i ] = false; if ( esti_plane( pabcd, points_near, 0.05f ) ) //(planeValid) { float pd2 = pabcd( 0 ) * point_world.x + pabcd( 1 ) * point_world.y + pabcd( 2 ) * point_world.z + pabcd( 3 ); float s = 1 - 0.9 * fabs( pd2 ) / sqrt( p_body.norm() ); if ( s > 0.9 ) { m_point_selected_surf[ i ] = true; m_normvec->points[ i ].x = pabcd( 0 ); m_normvec->points[ i ].y = pabcd( 1 ); m_normvec->points[ i ].z = pabcd( 2 ); m_normvec->points[ i ].intensity = pd2; m_res_last[ i ] = abs( pd2 ); } } } // cout<<"pca time test: "<<pca_time1<<" "<<pca_time2<<endl; m_effct_feat_num = 0; for ( int i = 0; i < m_feats_down_size; i++ ) { if ( m_point_selected_surf[ i ] && ( m_res_last[ i ] <= 2.0 ) ) { m_laserCloudOri->points[ m_effct_feat_num ] = m_feats_down_body->points[ i ]; m_corr_normvect->points[ m_effct_feat_num ] = m_normvec->points[ i ]; m_total_residual += m_res_last[ i ]; m_effct_feat_num++; } } m_res_mean_last = m_total_residual / m_effct_feat_num; } // std::cout << "pose:" << state.pos_end.transpose() << std::endl; // cout << "[ mapping ]: Effective feature num: " << m_effct_feat_num << ", ds size:" << m_feats_down_size // << " , raw size:" << m_feats_undistort->size() << " res_mean_last " << m_res_mean_last << endl; double solve_start = omp_get_wtime(); /*** Computation of Measuremnt Jacobian matrix H and measurents covarience * ***/ MatrixXd Hsub( m_effct_feat_num, 6 ); MatrixXd Hsub_T_R_inv( 6, m_effct_feat_num ); VectorXd R_inv( m_effct_feat_num ); VectorXd meas_vec( m_effct_feat_num ); meas_vec.setZero(); for ( int i = 0; i < m_effct_feat_num; i++ ) { const PointType &laser_p = m_laserCloudOri->points[ i ]; V3D point_this( laser_p.x, laser_p.y, laser_p.z ); V3D point_body( laser_p.x, laser_p.y, laser_p.z ); point_this = m_extR * point_this + m_extT; M3D point_crossmat; point_crossmat << SKEW_SYM_MATRX( point_this ); /*** get the normal vector of closest surface/corner ***/ PointType &norm_p = m_corr_normvect->points[ i ]; V3D norm_vec( norm_p.x, norm_p.y, norm_p.z ); if ( m_use_new_map ) { V3D point_world = state.rot_end * point_this + state.pos_end; // /*** get the normal vector of closest surface/corner ***/ M3D var; if ( m_p_pre->calib_laser ) { calcBodyVar( point_this, m_dept_err, CALIB_ANGLE_COV, var ); } else { calcBodyVar( point_this, m_dept_err, m_beam_err, var ); } var = state.rot_end * m_extR * var * ( state.rot_end * m_extR ).transpose(); // bug exist, to be fixed Eigen::Matrix< double, 1, 6 > J_nq; J_nq.block< 1, 3 >( 0, 0 ) = point_world - ptpl_list[ i ].center; J_nq.block< 1, 3 >( 0, 3 ) = -ptpl_list[ i ].normal; double sigma_l = J_nq * ptpl_list[ i ].plane_var * J_nq.transpose(); R_inv( i ) = 1.0 / ( sigma_l + norm_vec.transpose() * var * norm_vec ); // if (fabs(ptpl_list[i].normal[2]) > 0.7) { // R_inv(i) = // 1.0 / (0.0009 + sigma_l + norm_vec.transpose() * var * // norm_vec); // } else { // // } // R_inv(i) = 1000;0.0004 + // cout<<"sigma_l: "<<sigma_l<<" "<<var(0,0)<<" "<<var(1,1)<<" // "<<var(2,2)<<" "<<norm_vec.transpose()<<endl; // if ( fabs( reflec_ang_cos ) < 0.15 && point_this.norm() < 8 ) // { // // R_inv(i) = 1; // // norm_p.intensity = 0; // // cout<<" angle: "<<acosf(reflec_ang_cos)*57.3<<" point_this: // // "<<point_world[2]<<endl; // } // else // { // // depth_err = 0.0; // } // printf("R_inv(i): %.6lf index: %d \n", R_inv(i), i); } else { R_inv( i ) = 1 / LASER_POINT_COV; } m_laserCloudOri->points[ i ].intensity = sqrt( R_inv( i ) ); // R_inv(i) = 1.0; /*** calculate the Measuremnt Jacobian matrix H ***/ V3D A( point_crossmat * state.rot_end.transpose() * norm_vec ); Hsub.row( i ) << VEC_FROM_ARRAY( A ), norm_p.x, norm_p.y, norm_p.z; Hsub_T_R_inv.col( i ) << A[ 0 ] * R_inv( i ), A[ 1 ] * R_inv( i ), A[ 2 ] * R_inv( i ), norm_p.x * R_inv( i ), norm_p.y * R_inv( i ), norm_p.z * R_inv( i ); // cout<<"Hsub.row(i): "<<Hsub.row(i)<<" "<<norm_vec.transpose()<<endl; // cout<<"Hsub_T_R_inv.row(i): "<<Hsub_T_R_inv.col(i).transpose()<<endl; /*** Measuremnt: distance to the closest surface/corner ***/ meas_vec( i ) = -norm_p.intensity; // if (iterCount == 0) fout_dbg<<setprecision(6)<<i<<" "<<meas_vec[i]<<" // "<<Hsub.row(i)<<endl; if (fabs(meas_vec(i)) > 0.07) // { // printf("meas_vec(i): %.6lf index: %d \n", meas_vec(i), i); // } } m_solve_const_H_time += omp_get_wtime() - solve_start; m_EKF_stop_flg = false; m_flg_EKF_converged = false; MatrixXd K( DIM_STATE, m_effct_feat_num ); /*** Iterative Kalman Filter Update ***/ // auto &&Hsub_T = Hsub.transpose(); auto &&HTz = Hsub_T_R_inv * meas_vec; H_T_H.block< 6, 6 >( 0, 0 ) = Hsub_T_R_inv * Hsub; // EigenSolver<Matrix<double, 6, 6>> es(H_T_H.block<6,6>(0,0)); MD( DIM_STATE, DIM_STATE ) &&K_1 = ( H_T_H + state.cov.inverse() ).inverse(); G.block< DIM_STATE, 6 >( 0, 0 ) = K_1.block< DIM_STATE, 6 >( 0, 0 ) * H_T_H.block< 6, 6 >( 0, 0 ); auto vec = state_propagat - state; VD( DIM_STATE ) solution = K_1.block< DIM_STATE, 6 >( 0, 0 ) * HTz + vec - G.block< DIM_STATE, 6 >( 0, 0 ) * vec.block< 6, 1 >( 0, 0 ); // K = K_1.block<DIM_STATE,6>(0,0) * Hsub_T_R_inv; // solution = K * meas_vec + vec - K * Hsub * vec.block<6,1>(0,0); int minRow, minCol; if ( 0 ) // if(V.minCoeff(&minRow, &minCol) < 1.0f) { VD( 6 ) V = H_T_H.block< 6, 6 >( 0, 0 ).eigenvalues().real(); cout << "!!!!!! Degeneration Happend, eigen values: " << V.transpose() << endl; m_EKF_stop_flg = true; solution.block< 6, 1 >( 9, 0 ).setZero(); } state += solution; auto rot_add = solution.block< 3, 1 >( 0, 0 ); auto t_add = solution.block< 3, 1 >( 3, 0 ); // cout<<"solution: "<<solution.transpose()<<endl; // cout<<"HTz: "<<HTz.transpose()<<endl; // cout<<"H_T_H sub: "<<H_T_H.block<6,6>(0,0)<<endl; // cout<<"cov: "<<endl; // cout<<state.cov.diagonal().transpose()<<endl; // cout<<"state up: "<<state.pos_end.transpose()<<" // "<<state.vel_end.transpose()<<endl; cout<<"vec: "<<vec.transpose()<<endl; if ( ( rot_add.norm() * 57.3 < 0.01 ) && ( t_add.norm() * 100 < 0.015 ) ) { m_flg_EKF_converged = true; } m_euler_cur = RotMtoEuler( state.rot_end ); /*** Rematch Judgement ***/ nearest_search_en = false; if ( m_flg_EKF_converged || ( ( rematch_num == 0 ) && ( iterCount == ( NUM_MAX_ITERATIONS - 2 ) ) ) ) { nearest_search_en = true; rematch_num++; } /*** Convergence Judgements and Covariance Update ***/ if ( !m_EKF_stop_flg && ( rematch_num >= 2 || ( iterCount == NUM_MAX_ITERATIONS - 1 ) ) ) { /*** Covariance Update ***/ state.cov = ( I_STATE - G ) * state.cov; m_total_distance += ( state.pos_end - m_position_last ).norm(); m_position_last = state.pos_end; m_geo_Quat = tf::createQuaternionMsgFromRollPitchYaw( m_euler_cur( 0 ), m_euler_cur( 1 ), m_euler_cur( 2 ) ); // VD(DIM_STATE) K_sum = K.rowwise().sum(); // VD(DIM_STATE) P_diag = state.cov.diagonal(); m_EKF_stop_flg = true; } m_solve_time += omp_get_wtime() - solve_start; if ( m_EKF_stop_flg ) break; } } void Voxel_mapping::init_ros_node() { m_ros_node_ptr = std::make_shared< ros::NodeHandle >(); read_ros_parameters( *m_ros_node_ptr ); } int Voxel_mapping::service_LiDAR_update() { cout << "debug:" << m_debug << " MIN_IMG_COUNT: " << MIN_IMG_COUNT << endl; m_pcl_wait_pub->clear(); // if (m_lidar_en) // { ros::Subscriber sub_pcl; if ( m_p_pre->lidar_type == AVIA ) { sub_pcl = m_ros_node_ptr->subscribe( m_lid_topic, 200000, &Voxel_mapping::livox_pcl_cbk, this ); } else { sub_pcl = m_ros_node_ptr->subscribe( m_lid_topic, 200000, &Voxel_mapping::standard_pcl_cbk, this ); } // } ros::Subscriber sub_imu = m_ros_node_ptr->subscribe( m_imu_topic, 200000, &Voxel_mapping::imu_cbk, this ); // ros::Subscriber sub_img = m_ros_node_ptr->subscribe(m_img_topic, 200000, img_cbk); ros::Publisher pubLaserCloudFullRes = m_ros_node_ptr->advertise< sensor_msgs::PointCloud2 >( "/cloud_registered", 100 ); ros::Publisher pubLaserCloudVoxel = m_ros_node_ptr->advertise< sensor_msgs::PointCloud2 >( "/cloud_voxel", 100 ); ros::Publisher pubVisualCloud = m_ros_node_ptr->advertise< sensor_msgs::PointCloud2 >( "/cloud_visual_map", 100 ); ros::Publisher pubSubVisualCloud = m_ros_node_ptr->advertise< sensor_msgs::PointCloud2 >( "/cloud_visual_sub_map", 100 ); ros::Publisher pubLaserCloudEffect = m_ros_node_ptr->advertise< sensor_msgs::PointCloud2 >( "/cloud_effected", 100 ); ros::Publisher pubLaserCloudMap = m_ros_node_ptr->advertise< sensor_msgs::PointCloud2 >( "/Laser_map", 100 ); ros::Publisher pubOdomAftMapped = m_ros_node_ptr->advertise< nav_msgs::Odometry >( "/aft_mapped_to_init", 10 ); ros::Publisher pubPath = m_ros_node_ptr->advertise< nav_msgs::Path >( "/path", 10 ); ros::Publisher plane_pub = m_ros_node_ptr->advertise< visualization_msgs::Marker >( "/planner_normal", 1 ); ros::Publisher voxel_pub = m_ros_node_ptr->advertise< visualization_msgs::MarkerArray >( "/voxels", 1 ); // #ifdef DEPLOY ros::Publisher mavros_pose_publisher = m_ros_node_ptr->advertise< geometry_msgs::PoseStamped >( "/mavros/vision_pose/pose", 10 ); // #endif m_pub_path.header.stamp = ros::Time::now(); m_pub_path.header.frame_id = "camera_init"; FILE *fp_kitti; // string kitti_log_dir = "/home/zivlin/temp/FAST-LIO-Voxelmap//Log/" // "kitti_log_voxelmap.txt"; string kitti_log_dir = std::string( ROOT_DIR ).append( "/Log/kitti_log_voxelmap.txt" ); fp_kitti = fopen( kitti_log_dir.c_str(), "w" ); /*** variables definition ***/ #ifndef USE_IKFOM VD( DIM_STATE ) solution; MD( DIM_STATE, DIM_STATE ) G, H_T_H, I_STATE; V3D rot_add, t_add; StatesGroup state_propagat; PointType pointOri, pointSel, coeff; #endif // PointCloudXYZI::Ptr corr_normvect(new PointCloudXYZI(100000, 1)); int effect_feat_num = 0, frame_num = 0; double deltaT, deltaR, aver_time_consu = 0, aver_time_icp = 0, aver_time_match = 0, aver_time_solve = 0, aver_time_const_H_time = 0; FOV_DEG = ( m_fov_deg + 10.0 ) > 179.9 ? 179.9 : ( m_fov_deg + 10.0 ); HALF_FOV_COS = cos( ( FOV_DEG ) *0.5 * PI_M / 180.0 ); m_downSizeFilterSurf.setLeafSize( m_filter_size_surf_min, m_filter_size_surf_min, m_filter_size_surf_min ); // downSizeFilterMap.setLeafSize(filter_size_map_min, filter_size_map_min, // filter_size_map_min); #ifdef USE_ikdforest ikdforest.Set_balance_criterion_param( 0.6 ); ikdforest.Set_delete_criterion_param( 0.5 ); ikdforest.Set_environment( laserCloudDepth, laserCloudWidth, laserCloudHeight, cube_len ); ikdforest.Set_downsample_param( filter_size_map_min ); #endif shared_ptr< ImuProcess > p_imu( new ImuProcess() ); // p_imu->set_extrinsic(V3D(0.04165, 0.02326, -0.0284)); //avia // p_imu->set_extrinsic(V3D(0.05512, 0.02226, -0.0297)); //horizon m_extT << VEC_FROM_ARRAY( m_extrin_T ); m_extR << MAT_FROM_ARRAY( m_extrin_R ); p_imu->set_extrinsic( m_extT, m_extR ); cout << "IMU set extrinsic_R:\r\n " << m_extR << endl; cout << "IMU set extrinsic_t:\r\n " << vec_3( m_extrin_T[ 0 ], m_extrin_T[ 1 ], m_extrin_T[ 2 ] ).transpose() << endl; p_imu->set_gyr_cov_scale( V3D( m_gyr_cov, m_gyr_cov, m_gyr_cov ) ); p_imu->set_acc_cov_scale( V3D( m_acc_cov, m_acc_cov, m_acc_cov ) ); p_imu->set_gyr_bias_cov( V3D( 0.0001, 0.0001, 0.0001 ) ); p_imu->set_acc_bias_cov( V3D( 0.0001, 0.0001, 0.0001 ) ); p_imu->set_imu_init_frame_num( m_imu_int_frame ); if ( !m_imu_en ) p_imu->disable_imu(); #ifndef USE_IKFOM G.setZero(); H_T_H.setZero(); I_STATE.setIdentity(); #endif #ifdef USE_IKFOM double epsi[ 23 ] = { 0.001 }; fill( epsi, epsi + 23, 0.001 ); kf.init_dyn_share( get_f, df_dx, df_dw, h_share_model, NUM_MAX_ITERATIONS, epsi ); #endif /*** debug record ***/ FILE * fp; string pos_log_dir = m_root_dir + "/Log/pos_log.txt"; fp = fopen( pos_log_dir.c_str(), "w" ); m_fout_img_pos.open( string( string( ROOT_DIR ) + "PCD/img_pos.json" ), ios::out ); m_fout_pcd_pos.open( string( string( ROOT_DIR ) + "PCD/scans_pos.json" ), ios::out ); m_fout_pre.open( DEBUG_FILE_DIR( "mat_pre.txt" ), ios::out ); m_fout_out.open( DEBUG_FILE_DIR( "mat_out.txt" ), ios::out ); m_fout_dbg.open( DEBUG_FILE_DIR( "dbg.txt" ), ios::out ); // if (fout_pre && fout_out) // cout << "~~~~"<<ROOT_DIR<<" file opened" << endl; // else // cout << "~~~~"<<ROOT_DIR<<" doesn't exist" << endl; #ifdef USE_ikdforest ikdforest.Set_balance_criterion_param( 0.6 ); ikdforest.Set_delete_criterion_param( 0.5 ); #endif //------------------------------------------------------------------------------------------------------ // signal( SIGINT, SigHandle ); ros::Rate rate( 5000 ); bool status = ros::ok(); while ( ( status = ros::ok() ) ) { if ( m_flg_exit ) break; ros::spinOnce(); if ( !sync_packages( m_Lidar_Measures ) ) { status = ros::ok(); // cv::waitKey(1); rate.sleep(); continue; } /*** Packaged got ***/ if ( m_flg_reset ) { ROS_WARN( "reset when rosbag play back" ); p_imu->Reset(); m_flg_reset = false; continue; } if ( !m_is_first_frame ) { m_first_lidar_time = m_Lidar_Measures.lidar_beg_time; p_imu->first_lidar_time = m_first_lidar_time; m_is_first_frame = true; cout << "FIRST LIDAR FRAME!" << endl; } // std::cout << "ScanIdx:" << frame_num << std::endl; // double t0,t1,t2,t3,t4,t5,match_start, match_time, solve_start, // solve_time, svd_time; double t0, t1, t2, t3, t4, t5, match_start, solve_start, svd_time; m_match_time = m_kdtree_search_time = m_kdtree_search_counter = m_solve_time = m_solve_const_H_time = svd_time = 0; t0 = omp_get_wtime(); g_LiDAR_frame_start_time = t0; auto t_all_begin = std::chrono::high_resolution_clock::now(); #ifdef USE_IKFOM p_imu->Process( LidarMeasures, kf, feats_undistort ); state_point = kf.get_x(); pos_lid = state_point.pos + state_point.rot * state_point.offset_T_L_I; #else p_imu->Process2( m_Lidar_Measures, state, m_feats_undistort ); // ANCHOR: Remove point that nearing 10 meter if ( 0 ) { int feats_undistort_available = 0; for ( int i = 0; i < m_feats_undistort->size(); i++ ) { // vec_3 pt_vec = vec_3( m_feats_undistort->points[ i ].x, m_feats_undistort->points[ i ].y, m_feats_undistort->points[ i ].z ); vec_3 pt_vec = vec_3( m_feats_undistort->points[ i ].x, m_feats_undistort->points[ i ].y, m_feats_undistort->points[ i ].z ); if ( pt_vec.norm() <= 10 ) { continue; } feats_undistort_available++; m_feats_undistort->points[ feats_undistort_available ] = m_feats_undistort->points[ i ]; } m_feats_undistort->points.resize( feats_undistort_available ); cout << ANSI_COLOR_BLUE_BOLD << "Number of pts = " << feats_undistort_available << ANSI_COLOR_RESET << endl; } state_propagat = state; #endif // if(p_imu) if ( m_p_pre->calib_laser ) { for ( size_t i = 0; i < m_feats_undistort->size(); i++ ) { PointType pi = m_feats_undistort->points[ i ]; double range = sqrt( pi.x * pi.x + pi.y * pi.y + pi.z * pi.z ); double calib_vertical_angle = deg2rad( 0.15 ); double vertical_angle = asin( pi.z / range ) + calib_vertical_angle; double horizon_angle = atan2( pi.y, pi.x ); pi.z = range * sin( vertical_angle ); double project_len = range * cos( vertical_angle ); pi.x = project_len * cos( horizon_angle ); pi.y = project_len * sin( horizon_angle ); m_feats_undistort->points[ i ] = pi; } } if ( m_lidar_en ) { m_euler_cur = RotMtoEuler( state.rot_end ); #ifdef USE_IKFOM // state_ikfom fout_state = kf.get_x(); fout_pre << setw( 20 ) << LidarMeasures.last_update_time - first_lidar_time << " " << euler_cur.transpose() * 57.3 << " " << state_point.pos.transpose() << " " << state_point.vel.transpose() << " " << state_point.bg.transpose() << " " << state_point.ba.transpose() << " " << state_point.grav << endl; #else m_fout_pre << setw( 20 ) << m_Lidar_Measures.last_update_time - m_first_lidar_time << " " << m_euler_cur.transpose() * 57.3 << " " << state.pos_end.transpose() << " " << state.vel_end.transpose() << " " << state.bias_g.transpose() << " " << state.bias_a.transpose() << " " << state.gravity.transpose() << endl; #endif } if ( m_feats_undistort->empty() || ( m_feats_undistort == nullptr ) ) { cout << " No point!!!" << endl; continue; } m_flg_EKF_inited = ( m_Lidar_Measures.lidar_beg_time - m_first_lidar_time ) < INIT_TIME ? false : true; if ( !m_use_new_map ) laser_map_fov_segment(); /*** downsample the feature points in a scan ***/ m_downSizeFilterSurf.setInputCloud( m_feats_undistort ); m_downSizeFilterSurf.filter( *m_feats_down_body ); // std::cout << "feats size" << m_feats_undistort->size() << ", down size: " << m_feats_down_body->size() << std::endl; m_feats_down_size = m_feats_down_body->points.size(); /*** initialize the map ***/ if ( m_use_new_map ) { if ( !m_init_map ) { m_init_map = voxel_map_init(); if ( m_is_pub_plane_map ) pubPlaneMap( m_feat_map, voxel_pub, state.pos_end ); frame_num++; continue; }; } else if ( m_ikdtree.Root_Node == nullptr ) { if ( m_feats_down_body->points.size() > 5 ) { m_ikdtree.set_downsample_param( m_filter_size_map_min ); frameBodyToWorld( m_feats_down_body, m_feats_down_world ); m_ikdtree.Build( m_feats_down_world->points ); } continue; } int featsFromMapNum = m_ikdtree.size(); // cout<<"[ LIO ]: Raw feature num: "<<feats_undistort->points.size()<<" // downsamp num "<<feats_down_size<<" Map num: "<<featsFromMapNum<<endl; // cout<<"LidarMeasures.lidar_beg_time: "<<LidarMeasures.lidar_beg_time - // 1634087477.0<<endl; /*** ICP and iterated Kalman filter update ***/ m_normvec->resize( m_feats_down_size ); m_feats_down_world->clear(); m_feats_down_world->resize( m_feats_down_size ); // vector<double> res_last(feats_down_size, 1000.0); // initial // m_res_last.resize( m_feats_down_size, 1000.0 ); m_point_selected_surf.resize( m_feats_down_size, true ); m_pointSearchInd_surf.resize( m_feats_down_size ); m_Nearest_Points.resize( m_feats_down_size ); t1 = omp_get_wtime(); t2 = omp_get_wtime(); /*** iterated state estimation ***/ #ifdef MP_EN // cout<<"Using multi-processor, used core number: "<<MP_PROC_NUM<<endl; #endif double t_update_start = omp_get_wtime(); #ifdef USE_IKFOM double solve_H_time = 0; kf.update_iterated_dyn_share_modified( LASER_POINT_COV, solve_H_time ); // state_ikfom updated_state = kf.get_x(); state_point = kf.get_x(); // euler_cur = RotMtoEuler(state_point.rot.toRotationMatrix()); euler_cur = SO3ToEuler( state_point.rot ); pos_lid = state_point.pos + state_point.rot * state_point.offset_T_L_I; // cout<<"position: "<<pos_lid.transpose()<<endl; geoQuat.x = state_point.rot.coeffs()[ 0 ]; geoQuat.y = state_point.rot.coeffs()[ 1 ]; geoQuat.z = state_point.rot.coeffs()[ 2 ]; geoQuat.w = state_point.rot.coeffs()[ 3 ]; #else if ( m_lidar_en ) { lio_state_estimation( state_propagat ); } #endif double t_update_end = omp_get_wtime(); /******* Publish odometry *******/ m_euler_cur = RotMtoEuler( state.rot_end ); m_geo_Quat = tf::createQuaternionMsgFromRollPitchYaw( m_euler_cur( 0 ), m_euler_cur( 1 ), m_euler_cur( 2 ) ); publish_odometry( pubOdomAftMapped ); kitti_log( fp_kitti ); /*** add the feature points to map kdtree ***/ t3 = omp_get_wtime(); // cout << "Frame time consumption:" << (t3 - t0)*1000.0 << " ms" << endl; if ( m_lidar_en ) map_incremental_grow(); if ( m_is_pub_plane_map ) pubPlaneMap( m_feat_map, voxel_pub, state.pos_end ); auto t_all_end = std::chrono::high_resolution_clock::now(); auto all_time = std::chrono::duration_cast< std::chrono::duration< double > >( t_all_end - t_all_begin ).count() * 1000; // std::cout << "[Time]: all time:" << all_time << " ms" << std::endl; t5 = omp_get_wtime(); m_kdtree_incremental_time = t5 - t3 + m_readd_time; /******* Publish points *******/ PointCloudXYZI::Ptr laserCloudFullRes( m_dense_map_en ? m_feats_undistort : m_feats_down_body ); int size = laserCloudFullRes->points.size(); PointCloudXYZI::Ptr laserCloudWorld( new PointCloudXYZI( size, 1 ) ); // for ( int i = 0; i < size; i++ ) // { // RGBpointBodyToWorld( &laserCloudFullRes->points[ i ], &laserCloudWorld->points[ i ] ); // } // *m_pcl_wait_pub = *laserCloudWorld; publish_frame_world( pubLaserCloudFullRes, m_pub_point_skip ); if ( m_effect_point_pub ) publish_effect_world( pubLaserCloudEffect ); if ( m_use_new_map ) publish_voxel_point( pubLaserCloudVoxel, m_pcl_wait_pub ); // publish_map(pubLaserCloudMap); publish_path( pubPath ); // #ifdef DEPLOY publish_mavros( mavros_pose_publisher ); // #endif /*** Debug variables ***/ frame_num++; aver_time_consu = aver_time_consu * ( frame_num - 1 ) / frame_num + ( t5 - t0 ) / frame_num; aver_time_icp = aver_time_icp * ( frame_num - 1 ) / frame_num + ( t_update_end - t_update_start ) / frame_num; aver_time_match = aver_time_match * ( frame_num - 1 ) / frame_num + ( m_match_time ) / frame_num; #ifdef USE_IKFOM aver_time_solve = aver_time_solve * ( frame_num - 1 ) / frame_num + ( solve_time + solve_H_time ) / frame_num; aver_time_const_H_time = aver_time_const_H_time * ( frame_num - 1 ) / frame_num + solve_time / frame_num; #else aver_time_solve = aver_time_solve * ( frame_num - 1 ) / frame_num + ( m_solve_time ) / frame_num; aver_time_const_H_time = aver_time_const_H_time * ( frame_num - 1 ) / frame_num + m_solve_const_H_time / frame_num; // cout << "construct H:" << aver_time_const_H_time << std::endl; #endif // aver_time_consu = aver_time_consu * 0.9 + (t5 - t0) * 0.1; m_T1[ m_time_log_counter ] = m_Lidar_Measures.lidar_beg_time; m_s_plot[ m_time_log_counter ] = aver_time_consu; m_s_plot2[ m_time_log_counter ] = m_kdtree_incremental_time; m_s_plot3[ m_time_log_counter ] = m_kdtree_search_time / m_kdtree_search_counter; m_s_plot4[ m_time_log_counter ] = featsFromMapNum; m_s_plot5[ m_time_log_counter ] = t5 - t0; m_time_log_counter++; // printf( "[ mapping ]: time: fov_check %0.6f fov_check and readd: %0.6f " // "match: %0.6f solve: %0.6f ICP: %0.6f map incre: %0.6f total: " // "%0.6f icp: %0.6f construct H: %0.6f \n", // m_fov_check_time, t1 - t0, aver_time_match, aver_time_solve, t3 - t1, t5 - t3, aver_time_consu, aver_time_icp, // aver_time_const_H_time ); if ( m_lidar_en ) { m_euler_cur = RotMtoEuler( state.rot_end ); // #ifdef USE_IKFOM // fout_out << setw( 20 ) << LidarMeasures.last_update_time - first_lidar_time << " " << euler_cur.transpose() * 57.3 << " " // << state_point.pos.transpose() << " " << state_point.vel.transpose() << " " << state_point.bg.transpose() << " " // << state_point.ba.transpose() << " " << state_point.grav << " " << feats_undistort->points.size() << endl; // #else // m_fout_out << setw( 20 ) << m_Lidar_Measures.last_update_time - m_first_lidar_time << " " << m_euler_cur.transpose() * 57.3 // << " " // << state.pos_end.transpose() << " " << state.vel_end.transpose() << " " << state.bias_g.transpose() << " " // << state.bias_a.transpose() << " " << state.gravity.transpose() << " " << m_feats_undistort->points.size() << // endl; // #endif } } // #endif return 0; }
C++
3D
hku-mars/ImMesh
src/ImMesh_mesh_reconstruction.cpp
.cpp
19,762
445
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "voxel_mapping.hpp" #include "meshing/mesh_rec_display.hpp" #include "meshing/mesh_rec_geometry.hpp" #include "tools/tools_thread_pool.hpp" extern Global_map g_map_rgb_pts_mesh; extern Triangle_manager g_triangles_manager; extern int g_current_frame; extern double minimum_pts; extern double g_meshing_voxel_size; extern FILE * g_fp_cost_time; extern FILE * g_fp_lio_state; extern bool g_flag_pause; extern const int number_of_frame; extern int appending_pts_frame; extern LiDAR_frame_pts_and_pose_vec g_eigen_vec_vec; int g_maximum_thread_for_rec_mesh; std::mutex g_mutex_append_map; std::mutex g_mutex_reconstruct_mesh; extern double g_LiDAR_frame_start_time; double g_vx_map_frame_cost_time; static double g_LiDAR_frame_avg_time; struct Rec_mesh_data_package { pcl::PointCloud< pcl::PointXYZI >::Ptr m_frame_pts; Eigen::Quaterniond m_pose_q; Eigen::Vector3d m_pose_t; int m_frame_idx; Rec_mesh_data_package( pcl::PointCloud< pcl::PointXYZI >::Ptr frame_pts, Eigen::Quaterniond pose_q, Eigen::Vector3d pose_t, int frame_idx ) { m_frame_pts = frame_pts; m_pose_q = pose_q; m_pose_t = pose_t; m_frame_idx = frame_idx; } }; std::mutex g_mutex_data_package_lock; std::list< Rec_mesh_data_package > g_rec_mesh_data_package_list; std::shared_ptr< Common_tools::ThreadPool > g_thread_pool_rec_mesh = nullptr; extern int g_enable_mesh_rec; extern int g_save_to_offline_bin; LiDAR_frame_pts_and_pose_vec g_ponintcloud_pose_vec; void incremental_mesh_reconstruction( pcl::PointCloud< pcl::PointXYZI >::Ptr frame_pts, Eigen::Quaterniond pose_q, Eigen::Vector3d pose_t, int frame_idx ) { while ( g_flag_pause ) { std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); } Eigen::Matrix< double, 7, 1 > pose_vec; pose_vec.head< 4 >() = pose_q.coeffs().transpose(); pose_vec.block( 4, 0, 3, 1 ) = pose_t; for ( int i = 0; i < frame_pts->points.size(); i++ ) { g_eigen_vec_vec[ frame_idx ].first.emplace_back( frame_pts->points[ i ].x, frame_pts->points[ i ].y, frame_pts->points[ i ].z, frame_pts->points[ i ].intensity ); } g_eigen_vec_vec[ frame_idx ].second = pose_vec; // g_eigen_vec_vec.push_back( std::make_pair( empty_vec, pose_vec ) ); // TODO : add time tic toc int append_point_step = std::max( ( int ) 1, ( int ) std::round( frame_pts->points.size() / appending_pts_frame ) ); Common_tools::Timer tim, tim_total; g_mutex_append_map.lock(); g_map_rgb_pts_mesh.append_points_to_global_map( *frame_pts, frame_idx, nullptr, append_point_step ); std::unordered_set< std::shared_ptr< RGB_Voxel > > voxels_recent_visited = g_map_rgb_pts_mesh.m_voxels_recent_visited; g_mutex_append_map.unlock(); std::atomic< int > voxel_idx( 0 ); std::mutex mtx_triangle_lock, mtx_single_thr; typedef std::unordered_set< std::shared_ptr< RGB_Voxel > >::iterator set_voxel_it; std::unordered_map< std::shared_ptr< RGB_Voxel >, Triangle_set > removed_triangle_list; std::unordered_map< std::shared_ptr< RGB_Voxel >, Triangle_set > added_triangle_list; g_mutex_reconstruct_mesh.lock(); tim.tic(); tim_total.tic(); try { tbb::parallel_for_each( voxels_recent_visited.begin(), voxels_recent_visited.end(), [ & ]( const std::shared_ptr< RGB_Voxel > &voxel ) { // std::unique_lock<std::mutex> thr_lock(mtx_single_thr); // printf_line; if ( ( voxel->m_meshing_times >= 1 ) || ( voxel->m_new_added_pts_count < 0 ) ) { return; } Common_tools::Timer tim_lock; tim_lock.tic(); voxel->m_meshing_times++; voxel->m_new_added_pts_count = 0; vec_3 pos_1 = vec_3( voxel->m_pos[ 0 ], voxel->m_pos[ 1 ], voxel->m_pos[ 2 ] ); // printf("Voxels [%d], (%d, %d, %d) ", count, pos_1(0), pos_1(1), pos_1(2) ); std::unordered_set< std::shared_ptr< RGB_Voxel > > neighbor_voxels; neighbor_voxels.insert( voxel ); g_mutex_append_map.lock(); std::vector< RGB_pt_ptr > pts_in_voxels = retrieve_pts_in_voxels( neighbor_voxels ); if ( pts_in_voxels.size() < 3 ) { g_mutex_append_map.unlock(); return; } g_mutex_append_map.unlock(); // Voxel-wise mesh pull pts_in_voxels = retrieve_neighbor_pts_kdtree( pts_in_voxels ); pts_in_voxels = remove_outlier_pts( pts_in_voxels, voxel ); std::set< long > relative_point_indices; for ( RGB_pt_ptr tri_ptr : pts_in_voxels ) { relative_point_indices.insert( tri_ptr->m_pt_index ); } int iter_count = 0; g_triangles_manager.m_enable_map_edge_triangle = 0; pts_in_voxels.clear(); for ( auto p : relative_point_indices ) { pts_in_voxels.push_back( g_map_rgb_pts_mesh.m_rgb_pts_vec[ p ] ); } std::set< long > convex_hull_index, inner_pts_index; // mtx_triangle_lock.lock(); voxel->m_short_axis.setZero(); std::vector< long > add_triangle_idx = delaunay_triangulation( pts_in_voxels, voxel->m_long_axis, voxel->m_mid_axis, voxel->m_short_axis, convex_hull_index, inner_pts_index ); for ( auto p : inner_pts_index ) { if ( voxel->if_pts_belong_to_this_voxel( g_map_rgb_pts_mesh.m_rgb_pts_vec[ p ] ) ) { g_map_rgb_pts_mesh.m_rgb_pts_vec[ p ]->m_is_inner_pt = true; g_map_rgb_pts_mesh.m_rgb_pts_vec[ p ]->m_parent_voxel = voxel; } } for ( auto p : convex_hull_index ) { g_map_rgb_pts_mesh.m_rgb_pts_vec[ p ]->m_is_inner_pt = false; g_map_rgb_pts_mesh.m_rgb_pts_vec[ p ]->m_parent_voxel = voxel; } Triangle_set triangles_sets = g_triangles_manager.find_relative_triangulation_combination( relative_point_indices ); Triangle_set triangles_to_remove, triangles_to_add, existing_triangle; // Voxel-wise mesh commit triangle_compare( triangles_sets, add_triangle_idx, triangles_to_remove, triangles_to_add, &existing_triangle ); // Refine normal index for ( auto triangle_ptr : triangles_to_add ) { correct_triangle_index( triangle_ptr, g_eigen_vec_vec[ frame_idx ].second.block( 4, 0, 3, 1 ), voxel->m_short_axis ); } for ( auto triangle_ptr : existing_triangle ) { correct_triangle_index( triangle_ptr, g_eigen_vec_vec[ frame_idx ].second.block( 4, 0, 3, 1 ), voxel->m_short_axis ); } std::unique_lock< std::mutex > lock( mtx_triangle_lock ); removed_triangle_list.emplace( std::make_pair( voxel, triangles_to_remove ) ); added_triangle_list.emplace( std::make_pair( voxel, triangles_to_add ) ); voxel_idx++; } ); } catch ( ... ) { for ( int i = 0; i < 100; i++ ) { cout << ANSI_COLOR_RED_BOLD << "Exception in tbb parallels..." << ANSI_COLOR_RESET << endl; } return; } double mul_thr_cost_time = tim.toc( " ", 0 ); Common_tools::Timer tim_triangle_cost; int total_delete_triangle = 0, total_add_triangle = 0; // Voxel-wise mesh push for ( auto &triangles_set : removed_triangle_list ) { total_delete_triangle += triangles_set.second.size(); g_triangles_manager.remove_triangle_list( triangles_set.second ); } for ( auto &triangle_list : added_triangle_list ) { Triangle_set triangle_idx = triangle_list.second; total_add_triangle += triangle_idx.size(); for ( auto triangle_ptr : triangle_idx ) { Triangle_ptr tri_ptr = g_triangles_manager.insert_triangle( triangle_ptr->m_tri_pts_id[ 0 ], triangle_ptr->m_tri_pts_id[ 1 ], triangle_ptr->m_tri_pts_id[ 2 ], 1 ); tri_ptr->m_index_flip = triangle_ptr->m_index_flip; } } g_mutex_reconstruct_mesh.unlock(); if ( g_fp_cost_time ) { if ( frame_idx > 0 ) g_LiDAR_frame_avg_time = g_LiDAR_frame_avg_time * ( frame_idx - 1 ) / frame_idx + ( g_vx_map_frame_cost_time ) / frame_idx; fprintf( g_fp_cost_time, "%d %lf %d %lf %lf\r\n", frame_idx, tim.toc( " ", 0 ), ( int ) voxel_idx.load(), g_vx_map_frame_cost_time, g_LiDAR_frame_avg_time ); fflush( g_fp_cost_time ); } if ( g_current_frame < frame_idx ) { g_current_frame = frame_idx; } else { if ( g_eigen_vec_vec[ g_current_frame + 1 ].second.size() > 7 ) { g_current_frame++; } } } void service_reconstruct_mesh() { if ( g_thread_pool_rec_mesh == nullptr ) { g_thread_pool_rec_mesh = std::make_shared< Common_tools::ThreadPool >( g_maximum_thread_for_rec_mesh ); } int drop_frame_num = 0; while ( 1 ) { while ( g_rec_mesh_data_package_list.size() == 0 ) { std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) ); } g_mutex_data_package_lock.lock(); while ( g_rec_mesh_data_package_list.size() > 1e5 ) { cout << "Drop mesh frame [" << g_rec_mesh_data_package_list.front().m_frame_idx; printf( "], total_drop = %d, all_frame = %d\r\n", drop_frame_num++, g_rec_mesh_data_package_list.front().m_frame_idx ); g_rec_mesh_data_package_list.pop_front(); } if ( g_rec_mesh_data_package_list.size() > 10 ) { cout << "Poor real-time performance, current buffer size = " << g_rec_mesh_data_package_list.size() << endl; } Rec_mesh_data_package data_pack_front = g_rec_mesh_data_package_list.front(); g_rec_mesh_data_package_list.pop_front(); g_mutex_data_package_lock.unlock(); // ANCHOR - Comment follow line to disable meshing if ( g_enable_mesh_rec ) { g_thread_pool_rec_mesh->commit_task( incremental_mesh_reconstruction, data_pack_front.m_frame_pts, data_pack_front.m_pose_q, data_pack_front.m_pose_t, data_pack_front.m_frame_idx ); } std::this_thread::sleep_for( std::chrono::microseconds( 10 ) ); } } extern bool g_flag_pause; int g_frame_idx = 0; std::thread *g_rec_mesh_thr = nullptr; void start_mesh_threads( int maximum_threads = 20 ) { if ( g_eigen_vec_vec.size() <= 0 ) { g_eigen_vec_vec.resize( 1e6 ); } if ( g_rec_mesh_thr == nullptr ) { g_maximum_thread_for_rec_mesh = maximum_threads; g_rec_mesh_thr = new std::thread( service_reconstruct_mesh ); } } void reconstruct_mesh_from_pointcloud( pcl::PointCloud< pcl::PointXYZI >::Ptr frame_pts, double minimum_pts_distance ) { start_mesh_threads(); cout << "=== reconstruct_mesh_from_pointcloud ===" << endl; cout << "Input pointcloud have " << frame_pts->points.size() << " points." << endl; pcl::PointCloud< pcl::PointXYZI >::Ptr all_cloud_ds( new pcl::PointCloud< pcl::PointXYZI > ); pcl::VoxelGrid< pcl::PointXYZI > sor; sor.setInputCloud( frame_pts ); sor.setLeafSize( minimum_pts_distance, minimum_pts_distance, minimum_pts_distance ); sor.filter( *all_cloud_ds ); cout << ANSI_COLOR_BLUE_BOLD << "Raw points number = " << frame_pts->points.size() << ", downsampled points number = " << all_cloud_ds->points.size() << ANSI_COLOR_RESET << endl; g_mutex_data_package_lock.lock(); g_rec_mesh_data_package_list.emplace_back( all_cloud_ds, Eigen::Quaterniond::Identity(), vec_3::Zero(), 0 ); g_mutex_data_package_lock.unlock(); } void open_log_file() { if ( g_fp_cost_time == nullptr || g_fp_lio_state == nullptr ) { Common_tools::create_dir( std::string( Common_tools::get_home_folder() ).append( "/ImMesh_output" ).c_str() ); std::string cost_time_log_name = std::string( Common_tools::get_home_folder() ).append( "/ImMesh_output/mesh_cost_time.log" ); std::string lio_state_log_name = std::string( Common_tools::get_home_folder() ).append( "/ImMesh_output/lio_state.log" ); // cout << ANSI_COLOR_BLUE_BOLD ; // cout << "Record cost time to log file:" << cost_time_log_name << endl; // cout << "Record LIO state to log file:" << cost_time_log_name << endl; // cout << ANSI_COLOR_RESET; g_fp_cost_time = fopen( cost_time_log_name.c_str(), "w+" ); g_fp_lio_state = fopen( lio_state_log_name.c_str(), "w+" ); } } std::vector< vec_4 > convert_pcl_pointcloud_to_vec( pcl::PointCloud< pcl::PointXYZI > &pointcloud ) { int pt_size = pointcloud.points.size(); std::vector< vec_4 > eigen_pt_vec( pt_size ); for ( int i = 0; i < pt_size; i++ ) { eigen_pt_vec[ i ]( 0 ) = pointcloud.points[ i ].x; eigen_pt_vec[ i ]( 1 ) = pointcloud.points[ i ].y; eigen_pt_vec[ i ]( 2 ) = pointcloud.points[ i ].z; eigen_pt_vec[ i ]( 3 ) = pointcloud.points[ i ].intensity; } return eigen_pt_vec; } void Voxel_mapping::map_incremental_grow() { start_mesh_threads( m_meshing_maximum_thread_for_rec_mesh ); if ( m_use_new_map ) { while ( g_flag_pause ) { std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); } // startTime = clock(); pcl::PointCloud< pcl::PointXYZI >::Ptr world_lidar( new pcl::PointCloud< pcl::PointXYZI > ); pcl::PointCloud< pcl::PointXYZI >::Ptr world_lidar_full( new pcl::PointCloud< pcl::PointXYZI > ); std::vector< Point_with_var > pv_list; // TODO: saving pointcloud to file // pcl::io::savePCDFileBinary(Common_tools::get_home_folder().append("/r3live_output/").append("last_frame.pcd").c_str(), *m_feats_down_body); transformLidar( state.rot_end, state.pos_end, m_feats_down_body, world_lidar ); for ( size_t i = 0; i < world_lidar->size(); i++ ) { Point_with_var pv; pv.m_point << world_lidar->points[ i ].x, world_lidar->points[ i ].y, world_lidar->points[ i ].z; M3D point_crossmat = m_cross_mat_list[ i ]; M3D var = m_body_cov_list[ i ]; var = ( state.rot_end * m_extR ) * var * ( state.rot_end * m_extR ).transpose() + ( -point_crossmat ) * state.cov.block< 3, 3 >( 0, 0 ) * ( -point_crossmat ).transpose() + state.cov.block< 3, 3 >( 3, 3 ); pv.m_var = var; pv_list.push_back( pv ); } // pcl::PointCloud< pcl::PointXYZI >::Ptr world_lidar( new pcl::PointCloud< pcl::PointXYZI > ); std::sort( pv_list.begin(), pv_list.end(), var_contrast ); updateVoxelMap( pv_list, m_max_voxel_size, m_max_layer, m_layer_init_size, m_max_points_size, m_min_eigen_value, m_feat_map ); double vx_map_cost_time = omp_get_wtime(); g_vx_map_frame_cost_time = ( vx_map_cost_time - g_LiDAR_frame_start_time ) * 1000.0; // cout << "vx_map_cost_time = " << g_vx_map_frame_cost_time << " ms" << endl; transformLidar( state.rot_end, state.pos_end, m_feats_undistort, world_lidar_full ); g_mutex_data_package_lock.lock(); g_rec_mesh_data_package_list.emplace_back( world_lidar_full, Eigen::Quaterniond( state.rot_end ), state.pos_end, g_frame_idx ); g_mutex_data_package_lock.unlock(); open_log_file(); if ( g_fp_lio_state != nullptr ) { dump_lio_state_to_log( g_fp_lio_state ); } g_frame_idx++; } if ( !m_use_new_map ) { for ( int i = 0; i < m_feats_down_size; i++ ) { /* transform to world frame */ pointBodyToWorld( m_feats_down_body->points[ i ], m_feats_down_world->points[ i ] ); } // add_to_offline_bin( state, m_Lidar_Measures.lidar_beg_time, m_feats_down_world ); #ifdef USE_ikdtree #ifdef USE_ikdforest ikdforest.Add_Points( feats_down_world->points, lidar_end_time ); #else m_ikdtree.Add_Points( m_feats_down_world->points, true ); #endif #endif } }
C++
3D
hku-mars/ImMesh
src/preprocess.cpp
.cpp
46,590
1,375
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "preprocess.h" #define RETURN0 0x00 #define RETURN0AND1 0x10 Preprocess::Preprocess() : feature_enabled( 0 ), lidar_type( AVIA ), blind( 0.01 ), point_filter_num( 1 ) { inf_bound = 10; N_SCANS = 6; group_size = 8; disA = 0.01; disA = 0.1; // B? p2l_ratio = 225; limit_maxmid = 6.25; limit_midmin = 6.25; limit_maxmin = 3.24; jump_up_limit = 170.0; jump_down_limit = 8.0; cos160 = 160.0; edgea = 2; edgeb = 0.1; smallp_intersect = 172.5; smallp_ratio = 1.2; given_offset_time = false; jump_up_limit = cos( jump_up_limit / 180 * M_PI ); jump_down_limit = cos( jump_down_limit / 180 * M_PI ); cos160 = cos( cos160 / 180 * M_PI ); smallp_intersect = cos( smallp_intersect / 180 * M_PI ); } Preprocess::~Preprocess() {} void Preprocess::set( bool feat_en, int lid_type, double bld, int pfilt_num ) { feature_enabled = feat_en; lidar_type = lid_type; blind = bld; point_filter_num = pfilt_num; } void Preprocess::process( const livox_ros_driver::CustomMsg::ConstPtr &msg, PointCloudXYZI::Ptr &pcl_out ) { avia_handler( msg ); *pcl_out = pl_surf; } void Preprocess::process( const sensor_msgs::PointCloud2::ConstPtr &msg, PointCloudXYZI::Ptr &pcl_out ) { switch ( time_unit ) { case SEC: time_unit_scale = 1.e3f; break; case MS: time_unit_scale = 1.f; break; case US: time_unit_scale = 1.e-3f; break; case NS: time_unit_scale = 1.e-6f; break; default: time_unit_scale = 1.f; break; } switch ( lidar_type ) { case OUST64: oust64_handler( msg ); break; case VELO16: velodyne_handler( msg ); break; case L515: l515_handler( msg ); break; case XT32: xt32_handler( msg ); break; case VELO32: velodyne32_handler( msg ); break; default: printf( "Error LiDAR Type: %d \n", lidar_type ); break; } *pcl_out = pl_surf; } void Preprocess::avia_handler( const livox_ros_driver::CustomMsg::ConstPtr &msg ) { pl_surf.clear(); pl_corn.clear(); pl_full.clear(); double t1 = omp_get_wtime(); int plsize = msg->point_num; // cout<<"plsie: "<<plsize<<endl; pl_corn.reserve( plsize ); pl_surf.reserve( plsize ); pl_full.resize( plsize ); for ( int i = 0; i < N_SCANS; i++ ) { pl_buff[ i ].clear(); pl_buff[ i ].reserve( plsize ); } uint valid_num = 0; if ( feature_enabled ) { for ( uint i = 1; i < plsize; i++ ) { if ( ( msg->points[ i ].line < N_SCANS ) && ( ( msg->points[ i ].tag & 0x30 ) == 0x10 ) ) { pl_full[ i ].x = msg->points[ i ].x; pl_full[ i ].y = msg->points[ i ].y; pl_full[ i ].z = msg->points[ i ].z; pl_full[ i ].intensity = msg->points[ i ].reflectivity; pl_full[ i ].curvature = msg->points[ i ].offset_time / float( 1000000 ); // use curvature as time of each laser points bool is_new = false; if ( ( abs( pl_full[ i ].x - pl_full[ i - 1 ].x ) > 1e-7 ) || ( abs( pl_full[ i ].y - pl_full[ i - 1 ].y ) > 1e-7 ) || ( abs( pl_full[ i ].z - pl_full[ i - 1 ].z ) > 1e-7 ) ) { pl_buff[ msg->points[ i ].line ].push_back( pl_full[ i ] ); } } } static int count = 0; static double time = 0.0; count++; double t0 = omp_get_wtime(); for ( int j = 0; j < N_SCANS; j++ ) { if ( pl_buff[ j ].size() <= 5 ) continue; pcl::PointCloud< PointType > &pl = pl_buff[ j ]; plsize = pl.size(); vector< orgtype > &types = typess[ j ]; types.clear(); types.resize( plsize ); plsize--; for ( uint i = 0; i < plsize; i++ ) { types[ i ].range = pl[ i ].x * pl[ i ].x + pl[ i ].y * pl[ i ].y; vx = pl[ i ].x - pl[ i + 1 ].x; vy = pl[ i ].y - pl[ i + 1 ].y; vz = pl[ i ].z - pl[ i + 1 ].z; types[ i ].dista = vx * vx + vy * vy + vz * vz; } types[ plsize ].range = pl[ plsize ].x * pl[ plsize ].x + pl[ plsize ].y * pl[ plsize ].y; give_feature( pl, types ); // pl_surf += pl; } time += omp_get_wtime() - t0; printf( "Feature extraction time: %lf \n", time / count ); } else { for ( uint i = 1; i < plsize; i++ ) { if ( ( msg->points[ i ].line < N_SCANS ) ) // && ((msg->points[i].tag & 0x30) == 0x10)) { valid_num++; if ( valid_num % point_filter_num == 0 ) { pl_full[ i ].x = msg->points[ i ].x; pl_full[ i ].y = msg->points[ i ].y; pl_full[ i ].z = msg->points[ i ].z; pl_full[ i ].intensity = msg->points[ i ].reflectivity; pl_full[ i ].curvature = msg->points[ i ].offset_time / float( 1000000 ); // use curvature as time of each laser points if ( ( pl_full[ i ].intensity > 4 ) && ( pl_full[ i ].x * pl_full[ i ].x + pl_full[ i ].y * pl_full[ i ].y + pl_full[ i ].z * pl_full[ i ].z > blind_sqr ) ) { pl_surf.push_back( pl_full[ i ] ); } } } } } } void Preprocess::l515_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ) { pl_surf.clear(); pl_corn.clear(); pl_full.clear(); pcl::PointCloud< pcl::PointXYZRGB > pl_orig; pcl::fromROSMsg( *msg, pl_orig ); int plsize = pl_orig.size(); pl_corn.reserve( plsize ); pl_surf.reserve( plsize ); double time_stamp = msg->header.stamp.toSec(); // cout << "===================================" << endl; // printf("Pt size = %d, N_SCANS = %d\r\n", plsize, N_SCANS); for ( int i = 0; i < pl_orig.points.size(); i++ ) { if ( i % point_filter_num != 0 ) continue; double range = pl_orig.points[ i ].x * pl_orig.points[ i ].x + pl_orig.points[ i ].y * pl_orig.points[ i ].y + pl_orig.points[ i ].z * pl_orig.points[ i ].z; if ( range < blind_sqr ) continue; Eigen::Vector3d pt_vec; PointType added_pt; added_pt.x = pl_orig.points[ i ].x; added_pt.y = pl_orig.points[ i ].y; added_pt.z = pl_orig.points[ i ].z; added_pt.normal_x = pl_orig.points[ i ].r; added_pt.normal_y = pl_orig.points[ i ].g; added_pt.normal_z = pl_orig.points[ i ].b; added_pt.curvature = 0.0; pl_surf.points.push_back( added_pt ); } cout << "pl size:: " << pl_orig.points.size() << endl; // pub_func(pl_surf, pub_full, msg->header.stamp); // pub_func(pl_surf, pub_corn, msg->header.stamp); } void Preprocess::oust64_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ) { pl_surf.clear(); pl_corn.clear(); pl_full.clear(); pcl::PointCloud< ouster_ros::Point > pl_orig; pcl::fromROSMsg( *msg, pl_orig ); int plsize = pl_orig.size(); pl_corn.reserve( plsize ); pl_surf.reserve( plsize ); if ( feature_enabled ) { for ( int i = 0; i < N_SCANS; i++ ) { pl_buff[ i ].clear(); pl_buff[ i ].reserve( plsize ); } for ( uint i = 0; i < plsize; i++ ) { double range = pl_orig.points[ i ].x * pl_orig.points[ i ].x + pl_orig.points[ i ].y * pl_orig.points[ i ].y + pl_orig.points[ i ].z * pl_orig.points[ i ].z; if ( range < ( blind * blind ) ) continue; Eigen::Vector3d pt_vec; PointType added_pt; added_pt.x = pl_orig.points[ i ].x; added_pt.y = pl_orig.points[ i ].y; added_pt.z = pl_orig.points[ i ].z; added_pt.intensity = pl_orig.points[ i ].intensity; added_pt.normal_x = 0; added_pt.normal_y = 0; added_pt.normal_z = 0; double yaw_angle = atan2( added_pt.y, added_pt.x ) * 57.3; if ( yaw_angle >= 180.0 ) yaw_angle -= 360.0; if ( yaw_angle <= -180.0 ) yaw_angle += 360.0; // printf("Time scale = %f\r\n", (float )time_unit_scale); added_pt.curvature = pl_orig.points[ i ].t * time_unit_scale; if ( pl_orig.points[ i ].ring < N_SCANS ) { pl_buff[ pl_orig.points[ i ].ring ].push_back( added_pt ); } } for ( int j = 0; j < N_SCANS; j++ ) { PointCloudXYZI & pl = pl_buff[ j ]; int linesize = pl.size(); vector< orgtype > &types = typess[ j ]; types.clear(); types.resize( linesize ); linesize--; for ( uint i = 0; i < linesize; i++ ) { types[ i ].range = sqrt( pl[ i ].x * pl[ i ].x + pl[ i ].y * pl[ i ].y ); vx = pl[ i ].x - pl[ i + 1 ].x; vy = pl[ i ].y - pl[ i + 1 ].y; vz = pl[ i ].z - pl[ i + 1 ].z; types[ i ].dista = vx * vx + vy * vy + vz * vz; } types[ linesize ].range = sqrt( pl[ linesize ].x * pl[ linesize ].x + pl[ linesize ].y * pl[ linesize ].y ); give_feature( pl, types ); } } else { double time_stamp = msg->header.stamp.toSec(); // cout << "===================================" << endl; // printf( "Pt size = %d, N_SCANS = %d\r\n", plsize, N_SCANS ); for ( int i = 0; i < pl_orig.points.size(); i++ ) { if ( i % point_filter_num != 0 ) continue; double range = pl_orig.points[ i ].x * pl_orig.points[ i ].x + pl_orig.points[ i ].y * pl_orig.points[ i ].y + pl_orig.points[ i ].z * pl_orig.points[ i ].z; if ( range < ( blind * blind ) ) continue; Eigen::Vector3d pt_vec; PointType added_pt; added_pt.x = pl_orig.points[ i ].x; added_pt.y = pl_orig.points[ i ].y; added_pt.z = pl_orig.points[ i ].z; if ( 1 ) // ANCHOR: remove nearby points { pt_vec = Eigen::Vector3d( added_pt.x, added_pt.y, added_pt.z * 0 ); if ( pt_vec.norm() < 0.5 ) { continue; } } added_pt.intensity = pl_orig.points[ i ].intensity; added_pt.normal_x = 0; added_pt.normal_y = 0; added_pt.normal_z = 0; added_pt.curvature = pl_orig.points[ i ].t * time_unit_scale; // curvature unit: ms pl_surf.points.push_back( added_pt ); } } // std::cout << "feat size:" << pl_surf.points.size() << std::endl; // pub_func(pl_surf, pub_full, msg->header.stamp); // pub_func(pl_surf, pub_corn, msg->header.stamp); } // void Preprocess::oust64_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ) // { // std::cout << "get ouster" << std::endl; // pl_surf.clear(); // pl_corn.clear(); // pl_full.clear(); // pcl::PointCloud< ouster_ros::Point > pl_orig; // pcl::fromROSMsg( *msg, pl_orig ); // int plsize = pl_orig.size(); // pl_corn.reserve( plsize ); // pl_surf.reserve( plsize ); // if ( feature_enabled ) // { // for ( int i = 0; i < N_SCANS; i++ ) // { // pl_buff[ i ].clear(); // pl_buff[ i ].reserve( plsize ); // } // for ( uint i = 0; i < plsize; i++ ) // { // double range = pl_orig.points[ i ].x * pl_orig.points[ i ].x + pl_orig.points[ i ].y * pl_orig.points[ i ].y + // pl_orig.points[ i ].z * pl_orig.points[ i ].z; // if ( range < blind_sqr ) // continue; // Eigen::Vector3d pt_vec; // PointType added_pt; // added_pt.x = pl_orig.points[ i ].x; // added_pt.y = pl_orig.points[ i ].y; // added_pt.z = pl_orig.points[ i ].z; // added_pt.intensity = pl_orig.points[ i ].intensity; // added_pt.normal_x = 0; // added_pt.normal_y = 0; // added_pt.normal_z = 0; // double yaw_angle = atan2( added_pt.y, added_pt.x ) * 57.3; // if ( yaw_angle >= 180.0 ) // yaw_angle -= 360.0; // if ( yaw_angle <= -180.0 ) // yaw_angle += 360.0; // added_pt.curvature = pl_orig.points[ i ].t * time_unit_scale; // if ( pl_orig.points[ i ].ring < N_SCANS ) // { // pl_buff[ pl_orig.points[ i ].ring ].push_back( added_pt ); // } // } // for ( int j = 0; j < N_SCANS; j++ ) // { // PointCloudXYZI & pl = pl_buff[ j ]; // int linesize = pl.size(); // vector< orgtype > &types = typess[ j ]; // types.clear(); // types.resize( linesize ); // linesize--; // for ( uint i = 0; i < linesize; i++ ) // { // types[ i ].range = sqrt( pl[ i ].x * pl[ i ].x + pl[ i ].y * pl[ i ].y ); // vx = pl[ i ].x - pl[ i + 1 ].x; // vy = pl[ i ].y - pl[ i + 1 ].y; // vz = pl[ i ].z - pl[ i + 1 ].z; // types[ i ].dista = vx * vx + vy * vy + vz * vz; // } // types[ linesize ].range = sqrt( pl[ linesize ].x * pl[ linesize ].x + pl[ linesize ].y * pl[ linesize ].y ); // give_feature( pl, types ); // } // } // else // { // double time_stamp = msg->header.stamp.toSec(); // cout << "===================================" << endl; // std::cout << "time stamp unit scale:" << time_unit_scale << std::endl; // printf( "Pt size = %d, N_SCANS = %d\r\n", plsize, N_SCANS ); // for ( int i = 0; i < pl_orig.points.size(); i++ ) // { // if ( i % point_filter_num != 0 ) // continue; // double range = pl_orig.points[ i ].x * pl_orig.points[ i ].x + pl_orig.points[ i ].y * pl_orig.points[ i ].y + // pl_orig.points[ i ].z * pl_orig.points[ i ].z; // if ( range < blind_sqr ) // continue; // Eigen::Vector3d pt_vec; // PointType added_pt; // added_pt.x = pl_orig.points[ i ].x; // added_pt.y = pl_orig.points[ i ].y; // added_pt.z = pl_orig.points[ i ].z; // added_pt.intensity = pl_orig.points[ i ].intensity; // added_pt.normal_x = 0; // added_pt.normal_y = 0; // added_pt.normal_z = 0; // double yaw_angle = atan2( added_pt.y, added_pt.x ) * 57.3; // if ( yaw_angle >= 180.0 ) // yaw_angle -= 360.0; // if ( yaw_angle <= -180.0 ) // yaw_angle += 360.0; // added_pt.curvature = pl_orig.points[ i ].t * time_unit_scale; // // cout<<added_pt.curvature<<endl; // pl_surf.points.push_back( added_pt ); // } // } // // pub_func(pl_surf, pub_full, msg->header.stamp); // // pub_func(pl_surf, pub_corn, msg->header.stamp); // } #define MAX_LINE_NUM 64 void Preprocess::velodyne_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ) { pl_surf.clear(); pl_corn.clear(); pl_full.clear(); pcl::PointCloud< velodyne_ros::Point > pl_orig; pcl::fromROSMsg( *msg, pl_orig ); int plsize = pl_orig.points.size(); // pl_surf.reserve(plsize); for ( int i = 0; i < pl_orig.size(); i++ ) { PointType added_pt; added_pt.x = pl_orig.points[ i ].x; added_pt.y = pl_orig.points[ i ].y; added_pt.z = pl_orig.points[ i ].z; added_pt.intensity = pl_orig.points[ i ].intensity; float angle = atan( added_pt.z / sqrt( added_pt.x * added_pt.x + added_pt.y * added_pt.y ) ) * 180 / M_PI; int scanID = 0; if ( angle >= -8.83 ) scanID = int( ( 2 - angle ) * 3.0 + 0.5 ); else scanID = N_SCANS / 2 + int( ( -8.83 - angle ) * 2.0 + 0.5 ); // use [0 50] > 50 remove outlies if ( angle > 2 || angle < -24.33 || scanID > 50 || scanID < 0 ) { continue; } pl_surf.push_back( added_pt ); } } void Preprocess::velodyne32_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ) { pl_surf.clear(); pl_corn.clear(); pl_full.clear(); pcl::PointCloud< velodyne_ros::Point > pl_orig; pcl::fromROSMsg( *msg, pl_orig ); int plsize = pl_orig.points.size(); // pl_surf.reserve(plsize); for ( int i = 0; i < pl_orig.size(); i++ ) { PointType added_pt; added_pt.x = pl_orig.points[ i ].x; added_pt.y = pl_orig.points[ i ].y; added_pt.z = pl_orig.points[ i ].z; added_pt.intensity = pl_orig.points[ i ].intensity; added_pt.curvature = pl_orig.points[ i ].time * time_unit_scale; float angle = atan( added_pt.z / sqrt( added_pt.x * added_pt.x + added_pt.y * added_pt.y ) ) * 180 / M_PI; if ( i % point_filter_num == 0 ) { if ( added_pt.x * added_pt.x + added_pt.y * added_pt.y + added_pt.z * added_pt.z > ( blind * blind ) ) { pl_surf.points.push_back( added_pt ); } } pl_surf.push_back( added_pt ); } } // void Preprocess::velodyne_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ) // { // pl_surf.clear(); // pl_corn.clear(); // pl_full.clear(); // pcl::PointCloud< velodyne_ros::Point > pl_orig; // pcl::fromROSMsg( *msg, pl_orig ); // int plsize = pl_orig.points.size(); // pl_surf.reserve( plsize ); // bool is_first[ MAX_LINE_NUM ]; // double yaw_fp[ MAX_LINE_NUM ] = { 0 }; // yaw of first scan point // double omega_l = 3.61; // scan angular velocity // float yaw_last[ MAX_LINE_NUM ] = { 0.0 }; // yaw of last scan point // float time_last[ MAX_LINE_NUM ] = { 0.0 }; // last offset time // if ( pl_orig.points[ plsize - 1 ].time > 0 ) // { // given_offset_time = true; // } // else // { // given_offset_time = false; // memset( is_first, true, sizeof( is_first ) ); // double yaw_first = atan2( pl_orig.points[ 0 ].y, pl_orig.points[ 0 ].x ) * 57.29578; // double yaw_end = yaw_first; // int layer_first = pl_orig.points[ 0 ].ring; // for ( uint i = plsize - 1; i > 0; i-- ) // { // if ( pl_orig.points[ i ].ring == layer_first ) // { // yaw_end = atan2( pl_orig.points[ i ].y, pl_orig.points[ i ].x ) * 57.29578; // break; // } // } // } // if ( feature_enabled ) // { // for ( int i = 0; i < N_SCANS; i++ ) // { // pl_buff[ i ].clear(); // pl_buff[ i ].reserve( plsize ); // } // for ( int i = 0; i < plsize; i++ ) // { // PointType added_pt; // added_pt.normal_x = 0; // added_pt.normal_y = 0; // added_pt.normal_z = 0; // int layer = pl_orig.points[ i ].ring; // if ( layer >= N_SCANS ) // continue; // added_pt.x = pl_orig.points[ i ].x; // added_pt.y = pl_orig.points[ i ].y; // added_pt.z = pl_orig.points[ i ].z; // added_pt.intensity = pl_orig.points[ i ].intensity; // added_pt.curvature = pl_orig.points[ i ].time * time_unit_scale; // units: ms // if ( !given_offset_time ) // { // double yaw_angle = atan2( added_pt.y, added_pt.x ) * 57.2957; // if ( is_first[ layer ] ) // { // // printf("layer: %d; is first: %d", layer, is_first[layer]); // yaw_fp[ layer ] = yaw_angle; // is_first[ layer ] = false; // added_pt.curvature = 0.0; // yaw_last[ layer ] = yaw_angle; // time_last[ layer ] = added_pt.curvature; // continue; // } // if ( yaw_angle <= yaw_fp[ layer ] ) // { // added_pt.curvature = ( yaw_fp[ layer ] - yaw_angle ) / omega_l; // } // else // { // added_pt.curvature = ( yaw_fp[ layer ] - yaw_angle + 360.0 ) / omega_l; // } // if ( added_pt.curvature < time_last[ layer ] ) // added_pt.curvature += 360.0 / omega_l; // yaw_last[ layer ] = yaw_angle; // time_last[ layer ] = added_pt.curvature; // } // pl_buff[ layer ].points.push_back( added_pt ); // } // for ( int j = 0; j < N_SCANS; j++ ) // { // PointCloudXYZI &pl = pl_buff[ j ]; // int linesize = pl.size(); // if ( linesize < 2 ) // continue; // vector< orgtype > &types = typess[ j ]; // types.clear(); // types.resize( linesize ); // linesize--; // for ( uint i = 0; i < linesize; i++ ) // { // types[ i ].range = sqrt( pl[ i ].x * pl[ i ].x + pl[ i ].y * pl[ i ].y ); // vx = pl[ i ].x - pl[ i + 1 ].x; // vy = pl[ i ].y - pl[ i + 1 ].y; // vz = pl[ i ].z - pl[ i + 1 ].z; // types[ i ].dista = vx * vx + vy * vy + vz * vz; // } // types[ linesize ].range = sqrt( pl[ linesize ].x * pl[ linesize ].x + pl[ linesize ].y * pl[ linesize ].y ); // give_feature( pl, types ); // } // } // else // { // for ( int i = 0; i < plsize; i++ ) // { // PointType added_pt; // // cout<<"!!!!!!"<<i<<" "<<plsize<<endl; // added_pt.normal_x = 0; // added_pt.normal_y = 0; // added_pt.normal_z = 0; // added_pt.x = pl_orig.points[ i ].x; // added_pt.y = pl_orig.points[ i ].y; // added_pt.z = pl_orig.points[ i ].z; // added_pt.intensity = pl_orig.points[ i ].intensity; // added_pt.curvature = pl_orig.points[ i ].time * time_unit_scale; // if ( !given_offset_time ) // { // int layer = pl_orig.points[ i ].ring; // double yaw_angle = atan2( added_pt.y, added_pt.x ) * 57.2957; // if ( is_first[ layer ] ) // { // // printf("layer: %d; is first: %d", layer, is_first[layer]); // yaw_fp[ layer ] = yaw_angle; // is_first[ layer ] = false; // added_pt.curvature = 0.0; // yaw_last[ layer ] = yaw_angle; // time_last[ layer ] = added_pt.curvature; // continue; // } // // compute offset time // if ( yaw_angle <= yaw_fp[ layer ] ) // { // added_pt.curvature = ( yaw_fp[ layer ] - yaw_angle ) / omega_l; // } // else // { // added_pt.curvature = ( yaw_fp[ layer ] - yaw_angle + 360.0 ) / omega_l; // } // if ( added_pt.curvature < time_last[ layer ] ) // added_pt.curvature += 360.0 / omega_l; // // added_pt.curvature = pl_orig.points[i].t; // yaw_last[ layer ] = yaw_angle; // time_last[ layer ] = added_pt.curvature; // } // // if(i==(plsize-1)) printf("index: %d layer: %d, yaw: %lf, offset-time: %lf, condition: %d\n", i, layer, yaw_angle, // added_pt.curvature, // // prints); // if ( i % point_filter_num == 0 ) // { // if ( added_pt.x * added_pt.x + added_pt.y * added_pt.y + added_pt.z * added_pt.z > blind_sqr ) // { // pl_surf.points.push_back( added_pt ); // // printf("time mode: %d time: %d \n", given_offset_time, pl_orig.points[i].t); // } // } // } // } // // pub_func(pl_surf, pub_full, msg->header.stamp); // // pub_func(pl_surf, pub_surf, msg->header.stamp); // // pub_func(pl_surf, pub_corn, msg->header.stamp); // } void Preprocess::xt32_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ) { // std::cout << __FILE__ << ", " << __LINE__ << std::endl; pl_surf.clear(); pl_corn.clear(); pl_full.clear(); pcl::PointCloud< xt32_ros::Point > pl_orig; pcl::fromROSMsg( *msg, pl_orig ); int plsize = pl_orig.points.size(); pl_surf.reserve( plsize ); bool is_first[ MAX_LINE_NUM ]; double yaw_fp[ MAX_LINE_NUM ] = { 0 }; // yaw of first scan point double omega_l = 3.61; // scan angular velocity float yaw_last[ MAX_LINE_NUM ] = { 0.0 }; // yaw of last scan point float time_last[ MAX_LINE_NUM ] = { 0.0 }; // last offset time if ( pl_orig.points[ plsize - 1 ].timestamp > 0 ) { given_offset_time = true; } else { given_offset_time = false; memset( is_first, true, sizeof( is_first ) ); double yaw_first = atan2( pl_orig.points[ 0 ].y, pl_orig.points[ 0 ].x ) * 57.29578; double yaw_end = yaw_first; int layer_first = pl_orig.points[ 0 ].ring; for ( uint i = plsize - 1; i > 0; i-- ) { if ( pl_orig.points[ i ].ring == layer_first ) { yaw_end = atan2( pl_orig.points[ i ].y, pl_orig.points[ i ].x ) * 57.29578; break; } } } double time_head = pl_orig.points[ 0 ].timestamp; if ( feature_enabled ) { for ( int i = 0; i < N_SCANS; i++ ) { pl_buff[ i ].clear(); pl_buff[ i ].reserve( plsize ); } for ( int i = 0; i < plsize; i++ ) { PointType added_pt; added_pt.normal_x = 0; added_pt.normal_y = 0; added_pt.normal_z = 0; int layer = pl_orig.points[ i ].ring; if ( layer >= N_SCANS ) continue; added_pt.x = pl_orig.points[ i ].x; added_pt.y = pl_orig.points[ i ].y; added_pt.z = pl_orig.points[ i ].z; added_pt.intensity = pl_orig.points[ i ].intensity; added_pt.curvature = pl_orig.points[ i ].timestamp / 1000.0; // units: ms if ( !given_offset_time ) { double yaw_angle = atan2( added_pt.y, added_pt.x ) * 57.2957; if ( is_first[ layer ] ) { // printf("layer: %d; is first: %d", layer, is_first[layer]); yaw_fp[ layer ] = yaw_angle; is_first[ layer ] = false; added_pt.curvature = 0.0; yaw_last[ layer ] = yaw_angle; time_last[ layer ] = added_pt.curvature; continue; } if ( yaw_angle <= yaw_fp[ layer ] ) { added_pt.curvature = ( yaw_fp[ layer ] - yaw_angle ) / omega_l; } else { added_pt.curvature = ( yaw_fp[ layer ] - yaw_angle + 360.0 ) / omega_l; } if ( added_pt.curvature < time_last[ layer ] ) added_pt.curvature += 360.0 / omega_l; yaw_last[ layer ] = yaw_angle; time_last[ layer ] = added_pt.curvature; } pl_buff[ layer ].points.push_back( added_pt ); } for ( int j = 0; j < N_SCANS; j++ ) { PointCloudXYZI &pl = pl_buff[ j ]; int linesize = pl.size(); if ( linesize < 2 ) continue; vector< orgtype > &types = typess[ j ]; types.clear(); types.resize( linesize ); linesize--; for ( uint i = 0; i < linesize; i++ ) { types[ i ].range = sqrt( pl[ i ].x * pl[ i ].x + pl[ i ].y * pl[ i ].y ); vx = pl[ i ].x - pl[ i + 1 ].x; vy = pl[ i ].y - pl[ i + 1 ].y; vz = pl[ i ].z - pl[ i + 1 ].z; types[ i ].dista = vx * vx + vy * vy + vz * vz; } types[ linesize ].range = sqrt( pl[ linesize ].x * pl[ linesize ].x + pl[ linesize ].y * pl[ linesize ].y ); give_feature( pl, types ); } } else { for ( int i = 0; i < plsize; i++ ) { PointType added_pt; // cout<<"!!!!!!"<<i<<" "<<plsize<<endl; added_pt.normal_x = 0; added_pt.normal_y = 0; added_pt.normal_z = 0; added_pt.x = pl_orig.points[ i ].x; added_pt.y = pl_orig.points[ i ].y; added_pt.z = pl_orig.points[ i ].z; added_pt.intensity = pl_orig.points[ i ].intensity; added_pt.curvature = ( pl_orig.points[ i ].timestamp - time_head ) * 1000.f; // if ( i % 1000 == 0 ) // { // printf( "added_pt.curvature: %lf %lf %f \n", added_pt.curvature, pl_orig.points[ i ].timestamp, ( float ) time_unit_scale ); // } // if(i==(plsize-1)) printf("index: %d layer: %d, yaw: %lf, offset-time: %lf, condition: %d\n", i, layer, yaw_angle, added_pt.curvature, // prints); if ( i % point_filter_num == 0 ) { if ( added_pt.x * added_pt.x + added_pt.y * added_pt.y + added_pt.z * added_pt.z > blind_sqr ) { pl_surf.points.push_back( added_pt ); // printf("time mode: %d time: %d \n", given_offset_time, pl_orig.points[i].t); } } } } // pub_func(pl_surf, pub_full, msg->header.stamp); // pub_func(pl_surf, pub_surf, msg->header.stamp); // pub_func(pl_surf, pub_corn, msg->header.stamp); } void Preprocess::give_feature( pcl::PointCloud< PointType > &pl, vector< orgtype > &types ) { int plsize = pl.size(); int plsize2; if ( plsize == 0 ) { printf( "something wrong\n" ); return; } uint head = 0; while ( types[ head ].range < blind_sqr ) { head++; } // Surf plsize2 = ( plsize > group_size ) ? ( plsize - group_size ) : 0; Eigen::Vector3d curr_direct( Eigen::Vector3d::Zero() ); Eigen::Vector3d last_direct( Eigen::Vector3d::Zero() ); uint i_nex = 0, i2; uint last_i = 0; uint last_i_nex = 0; int last_state = 0; int plane_type; for ( uint i = head; i < plsize2; i++ ) { if ( types[ i ].range < blind_sqr ) { continue; } i2 = i; plane_type = plane_judge( pl, types, i, i_nex, curr_direct ); if ( plane_type == 1 ) { for ( uint j = i; j <= i_nex; j++ ) { if ( j != i && j != i_nex ) { types[ j ].ftype = Real_Plane; } else { types[ j ].ftype = Poss_Plane; } } // if(last_state==1 && fabs(last_direct.sum())>0.5) if ( last_state == 1 && last_direct.norm() > 0.1 ) { double mod = last_direct.transpose() * curr_direct; if ( mod > -0.707 && mod < 0.707 ) { types[ i ].ftype = Edge_Plane; } else { types[ i ].ftype = Real_Plane; } } i = i_nex - 1; last_state = 1; } else // if(plane_type == 2) { i = i_nex; last_state = 0; } // else if(plane_type == 0) // { // if(last_state == 1) // { // uint i_nex_tem; // uint j; // for(j=last_i+1; j<=last_i_nex; j++) // { // uint i_nex_tem2 = i_nex_tem; // Eigen::Vector3d curr_direct2; // uint ttem = plane_judge(pl, types, j, i_nex_tem, curr_direct2); // if(ttem != 1) // { // i_nex_tem = i_nex_tem2; // break; // } // curr_direct = curr_direct2; // } // if(j == last_i+1) // { // last_state = 0; // } // else // { // for(uint k=last_i_nex; k<=i_nex_tem; k++) // { // if(k != i_nex_tem) // { // types[k].ftype = Real_Plane; // } // else // { // types[k].ftype = Poss_Plane; // } // } // i = i_nex_tem-1; // i_nex = i_nex_tem; // i2 = j-1; // last_state = 1; // } // } // } last_i = i2; last_i_nex = i_nex; last_direct = curr_direct; } plsize2 = plsize > 3 ? plsize - 3 : 0; for ( uint i = head + 3; i < plsize2; i++ ) { if ( types[ i ].range < blind_sqr || types[ i ].ftype >= Real_Plane ) { continue; } if ( types[ i - 1 ].dista < 1e-16 || types[ i ].dista < 1e-16 ) { continue; } Eigen::Vector3d vec_a( pl[ i ].x, pl[ i ].y, pl[ i ].z ); Eigen::Vector3d vecs[ 2 ]; for ( int j = 0; j < 2; j++ ) { int m = -1; if ( j == 1 ) { m = 1; } if ( types[ i + m ].range < blind_sqr ) { if ( types[ i ].range > inf_bound ) { types[ i ].edj[ j ] = Nr_inf; } else { types[ i ].edj[ j ] = Nr_blind; } continue; } vecs[ j ] = Eigen::Vector3d( pl[ i + m ].x, pl[ i + m ].y, pl[ i + m ].z ); vecs[ j ] = vecs[ j ] - vec_a; types[ i ].angle[ j ] = vec_a.dot( vecs[ j ] ) / vec_a.norm() / vecs[ j ].norm(); if ( types[ i ].angle[ j ] < jump_up_limit ) { types[ i ].edj[ j ] = Nr_180; } else if ( types[ i ].angle[ j ] > jump_down_limit ) { types[ i ].edj[ j ] = Nr_zero; } } types[ i ].intersect = vecs[ Prev ].dot( vecs[ Next ] ) / vecs[ Prev ].norm() / vecs[ Next ].norm(); if ( types[ i ].edj[ Prev ] == Nr_nor && types[ i ].edj[ Next ] == Nr_zero && types[ i ].dista > 0.0225 && types[ i ].dista > 4 * types[ i - 1 ].dista ) { if ( types[ i ].intersect > cos160 ) { if ( edge_jump_judge( pl, types, i, Prev ) ) { types[ i ].ftype = Edge_Jump; } } } else if ( types[ i ].edj[ Prev ] == Nr_zero && types[ i ].edj[ Next ] == Nr_nor && types[ i - 1 ].dista > 0.0225 && types[ i - 1 ].dista > 4 * types[ i ].dista ) { if ( types[ i ].intersect > cos160 ) { if ( edge_jump_judge( pl, types, i, Next ) ) { types[ i ].ftype = Edge_Jump; } } } else if ( types[ i ].edj[ Prev ] == Nr_nor && types[ i ].edj[ Next ] == Nr_inf ) { if ( edge_jump_judge( pl, types, i, Prev ) ) { types[ i ].ftype = Edge_Jump; } } else if ( types[ i ].edj[ Prev ] == Nr_inf && types[ i ].edj[ Next ] == Nr_nor ) { if ( edge_jump_judge( pl, types, i, Next ) ) { types[ i ].ftype = Edge_Jump; } } else if ( types[ i ].edj[ Prev ] > Nr_nor && types[ i ].edj[ Next ] > Nr_nor ) { if ( types[ i ].ftype == Nor ) { types[ i ].ftype = Wire; } } } plsize2 = plsize - 1; double ratio; for ( uint i = head + 1; i < plsize2; i++ ) { if ( types[ i ].range < blind_sqr || types[ i - 1 ].range < blind_sqr || types[ i + 1 ].range < blind_sqr ) { continue; } if ( types[ i - 1 ].dista < 1e-8 || types[ i ].dista < 1e-8 ) { continue; } if ( types[ i ].ftype == Nor ) { if ( types[ i - 1 ].dista > types[ i ].dista ) { ratio = types[ i - 1 ].dista / types[ i ].dista; } else { ratio = types[ i ].dista / types[ i - 1 ].dista; } if ( types[ i ].intersect < smallp_intersect && ratio < smallp_ratio ) { if ( types[ i - 1 ].ftype == Nor ) { types[ i - 1 ].ftype = Real_Plane; } if ( types[ i + 1 ].ftype == Nor ) { types[ i + 1 ].ftype = Real_Plane; } types[ i ].ftype = Real_Plane; } } } int last_surface = -1; for ( uint j = head; j < plsize; j++ ) { if ( types[ j ].ftype == Poss_Plane || types[ j ].ftype == Real_Plane ) { if ( last_surface == -1 ) { last_surface = j; } if ( j == uint( last_surface + point_filter_num - 1 ) ) { PointType ap; ap.x = pl[ j ].x; ap.y = pl[ j ].y; ap.z = pl[ j ].z; ap.curvature = pl[ j ].curvature; pl_surf.push_back( ap ); last_surface = -1; } } else { if ( types[ j ].ftype == Edge_Jump || types[ j ].ftype == Edge_Plane ) { pl_corn.push_back( pl[ j ] ); } if ( last_surface != -1 ) { PointType ap; for ( uint k = last_surface; k < j; k++ ) { ap.x += pl[ k ].x; ap.y += pl[ k ].y; ap.z += pl[ k ].z; ap.curvature += pl[ k ].curvature; } ap.x /= ( j - last_surface ); ap.y /= ( j - last_surface ); ap.z /= ( j - last_surface ); ap.curvature /= ( j - last_surface ); pl_surf.push_back( ap ); } last_surface = -1; } } } void Preprocess::pub_func( PointCloudXYZI &pl, const ros::Time &ct ) { pl.height = 1; pl.width = pl.size(); sensor_msgs::PointCloud2 output; pcl::toROSMsg( pl, output ); output.header.frame_id = "livox"; output.header.stamp = ct; } int Preprocess::plane_judge( const PointCloudXYZI &pl, vector< orgtype > &types, uint i_cur, uint &i_nex, Eigen::Vector3d &curr_direct ) { double group_dis = disA * types[ i_cur ].range + disB; group_dis = group_dis * group_dis; // i_nex = i_cur; double two_dis; vector< double > disarr; disarr.reserve( 20 ); for ( i_nex = i_cur; i_nex < i_cur + group_size; i_nex++ ) { if ( types[ i_nex ].range < blind_sqr ) { curr_direct.setZero(); return 2; } disarr.push_back( types[ i_nex ].dista ); } for ( ;; ) { if ( ( i_cur >= pl.size() ) || ( i_nex >= pl.size() ) ) break; if ( types[ i_nex ].range < blind_sqr ) { curr_direct.setZero(); return 2; } vx = pl[ i_nex ].x - pl[ i_cur ].x; vy = pl[ i_nex ].y - pl[ i_cur ].y; vz = pl[ i_nex ].z - pl[ i_cur ].z; two_dis = vx * vx + vy * vy + vz * vz; if ( two_dis >= group_dis ) { break; } disarr.push_back( types[ i_nex ].dista ); i_nex++; } double leng_wid = 0; double v1[ 3 ], v2[ 3 ]; for ( uint j = i_cur + 1; j < i_nex; j++ ) { if ( ( j >= pl.size() ) || ( i_cur >= pl.size() ) ) break; v1[ 0 ] = pl[ j ].x - pl[ i_cur ].x; v1[ 1 ] = pl[ j ].y - pl[ i_cur ].y; v1[ 2 ] = pl[ j ].z - pl[ i_cur ].z; v2[ 0 ] = v1[ 1 ] * vz - vy * v1[ 2 ]; v2[ 1 ] = v1[ 2 ] * vx - v1[ 0 ] * vz; v2[ 2 ] = v1[ 0 ] * vy - vx * v1[ 1 ]; double lw = v2[ 0 ] * v2[ 0 ] + v2[ 1 ] * v2[ 1 ] + v2[ 2 ] * v2[ 2 ]; if ( lw > leng_wid ) { leng_wid = lw; } } if ( ( two_dis * two_dis / leng_wid ) < p2l_ratio ) { curr_direct.setZero(); return 0; } uint disarrsize = disarr.size(); for ( uint j = 0; j < disarrsize - 1; j++ ) { for ( uint k = j + 1; k < disarrsize; k++ ) { if ( disarr[ j ] < disarr[ k ] ) { leng_wid = disarr[ j ]; disarr[ j ] = disarr[ k ]; disarr[ k ] = leng_wid; } } } if ( disarr[ disarr.size() - 2 ] < 1e-16 ) { curr_direct.setZero(); return 0; } if ( lidar_type == AVIA ) { double dismax_mid = disarr[ 0 ] / disarr[ disarrsize / 2 ]; double dismid_min = disarr[ disarrsize / 2 ] / disarr[ disarrsize - 2 ]; if ( dismax_mid >= limit_maxmid || dismid_min >= limit_midmin ) { curr_direct.setZero(); return 0; } } else { double dismax_min = disarr[ 0 ] / disarr[ disarrsize - 2 ]; if ( dismax_min >= limit_maxmin ) { curr_direct.setZero(); return 0; } } curr_direct << vx, vy, vz; curr_direct.normalize(); return 1; } bool Preprocess::edge_jump_judge( const PointCloudXYZI &pl, vector< orgtype > &types, uint i, Surround nor_dir ) { if ( nor_dir == 0 ) { if ( types[ i - 1 ].range < blind_sqr || types[ i - 2 ].range < blind_sqr ) { return false; } } else if ( nor_dir == 1 ) { if ( types[ i + 1 ].range < blind_sqr || types[ i + 2 ].range < blind_sqr ) { return false; } } double d1 = types[ i + nor_dir - 1 ].dista; double d2 = types[ i + 3 * nor_dir - 2 ].dista; double d; if ( d1 < d2 ) { d = d1; d1 = d2; d2 = d; } d1 = sqrt( d1 ); d2 = sqrt( d2 ); if ( d1 > edgea * d2 || ( d1 - d2 ) > edgeb ) { return false; } return true; }
C++
3D
hku-mars/ImMesh
src/voxel_mapping.hpp
.hpp
19,127
416
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <condition_variable> #include <pcl/filters/voxel_grid.h> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <nav_msgs/Odometry.h> #include <nav_msgs/Path.h> #include "IMU_Processing.h" #include "preprocess.h" #include "ikd-Tree/ikd_Tree.h" #include "voxel_loc.hpp" #define INIT_TIME ( 0.0 ) #define MAXN ( 360000 ) #define PUBFRAME_PERIOD ( 20 ) #define NUM_POINTS 2000 using KDtree_pt = ikdTree_PointType; using KDtree_pt_vector = KD_TREE< KDtree_pt >::PointVector; #define time_debug #define HASH_P 116101 #define MAX_N 10000000000 const bool intensity_contrast( PointType &x, PointType &y ); const bool var_contrast( Point_with_var &x, Point_with_var &y ); float calc_dist( PointType p1, PointType p2 ); void mapJet( double v, double vmin, double vmax, uint8_t &r, uint8_t &g, uint8_t &b ); void buildUnorderMap( const std::vector< Point_with_var > &input_points, const float voxel_size, const Eigen::Vector3d &layer_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ); void buildVoxelMap( const std::vector< Point_with_var > &input_points, const float voxel_size, const int max_layer, const std::vector< int > &layer_init_num, const int max_points_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ); V3F RGBFromVoxel( const V3D &input_point, const float voxel_size, const Eigen::Vector3d &layer_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ); void updateUnorderMap( const std::vector< Point_with_var > &input_points, const float voxel_size, const Eigen::Vector3d &layer_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ); void updateVoxelMap( const std::vector< Point_with_var > &input_points, const float voxel_size, const int max_layer, const std::vector< int > &layer_init_num, const int max_points_size, const float planer_threshold, std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map ); void build_single_residual( const Point_with_var &pv, const OctoTree *current_octo, const int current_layer, const int max_layer, const double sigma_num, bool &is_sucess, double &prob, ptpl &single_ptpl ); void transformLidar( const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr &input_cloud, pcl::PointCloud< pcl::PointXYZI >::Ptr &trans_cloud ); void BuildPtplList( const unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const float match_eigen_value, const int layer, const float voxel_size, const float match_constraint, const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr input_cloud, std::vector< ptpl > &ptpl_list ); void BuildResidualListOMP( const unordered_map< VOXEL_LOC, OctoTree * > &voxel_map, const double voxel_size, const double sigma_num, const int max_layer, const std::vector< Point_with_var > &pv_list, std::vector< ptpl > &ptpl_list, std::vector< Eigen::Vector3d > &non_match ); void BuildResidualList( const unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const double voxel_size, const double sigma_num, const Point_with_var &pv, const M3D &rot, const V3D &t, const M3D &ext_R, const V3D &ext_T, ptpl &ptpl_list ); void BuildOptiList( const unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const float voxel_size, const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr input_cloud, const float sigma_num, const std::vector< Eigen::Matrix3d > var_list, std::vector< ptpl > &ptpl_list ); void CalcQuation( const Eigen::Vector3d &vec, const int axis, geometry_msgs::Quaternion &q ); void NormalToQuaternion( const Eigen::Vector3d &normal_vec, geometry_msgs::Quaternion &q ); void pubNormal( visualization_msgs::MarkerArray &normal_pub, const std::string normal_ns, const int normal_id, const pcl::PointXYZINormal normal_p, const float alpha, const Eigen::Vector3d rgb ); void pubPlane( visualization_msgs::MarkerArray &plane_pub, const std::string plane_ns, const int plane_id, const pcl::PointXYZINormal normal_p, const float radius, const float min_eigen_value, const float alpha, const Eigen::Vector3d rgb ); void pubPlaneMap( const std::unordered_map< VOXEL_LOC, OctoTree * > &feat_map, const ros::Publisher &plane_map_pub, const V3D &position ); // Similar with PCL voxelgrid filter void down_sampling_voxel( pcl::PointCloud< pcl::PointXYZI > &pl_feat, double voxel_size ); void calcBodyVar( Eigen::Vector3d &pb, const float range_inc, const float degree_inc, Eigen::Matrix3d &var ); void reconstruct_mesh_from_pointcloud( pcl::PointCloud< pcl::PointXYZI >::Ptr frame_pts, double minimum_pts_distance = 0.01 ); class Voxel_mapping { public: std::shared_ptr< ros::NodeHandle > m_ros_node_ptr = nullptr; float DETECTION_RANGE = 300.0f; const float MOV_THRESHOLD = 1.5f; mutex m_mutex_buffer; condition_variable m_sig_buffer; // mutex mtx_buffer_pointcloud; string m_root_dir = ROOT_DIR; string m_map_file_path, m_lid_topic, m_imu_topic, m_hilti_seq_name, m_img_topic, m_config_file; M3D Eye3d = M3D::Identity(); M3F Eye3f = M3F::Identity(); V3D Zero3d = V3D::Zero(); V3F Zero3f = V3F::Zero(); V3D m_extT = Zero3d; M3D m_extR = Eye3d; M3D _gravity_correct_rotM = M3D::Identity(); int NUM_MAX_ITERATIONS = 0; int MIN_IMG_COUNT = 0; double HALF_FOV_COS = 0, FOV_DEG = 0; bool USE_NED = true; int m_iterCount = 0, m_feats_down_size = 0, m_laserCloudValidNum = 0, m_effct_feat_num = 0, m_time_log_counter = 0, m_publish_count = 0; double m_res_mean_last = 0.05, m_last_lidar_processed_time = -1.0; double m_gyr_cov = 0, m_acc_cov = 0; double m_last_timestamp_lidar = -1.0, m_last_timestamp_imu = -1.0, m_last_timestamp_img = -1.0; double m_filter_size_corner_min = 0, m_filter_size_surf_min = 0, m_filter_size_map_min = 0, m_fov_deg = 0; double m_cube_len = 0, m_total_distance = 0, m_lidar_end_time = 0, m_first_lidar_time = 0.0; double m_first_img_time = -1.0; double m_kdtree_incremental_time = 0, m_kdtree_search_time = 0, m_kdtree_delete_time = 0.0; int m_kdtree_search_counter = 0, m_kdtree_size_st = 0, m_kdtree_size_end = 0, m_add_point_size = 0, m_kdtree_delete_counter = 0; double m_copy_time = 0, m_readd_time = 0, m_fov_check_time = 0, m_readd_box_time = 0, m_delete_box_time = 0; double m_T1[ MAXN ], m_T2[ MAXN ], m_s_plot[ MAXN ], m_s_plot2[ MAXN ], m_s_plot3[ MAXN ], m_s_plot4[ MAXN ], m_s_plot5[ MAXN ], m_s_plot6[ MAXN ], m_s_plot7[ MAXN ]; double m_keyf_rotd = 0.05, m_keyf_posd = 0.15; double m_match_time = 0, m_solve_time = 0, m_solve_const_H_time = 0; /*** For voxel map ***/ double m_max_voxel_size, m_min_eigen_value = 0.003, m_match_s = 0.90, m_sigma_num = 2.0, m_match_eigen_value = 0.0025; double m_beam_err = 0.03, m_dept_err = 0.05; int m_pub_map = 0, m_voxel_layer = 1; int m_last_match_num = 0; bool m_init_map = false, m_use_new_map = true, m_is_pub_plane_map = false, m_pcd_save_en = false, m_img_save_en = false, m_effect_point_pub = false, m_hilti_en = false; int m_min_points_size = 30, m_pcd_save_type = 0, m_pcd_save_interval = -1, m_img_save_interval = 1, m_pcd_index = 0, m_pub_point_skip = 1; std::time_t m_startTime, m_endTime; std::unordered_map< VOXEL_LOC, OctoTree * > m_feat_map; V3D m_layer_size = V3D( 20, 10, 10 ); std::vector< M3D > m_cross_mat_list; std::vector< M3D > m_body_cov_list; /*********************/ int m_max_points_size; int m_max_layer; std::vector< int > m_layer_init_size; bool m_lidar_pushed, m_imu_en, m_flg_reset, m_flg_exit = false; int m_dense_map_en = 1; int m_img_en = 1, m_imu_int_frame = 3; int m_lidar_en = 1; int m_GUI_font_size = 14; int m_debug = 0; bool m_is_first_frame = false; int m_grid_size, m_patch_size; double m_outlier_threshold; vector< BoxPointType > m_cub_need_rm; vector< BoxPointType > m_cub_need_add; // deque<sensor_msgs::PointCloud2::ConstPtr> lidar_buffer; deque< PointCloudXYZI::Ptr > m_lidar_buffer; deque< double > m_time_buffer; deque< sensor_msgs::Imu::ConstPtr > m_imu_buffer; deque< cv::Mat > m_img_buffer; deque< double > m_img_time_buffer; vector< bool > m_point_selected_surf; vector< vector< int > > m_pointSearchInd_surf; vector< PointVector > m_Nearest_Points; vector< double > m_res_last; double m_total_residual; double LASER_POINT_COV, IMG_POINT_COV, cam_fx, cam_fy, cam_cx, cam_cy; bool m_flg_EKF_inited, m_flg_EKF_converged, m_EKF_stop_flg = 0; // surf feature in map PointCloudXYZI::Ptr m_featsFromMap = nullptr; PointCloudXYZI::Ptr m_cube_points_add = nullptr; PointCloudXYZI::Ptr m_map_cur_frame_point = nullptr; PointCloudXYZI::Ptr m_sub_map_cur_frame_point = nullptr; PointCloudXYZI::Ptr m_feats_undistort = nullptr; PointCloudXYZI::Ptr m_feats_down_body = nullptr; PointCloudXYZI::Ptr m_feats_down_world = nullptr; PointCloudXYZI::Ptr m_normvec = nullptr; PointCloudXYZI::Ptr m_laserCloudOri = nullptr; PointCloudXYZI::Ptr m_corr_normvect = nullptr; ofstream m_fout_pre, m_fout_out, m_fout_dbg, m_fout_pcd_pos, m_fout_img_pos; pcl::VoxelGrid< PointType > m_downSizeFilterSurf; // pcl::VoxelGrid<PointType> downSizeFilterMap; PointCloudXYZI::Ptr m_pcl_wait_pub = nullptr; PointCloudXYZI::Ptr m_pcl_wait_save = nullptr; shared_ptr< Preprocess > m_p_pre = nullptr; PointCloudXYZI::Ptr m_pcl_visual_wait_pub = nullptr; PointCloudXYZI::Ptr m_sub_pcl_visual_wait_pub = nullptr; vector< double > m_extrin_T; vector< double > m_extrin_R; vector< double > m_camera_extrin_T; vector< double > m_camera_extrin_R; // KD_TREE m_ikdtree; KD_TREE< PointType > m_ikdtree; V3F m_XAxis_Point_body = V3F( LIDAR_SP_LEN, 0.0, 0.0 ); V3F m_XAxis_Point_world = V3F( LIDAR_SP_LEN, 0.0, 0.0 ); V3D m_euler_cur; V3D m_position_last = Zero3d; Eigen::Matrix3d m_Rcl; Eigen::Vector3d m_Pcl; // estimator inputs and output; LidarMeasureGroup m_Lidar_Measures; // SparseMap sparse_map; StatesGroup state; nav_msgs::Path m_pub_path; nav_msgs::Odometry m_odom_aft_mapped; geometry_msgs::Quaternion m_geo_Quat; geometry_msgs::PoseStamped m_msg_body_pose; BoxPointType m_LocalMap_Points; bool m_localmap_Initialized = false; int m_points_cache_size = 0; StatesGroup m_last_state; double m_img_lid_time_diff = 0; int m_scanIdx = 0; // Configuration for meshing double m_meshing_distance_scale = 1.0; double m_meshing_points_minimum_scale = 0.1; double m_meshing_voxel_resolution = 0.4; double m_meshing_region_size = 10.0; int m_if_enable_mesh_rec = 1; int m_if_draw_mesh = 1; int m_meshing_maximum_thread_for_rec_mesh = 12; int m_meshing_number_of_pts_append_to_map = 5000; std::string m_pointcloud_file_name = std::string( " " ); // PointCloudXYZRGB::Ptr pcl_wait_pub_RGB(new PointCloudXYZRGB(500000, 1)); Voxel_mapping() { m_extrin_T = std::vector< double >( 3, 0.0 ); m_extrin_R = std::vector< double >( 9, 0.0 ); m_camera_extrin_T = std::vector< double >( 3, 0.0 ); m_camera_extrin_R = std::vector< double >( 9, 0.0 ); m_featsFromMap = PointCloudXYZI().makeShared(); m_cube_points_add = PointCloudXYZI().makeShared(); m_map_cur_frame_point = PointCloudXYZI().makeShared(); m_sub_map_cur_frame_point = PointCloudXYZI().makeShared(); m_feats_undistort = PointCloudXYZI().makeShared(); m_feats_down_body = PointCloudXYZI().makeShared(); m_feats_down_world = PointCloudXYZI().makeShared(); m_normvec = PointCloudXYZI( 100000, 1 ).makeShared(); m_laserCloudOri = PointCloudXYZI( 100000, 1 ).makeShared(); m_corr_normvect = PointCloudXYZI( 100000, 1 ).makeShared(); m_pcl_wait_pub = PointCloudXYZI( 500000, 1 ).makeShared(); m_pcl_wait_save = PointCloudXYZI().makeShared(); m_p_pre = std::make_shared< Preprocess >(); m_pcl_visual_wait_pub = PointCloudXYZI( 500000, 1 ).makeShared(); m_sub_pcl_visual_wait_pub = PointCloudXYZI( 500000, 1 ).makeShared(); } void kitti_log( FILE *fp ); void SigHandle( int sig ); void dump_lio_state_to_log( FILE *fp ); void pointBodyToWorld( const PointType &pi, PointType &po ); template < typename T > void pointBodyToWorld( const Matrix< T, 3, 1 > &pi, Matrix< T, 3, 1 > &po ) { V3D p_body( pi[ 0 ], pi[ 1 ], pi[ 2 ] ); V3D p_global( state.rot_end * ( m_extR * p_body + m_extT ) + state.pos_end ); po[ 0 ] = p_global( 0 ); po[ 1 ] = p_global( 1 ); po[ 2 ] = p_global( 2 ); } template < typename T > Matrix< T, 3, 1 > pointBodyToWorld( const Matrix< T, 3, 1 > &pi ) { V3D p( pi[ 0 ], pi[ 1 ], pi[ 2 ] ); p = ( state.rot_end * ( m_extR * p + m_extT ) + state.pos_end ); Matrix< T, 3, 1 > po( p[ 0 ], p[ 1 ], p[ 2 ] ); return po; } void frameBodyToWorld( const PointCloudXYZI::Ptr &pi, PointCloudXYZI::Ptr &po ); void get_NED_transform(); void RGBpointBodyToWorld( PointType const *const pi, PointType *const po ); void RGBpointBodyLidarToIMU( PointType const *const pi, PointType *const po ); void points_cache_collect(); void laser_map_fov_segment(); void standard_pcl_cbk( const sensor_msgs::PointCloud2::ConstPtr &msg ); void livox_pcl_cbk( const livox_ros_driver::CustomMsg::ConstPtr &msg ); void imu_cbk( const sensor_msgs::Imu::ConstPtr &msg_in ); bool sync_packages( LidarMeasureGroup &meas ); void map_incremental_grow(); void publish_voxel_point( const ros::Publisher &pubLaserCloudVoxel, const PointCloudXYZI::Ptr &pcl_wait_pub ); void publish_visual_world_map( const ros::Publisher &pubVisualCloud ); void publish_visual_world_sub_map( const ros::Publisher &pubSubVisualCloud ); void publish_effect_world( const ros::Publisher &pubLaserCloudEffect ); void publish_map( const ros::Publisher &pubLaserCloudMap ); template < typename T > void set_pose_timestamp( T &out ) { #ifdef USE_IKFOM // state_ikfom stamp_state = kf.get_x(); out.position.x = state_point.pos( 0 ); out.position.y = state_point.pos( 1 ); out.position.z = state_point.pos( 2 ); #else out.position.x = state.pos_end( 0 ); out.position.y = state.pos_end( 1 ); out.position.z = state.pos_end( 2 ); #endif out.orientation.x = m_geo_Quat.x; out.orientation.y = m_geo_Quat.y; out.orientation.z = m_geo_Quat.z; out.orientation.w = m_geo_Quat.w; } void publish_odometry( const ros::Publisher &pubOdomAftMapped ); void publish_mavros( const ros::Publisher &mavros_pose_publisher ); void publish_frame_world( const ros::Publisher &pubLaserCloudFullRes, const int point_skip ); void publish_path( const ros::Publisher pubPath ); void read_ros_parameters( ros::NodeHandle &nh ); void transformLidar( const Eigen::Matrix3d rot, const Eigen::Vector3d t, const PointCloudXYZI::Ptr &input_cloud, pcl::PointCloud< pcl::PointXYZI >::Ptr &trans_cloud ); bool voxel_map_init(); /*** EKF update ***/ void lio_state_estimation( StatesGroup &state_propagat ); void init_ros_node(); int service_LiDAR_update(); };
Unknown
3D
hku-mars/ImMesh
src/IMU_Processing.cpp
.cpp
43,055
1,009
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "IMU_Processing.h" Eigen::Matrix3d Eye3d = Eigen::Matrix3d::Identity(); Eigen::Matrix3f Eye3f = Eigen::Matrix3f::Identity(); Eigen::Vector3d Zero3d = Eigen::Vector3d::Zero(); Eigen::Vector3f Zero3f = Eigen::Vector3f::Zero(); const bool time_list( PointType &x, PointType &y ) { return ( x.curvature < y.curvature ); } ImuProcess::ImuProcess() : b_first_frame_( true ), imu_need_init_( true ), start_timestamp_( -1 ) { init_iter_num = 1; #ifdef USE_IKFOM Q = process_noise_cov(); #endif cov_acc = V3D( 0.1, 0.1, 0.1 ); cov_gyr = V3D( 0.1, 0.1, 0.1 ); // cov_acc_scale = V3D(1, 1, 1); // cov_gyr_scale = V3D(1, 1, 1); cov_bias_gyr = V3D( 0.1, 0.1, 0.1 ); cov_bias_acc = V3D( 0.1, 0.1, 0.1 ); mean_acc = V3D( 0, 0, -1.0 ); mean_gyr = V3D( 0, 0, 0 ); angvel_last = Zero3d; acc_s_last = Zero3d; Lid_offset_to_IMU = Zero3d; Lid_rot_to_IMU = Eye3d; last_imu_.reset( new sensor_msgs::Imu() ); } ImuProcess::~ImuProcess() {} void ImuProcess::Reset() { ROS_WARN( "Reset ImuProcess" ); mean_acc = V3D( 0, 0, -1.0 ); mean_gyr = V3D( 0, 0, 0 ); angvel_last = Zero3d; imu_need_init_ = true; start_timestamp_ = -1; init_iter_num = 1; v_imu_.clear(); IMUpose.clear(); last_imu_.reset( new sensor_msgs::Imu() ); cur_pcl_un_.reset( new PointCloudXYZI() ); } void ImuProcess::disable_imu() { cout << "IMU disabled !!!!!" << endl; imu_en = false; imu_need_init_ = false; } void ImuProcess::push_update_state( double offs_t, StatesGroup state ) { // V3D acc_tmp(last_acc), angvel_tmp(last_ang), vel_imu(state.vel_end), pos_imu(state.pos_end); // M3D R_imu(state.rot_end); // angvel_tmp -= state.bias_g; // acc_tmp = acc_tmp * G_m_s2 / mean_acc.norm() - state.bias_a; // acc_tmp = R_imu * acc_tmp + state.gravity; // IMUpose.push_back(set_pose6d(offs_t, acc_tmp, angvel_tmp, vel_imu, pos_imu, R_imu)); V3D acc_tmp = acc_s_last, angvel_tmp = angvel_last, vel_imu( state.vel_end ), pos_imu( state.pos_end ); M3D R_imu( state.rot_end ); IMUpose.push_back( set_pose6d( offs_t, acc_tmp, angvel_tmp, vel_imu, pos_imu, R_imu ) ); } void ImuProcess::set_extrinsic( const MD( 4, 4 ) & T ) { Lid_offset_to_IMU = T.block< 3, 1 >( 0, 3 ); Lid_rot_to_IMU = T.block< 3, 3 >( 0, 0 ); } void ImuProcess::set_extrinsic( const V3D &transl ) { Lid_offset_to_IMU = transl; Lid_rot_to_IMU.setIdentity(); } void ImuProcess::set_extrinsic( const V3D &transl, const M3D &rot ) { Lid_offset_to_IMU = transl; Lid_rot_to_IMU = rot; } void ImuProcess::set_gyr_cov_scale( const V3D &scaler ) { cov_gyr = scaler; } void ImuProcess::set_acc_cov_scale( const V3D &scaler ) { cov_acc = scaler; } void ImuProcess::set_gyr_bias_cov( const V3D &b_g ) { cov_bias_gyr = b_g; } void ImuProcess::set_acc_bias_cov( const V3D &b_a ) { cov_bias_acc = b_a; } void ImuProcess::set_imu_init_frame_num( const int &num ) { MAX_INI_COUNT = num; } #ifdef USE_IKFOM void ImuProcess::IMU_init( const MeasureGroup &meas, esekfom::esekf< state_ikfom, 12, input_ikfom > &kf_state, int &N ) { /** 1. initializing the gravity, gyro bias, acc and gyro covariance ** 2. normalize the acceleration measurenments to unit gravity **/ ROS_INFO( "IMU Initializing: %.1f %%", double( N ) / MAX_INI_COUNT * 100 ); V3D cur_acc, cur_gyr; if ( b_first_frame_ ) { Reset(); N = 1; b_first_frame_ = false; const auto &imu_acc = meas.imu.front()->linear_acceleration; const auto &gyr_acc = meas.imu.front()->angular_velocity; mean_acc << imu_acc.x, imu_acc.y, imu_acc.z; mean_gyr << gyr_acc.x, gyr_acc.y, gyr_acc.z; // first_lidar_time = meas.lidar_beg_time; // cout<<"init acc norm: "<<mean_acc.norm()<<endl; } for ( const auto &imu : meas.imu ) { const auto &imu_acc = imu->linear_acceleration; const auto &gyr_acc = imu->angular_velocity; cur_acc << imu_acc.x, imu_acc.y, imu_acc.z; cur_gyr << gyr_acc.x, gyr_acc.y, gyr_acc.z; mean_acc += ( cur_acc - mean_acc ) / N; mean_gyr += ( cur_gyr - mean_gyr ) / N; cov_acc = cov_acc * ( N - 1.0 ) / N + ( cur_acc - mean_acc ).cwiseProduct( cur_acc - mean_acc ) * ( N - 1.0 ) / ( N * N ); cov_gyr = cov_gyr * ( N - 1.0 ) / N + ( cur_gyr - mean_gyr ).cwiseProduct( cur_gyr - mean_gyr ) * ( N - 1.0 ) / ( N * N ); // cout<<"acc norm: "<<cur_acc.norm()<<" "<<mean_acc.norm()<<endl; N++; } state_ikfom init_state = kf_state.get_x(); init_state.grav = S2( -mean_acc / mean_acc.norm() * G_m_s2 ); // state_inout.rot = Eye3d; // Exp(mean_acc.cross(V3D(0, 0, -1 / scale_gravity))); init_state.bg = mean_gyr; init_state.offset_T_L_I = Lid_offset_to_IMU; init_state.offset_R_L_I = Lid_rot_to_IMU; kf_state.change_x( init_state ); esekfom::esekf< state_ikfom, 12, input_ikfom >::cov init_P = kf_state.get_P() * 0.001; kf_state.change_P( init_P ); last_imu_ = meas.imu.back(); } #else void ImuProcess::IMU_init( const MeasureGroup &meas, StatesGroup &state_inout, int &N ) { /** 1. initializing the gravity, gyro bias, acc and gyro covariance ** 2. normalize the acceleration measurenments to unit gravity **/ ROS_INFO( "IMU Initializing: %.1f %%", double( N ) / MAX_INI_COUNT * 100 ); V3D cur_acc, cur_gyr; if ( b_first_frame_ ) { Reset(); N = 1; b_first_frame_ = false; const auto &imu_acc = meas.imu.front()->linear_acceleration; const auto &gyr_acc = meas.imu.front()->angular_velocity; mean_acc << imu_acc.x, imu_acc.y, imu_acc.z; mean_gyr << gyr_acc.x, gyr_acc.y, gyr_acc.z; // first_lidar_time = meas.lidar_beg_time; // cout<<"init acc norm: "<<mean_acc.norm()<<endl; } for ( const auto &imu : meas.imu ) { const auto &imu_acc = imu->linear_acceleration; const auto &gyr_acc = imu->angular_velocity; cur_acc << imu_acc.x, imu_acc.y, imu_acc.z; cur_gyr << gyr_acc.x, gyr_acc.y, gyr_acc.z; mean_acc += ( cur_acc - mean_acc ) / N; mean_gyr += ( cur_gyr - mean_gyr ) / N; // cov_acc = cov_acc * (N - 1.0) / N + (cur_acc - mean_acc).cwiseProduct(cur_acc - mean_acc) * (N - 1.0) / (N * N); // cov_gyr = cov_gyr * (N - 1.0) / N + (cur_gyr - mean_gyr).cwiseProduct(cur_gyr - mean_gyr) * (N - 1.0) / (N * N); // cout<<"acc norm: "<<cur_acc.norm()<<" "<<mean_acc.norm()<<endl; N++; } state_inout.gravity = -mean_acc / mean_acc.norm() * G_m_s2; state_inout.rot_end = Eye3d; // Exp(mean_acc.cross(V3D(0, 0, -1 / scale_gravity))); state_inout.bias_g = Zero3d; // mean_gyr; last_imu_ = meas.imu.back(); } #endif #ifdef USE_IKFOM void ImuProcess::UndistortPcl( const MeasureGroup &meas, esekfom::esekf< state_ikfom, 12, input_ikfom > &kf_state, PointCloudXYZI &pcl_out ) { /*** add the imu of the last frame-tail to the of current frame-head ***/ auto v_imu = meas.imu; v_imu.push_front( last_imu_ ); const double & imu_beg_time = v_imu.front()->header.stamp.toSec(); const double &imu_end_time IMUpose.push_back( set_pose6d( offs_t, acc_imu, angvel_avr, vel_imu, pos_imu, R_imu ) ); time *** / pcl_out = *( meas.lidar ); sort( pcl_out.points.begin(), pcl_out.points.end(), time_list ); const double &pcl_end_time = pcl_beg_time + pcl_out.points.back().curvature / double( 1000 ); // cout<<"[ IMU Process ]: Process lidar from "<<pcl_beg_time<<" to "<<pcl_end_time<<", " \ // <<meas.imu.size()<<" imu msgs from "<<imu_beg_time<<" to "<<imu_end_time<<endl; /*** Initialize IMU pose ***/ state_ikfom imu_state = kf_state.get_x(); IMUpose.clear(); IMUpose.push_back( set_pose6d( 0.0, acc_s_last, angvel_last, imu_state.vel, imu_state.pos, imu_state.rot.toRotationMatrix() ) ); /*** forward propagation at each imu point ***/ V3D angvel_avr, acc_avr, acc_imu, vel_imu, pos_imu; M3D R_imu; double dt = 0; input_ikfom in; for ( auto it_imu = v_imu.begin(); it_imu < ( v_imu.end() - 1 ); it_imu++ ) { auto &&head = *( it_imu ); auto &&tail = *( it_imu + 1 ); if ( tail->header.stamp.toSec() < last_lidar_end_time_ ) continue; angvel_avr << 0.5 * ( head->angular_velocity.x + tail->angular_velocity.x ), 0.5 * ( head->angular_velocity.y + tail->angular_velocity.y ), 0.5 * ( head->angular_velocity.z + tail->angular_velocity.z ); acc_avr << 0.5 * ( head->linear_acceleration.x + tail->linear_acceleration.x ), 0.5 * ( head->linear_acceleration.y + tail->linear_acceleration.y ), 0.5 * ( head->linear_acceleration.z + tail->linear_acceleration.z ); // #ifdef DEBUG_PRINT fout_imu << setw( 10 ) << head->header.stamp.toSec() - first_lidar_time << " " << angvel_avr.transpose() << " " << acc_avr.transpose() << endl; // #endif acc_avr = acc_avr * G_m_s2 / mean_acc.norm(); // - state_inout.ba; if ( head->header.stamp.toSec() < last_lidar_end_time_ ) { dt = tail->header.stamp.toSec() - last_lidar_end_time_; // dt = tail->header.stamp.toSec() - pcl_beg_time; } else { dt = tail->header.stamp.toSec() - head->header.stamp.toSec(); } in.acc = acc_avr; in.gyro = angvel_avr; Q.block< 3, 3 >( 0, 0 ).diagonal() = cov_gyr; Q.block< 3, 3 >( 3, 3 ).diagonal() = cov_acc; kf_state.predict( dt, Q, in ); /* save the poses at each IMU measurements */ imu_state = kf_state.get_x(); angvel_last = angvel_avr - imu_state.bg; acc_s_last = imu_state.rot * ( acc_avr - imu_state.ba ); for ( int i = 0; i < 3; i++ ) { acc_s_last[ i ] += imu_state.grav[ i ]; } double &&offs_t = tail->header.stamp.toSec() - pcl_beg_time; IMUpose.push_back( set_pose6d( offs_t, acc_s_last, angvel_last, imu_state.vel, imu_state.pos, imu_state.rot.toRotationMatrix() ) ); } /*** calculated the pos and attitude prediction at the frame-end ***/ double note = pcl_end_time > imu_end_time ? 1.0 : -1.0; dt = note * ( pcl_end_time - imu_end_time ); kf_state.predict( dt, Q, in ); imu_state = kf_state.get_x(); last_imu_ = meas.imu.back(); last_lidar_end_time_ = pcl_end_time; #ifdef DEBUG_PRINT esekfom::esekf< state_ikfom, 12, input_ikfom >::cov P = kf_state.get_P(); cout << "[ IMU Process ]: vel " << imu_state.vel.transpose() << " pos " << imu_state.pos.transpose() << " ba" << imu_state.ba.transpose() << " bg " << imu_state.bg.transpose() << endl; cout << "propagated cov: " << P.diagonal().transpose() << endl; #endif /*** undistort each lidar point (backward propagation) ***/ auto it_pcl = pcl_out.points.end() - 1; for ( auto it_kp = IMUpose.end() - 1; it_kp != IMUpose.begin(); it_kp-- ) { auto head = it_kp - 1; auto tail = it_kp; R_imu << MAT_FROM_ARRAY( head->rot ); // cout<<"head imu acc: "<<acc_imu.transpose()<<endl; vel_imu << VEC_FROM_ARRAY( head->vel ); pos_imu << VEC_FROM_ARRAY( head->pos ); acc_imu << VEC_FROM_ARRAY( tail->acc ); angvel_avr << VEC_FROM_ARRAY( tail->gyr ); for ( ; it_pcl->curvature / double( 1000 ) > head->offset_time; it_pcl-- ) { dt = it_pcl->curvature / double( 1000 ) - head->offset_time; /* Transform to the 'end' frame, using only the rotation * Note: Compensation direction is INVERSE of Frame's moving direction * So if we want to compensate a point at timestamp-i to the frame-e * P_compensate = R_imu_e ^ T * (R_i * P_i + T_ei) where T_ei is represented in global frame */ M3D R_i( R_imu * Exp( angvel_avr, dt ) ); V3D P_i( it_pcl->x, it_pcl->y, it_pcl->z ); V3D T_ei( pos_imu + vel_imu * dt + 0.5 * acc_imu * dt * dt - imu_state.pos ); V3D P_compensate = imu_state.offset_R_L_I.conjugate() * ( imu_state.rot.conjugate() * ( R_i * ( imu_state.offset_R_L_I * P_i + imu_state.offset_T_L_I ) + T_ei ) - imu_state.offset_T_L_I ); // not accurate! // save Undistorted points and their rotation it_pcl->x = P_compensate( 0 ); it_pcl->y = P_compensate( 1 ); it_pcl->z = P_compensate( 2 ); if ( it_pcl == pcl_out.points.begin() ) break; } } } #else void ImuProcess::Forward( const MeasureGroup &meas, StatesGroup &state_inout, double pcl_beg_time, double end_time ) { /*** add the imu of the last frame-tail to the of current frame-head ***/ auto v_imu = meas.imu; v_imu.push_front( last_imu_ ); const double &imu_beg_time = v_imu.front()->header.stamp.toSec(); const double &imu_end_time = v_imu.back()->header.stamp.toSec(); // cout<<"[ IMU Process ]: Process lidar from "<<pcl_beg_time<<" to "<<pcl_end_time<<", " \ // <<meas.imu.size()<<" imu msgs from "<<imu_beg_time<<" to "<<imu_end_time<<endl; // IMUpose.push_back(set_pose6d(0.0, Zero3d, Zero3d, state.vel_end, state.pos_end, state.rot_end)); if ( IMUpose.empty() ) { IMUpose.push_back( set_pose6d( 0.0, acc_s_last, angvel_last, state_inout.vel_end, state_inout.pos_end, state_inout.rot_end ) ); } /*** forward propagation at each imu point ***/ V3D acc_imu = acc_s_last, angvel_avr = angvel_last, acc_avr, vel_imu( state_inout.vel_end ), pos_imu( state_inout.pos_end ); M3D R_imu( state_inout.rot_end ); // last_state = state_inout; MD( DIM_STATE, DIM_STATE ) F_x, cov_w; double dt = 0; for ( auto it_imu = v_imu.begin(); it_imu < ( v_imu.end() - 1 ); it_imu++ ) { auto &&head = *( it_imu ); auto &&tail = *( it_imu + 1 ); if ( tail->header.stamp.toSec() < last_lidar_end_time_ ) continue; angvel_avr << 0.5 * ( head->angular_velocity.x + tail->angular_velocity.x ), 0.5 * ( head->angular_velocity.y + tail->angular_velocity.y ), 0.5 * ( head->angular_velocity.z + tail->angular_velocity.z ); // angvel_avr<<tail->angular_velocity.x, tail->angular_velocity.y, tail->angular_velocity.z; acc_avr << 0.5 * ( head->linear_acceleration.x + tail->linear_acceleration.x ), 0.5 * ( head->linear_acceleration.y + tail->linear_acceleration.y ), 0.5 * ( head->linear_acceleration.z + tail->linear_acceleration.z ); last_acc = acc_avr; last_ang = angvel_avr; // #ifdef DEBUG_PRINT fout_imu << setw( 10 ) << head->header.stamp.toSec() - first_lidar_time << " " << angvel_avr.transpose() << " " << acc_avr.transpose() << endl; // #endif angvel_avr -= state_inout.bias_g; acc_avr = acc_avr * G_m_s2 / mean_acc.norm() - state_inout.bias_a; if ( head->header.stamp.toSec() < last_lidar_end_time_ ) { dt = tail->header.stamp.toSec() - last_lidar_end_time_; } else { dt = tail->header.stamp.toSec() - head->header.stamp.toSec(); } // cout<<setw(20)<<"dt: "<<dt<<endl; /* covariance propagation */ M3D acc_avr_skew; M3D Exp_f = Exp( angvel_avr, dt ); acc_avr_skew << SKEW_SYM_MATRX( acc_avr ); F_x.setIdentity(); cov_w.setZero(); F_x.block< 3, 3 >( 0, 0 ) = Exp( angvel_avr, -dt ); F_x.block< 3, 3 >( 0, 9 ) = -Eye3d * dt; // F_x.block<3,3>(3,0) = R_imu * off_vel_skew * dt; F_x.block< 3, 3 >( 3, 6 ) = Eye3d * dt; F_x.block< 3, 3 >( 6, 0 ) = -R_imu * acc_avr_skew * dt; F_x.block< 3, 3 >( 6, 12 ) = -R_imu * dt; F_x.block< 3, 3 >( 6, 15 ) = Eye3d * dt; cov_w.block< 3, 3 >( 0, 0 ).diagonal() = cov_gyr * dt * dt; cov_w.block< 3, 3 >( 6, 6 ) = R_imu * cov_acc.asDiagonal() * R_imu.transpose() * dt * dt; cov_w.block< 3, 3 >( 9, 9 ).diagonal() = cov_bias_gyr * dt * dt; // bias gyro covariance cov_w.block< 3, 3 >( 12, 12 ).diagonal() = cov_bias_acc * dt * dt; // bias acc covariance state_inout.cov = F_x * state_inout.cov * F_x.transpose() + cov_w; /* propogation of IMU attitude */ R_imu = R_imu * Exp_f; /* Specific acceleration (global frame) of IMU */ acc_imu = R_imu * acc_avr + state_inout.gravity; /* propogation of IMU */ pos_imu = pos_imu + vel_imu * dt + 0.5 * acc_imu * dt * dt; /* velocity of IMU */ vel_imu = vel_imu + acc_imu * dt; /* save the poses at each IMU measurements */ angvel_last = angvel_avr; acc_s_last = acc_imu; double &&offs_t = tail->header.stamp.toSec() - pcl_beg_time; IMUpose.push_back( set_pose6d( offs_t, acc_imu, angvel_avr, vel_imu, pos_imu, R_imu ) ); } /*** calculated the pos and attitude prediction at the frame-end ***/ double note = end_time > imu_end_time ? 1.0 : -1.0; dt = note * ( end_time - imu_end_time ); state_inout.vel_end = vel_imu + note * acc_imu * dt; state_inout.rot_end = R_imu * Exp( V3D( note * angvel_avr ), dt ); state_inout.pos_end = pos_imu + note * vel_imu * dt + note * 0.5 * acc_imu * dt * dt; last_imu_ = v_imu.back(); last_lidar_end_time_ = end_time; // auto pos_liD_e = state_inout.pos_end + state_inout.rot_end * Lid_offset_to_IMU; // auto R_liD_e = state_inout.rot_end * Lidar_R_to_IMU; #ifdef DEBUG_PRINT cout << "[ IMU Process ]: vel " << state_inout.vel_end.transpose() << " pos " << state_inout.pos_end.transpose() << " ba" << state_inout.bias_a.transpose() << " bg " << state_inout.bias_g.transpose() << endl; cout << "propagated cov: " << state_inout.cov.diagonal().transpose() << endl; #endif } void ImuProcess::Forward_without_imu( LidarMeasureGroup &meas, StatesGroup &state_inout, PointCloudXYZI &pcl_out ) { const double &pcl_beg_time = meas.lidar_beg_time; /*** sort point clouds by offset time ***/ pcl_out = *( meas.lidar ); // sort(pcl_out->points.begin(), pcl_out->points.end(), time_list); const double &pcl_end_time = pcl_beg_time + pcl_out.points.back().curvature / double( 1000 ); // V3D acc_imu, angvel_avr, acc_avr, vel_imu(state_inout.vel_end), // pos_imu(state_inout.pos_end); // M3D R_imu(state_inout.rot_end); meas.last_update_time = pcl_end_time; MD( DIM_STATE, DIM_STATE ) F_x, cov_w; double dt = 0; if ( b_first_frame_ ) { dt = 0.1; b_first_frame_ = false; } else { dt = pcl_beg_time - time_last_scan; } // std::cout << "[No imu] dt:" << dt << std::endl; time_last_scan = pcl_beg_time; // for (size_t i = 0; i < pcl_out->points.size(); i++) { // if (dt < pcl_out->points[i].curvature) { // dt = pcl_out->points[i].curvature; // } // } // dt = dt / (double)1000; // std::cout << "dt:" << dt << std::endl; // double dt = pcl_out->points.back().curvature / double(1000); /* covariance propagation */ // M3D acc_avr_skew; M3D Exp_f = Exp( state_inout.bias_g, dt ); F_x.setIdentity(); cov_w.setZero(); F_x.block< 3, 3 >( 0, 0 ) = Exp( state_inout.bias_g, -dt ); F_x.block< 3, 3 >( 0, 9 ) = Eye3d * dt; F_x.block< 3, 3 >( 3, 6 ) = Eye3d * dt; // F_x.block<3, 3>(6, 0) = - R_imu * acc_avr_skew * dt; // F_x.block<3, 3>(6, 12) = - R_imu * dt; // F_x.block<3, 3>(6, 15) = Eye3d * dt; cov_w.block< 3, 3 >( 9, 9 ).diagonal() = cov_gyr * dt * dt; // for omega in constant model cov_w.block< 3, 3 >( 6, 6 ).diagonal() = cov_acc * dt * dt; // for velocity in constant model // cov_w.block<3, 3>(6, 6) = // R_imu * cov_acc.asDiagonal() * R_imu.transpose() * dt * dt; // cov_w.block<3, 3>(9, 9).diagonal() = // cov_bias_gyr * dt * dt; // bias gyro covariance // cov_w.block<3, 3>(12, 12).diagonal() = // cov_bias_acc * dt * dt; // bias acc covariance // std::cout << "before propagete:" << state_inout.cov.diagonal().transpose() // << std::endl; state_inout.cov = F_x * state_inout.cov * F_x.transpose() + cov_w; // std::cout << "cov_w:" << cov_w.diagonal().transpose() << std::endl; // std::cout << "after propagete:" << state_inout.cov.diagonal().transpose() // << std::endl; state_inout.rot_end = state_inout.rot_end * Exp_f; state_inout.pos_end = state_inout.pos_end + state_inout.vel_end * dt; } void ImuProcess::Backward( const LidarMeasureGroup &lidar_meas, StatesGroup &state_inout, PointCloudXYZI &pcl_out ) { /*** undistort each lidar point (backward propagation) ***/ M3D R_imu; V3D acc_imu, angvel_avr, vel_imu, pos_imu; double dt; auto pos_liD_e = state_inout.pos_end + state_inout.rot_end * Lid_offset_to_IMU; auto it_pcl = pcl_out.points.end() - 1; for ( auto it_kp = IMUpose.end() - 1; it_kp != IMUpose.begin(); it_kp-- ) { auto head = it_kp - 1; auto tail = it_kp; R_imu << MAT_FROM_ARRAY( head->rot ); acc_imu << VEC_FROM_ARRAY( head->acc ); // cout<<"head imu acc: "<<acc_imu.transpose()<<endl; vel_imu << VEC_FROM_ARRAY( head->vel ); pos_imu << VEC_FROM_ARRAY( head->pos ); angvel_avr << VEC_FROM_ARRAY( head->gyr ); for ( ; it_pcl->curvature / double( 1000 ) > head->offset_time; it_pcl-- ) { dt = it_pcl->curvature / double( 1000 ) - head->offset_time; /* Transform to the 'end' frame, using only the rotation * Note: Compensation direction is INVERSE of Frame's moving direction * So if we want to compensate a point at timestamp-i to the frame-e * P_compensate = R_imu_e ^ T * (R_i * P_i + T_ei) where T_ei is represented in global frame */ M3D R_i( R_imu * Exp( angvel_avr, dt ) ); V3D T_ei( pos_imu + vel_imu * dt + 0.5 * acc_imu * dt * dt + R_i * Lid_offset_to_IMU - pos_liD_e ); V3D P_i( it_pcl->x, it_pcl->y, it_pcl->z ); V3D P_compensate = state_inout.rot_end.transpose() * ( R_i * P_i + T_ei ); /// save Undistorted points and their rotation it_pcl->x = P_compensate( 0 ); it_pcl->y = P_compensate( 1 ); it_pcl->z = P_compensate( 2 ); if ( it_pcl == pcl_out.points.begin() ) break; } } } #endif #ifdef USE_IKFOM void ImuProcess::Process( const LidarMeasureGroup &lidar_meas, esekfom::esekf< state_ikfom, 12, input_ikfom > &kf_state, PointCloudXYZI::Ptr cur_pcl_un_ ) { double t1, t2, t3; t1 = omp_get_wtime(); MeasureGroup meas = lidar_meas.measures.back(); if ( meas.imu.empty() ) { return; }; ROS_ASSERT( meas.lidar != nullptr ); if ( imu_need_init_ ) { /// The very first lidar frame IMU_init( meas, kf_state, init_iter_num ); imu_need_init_ = true; last_imu_ = meas.imu.back(); state_ikfom imu_state = kf_state.get_x(); if ( init_iter_num > MAX_INI_COUNT ) { cov_acc *= pow( G_m_s2 / mean_acc.norm(), 2 ); imu_need_init_ = false; ROS_INFO( "IMU Initials: Gravity: %.4f %.4f %.4f %.4f; state.bias_g: %.4f %.4f %.4f; acc covarience: %.8f %.8f %.8f; gry covarience: " "%.8f %.8f %.8f", imu_state.grav[ 0 ], imu_state.grav[ 1 ], imu_state.grav[ 2 ], mean_acc.norm(), cov_acc_scale[ 0 ], cov_acc_scale[ 1 ], cov_acc_scale[ 2 ], cov_acc[ 0 ], cov_acc[ 1 ], cov_acc[ 2 ], cov_gyr[ 0 ], cov_gyr[ 1 ], cov_gyr[ 2 ] ); cov_acc = cov_acc.cwiseProduct( cov_acc_scale ); cov_gyr = cov_gyr.cwiseProduct( cov_gyr_scale ); // cout<<"mean acc: "<<mean_acc<<" acc measures in word frame:"<<state.rot_end.transpose()*mean_acc<<endl; ROS_INFO( "IMU Initials: Gravity: %.4f %.4f %.4f %.4f; state.bias_g: %.4f %.4f %.4f; acc covarience: %.8f %.8f %.8f; gry covarience: " "%.8f %.8f %.8f", imu_state.grav[ 0 ], imu_state.grav[ 1 ], imu_state.grav[ 2 ], mean_acc.norm(), cov_bias_gyr[ 0 ], cov_bias_gyr[ 1 ], cov_bias_gyr[ 2 ], cov_acc[ 0 ], cov_acc[ 1 ], cov_acc[ 2 ], cov_gyr[ 0 ], cov_gyr[ 1 ], cov_gyr[ 2 ] ); fout_imu.open( DEBUG_FILE_DIR( "imu.txt" ), ios::out ); } return; } /// Undistort points: the first point is assummed as the base frame /// Compensate lidar points with IMU rotation (with only rotation now) if ( lidar_meas.is_lidar_end ) { UndistortPcl( lidar_meas, kf_state, *cur_pcl_un_ ); } t2 = omp_get_wtime(); // { // static ros::Publisher pub_UndistortPcl = // nh.advertise<sensor_msgs::PointCloud2>("/livox_undistort", 100); // sensor_msgs::PointCloud2 pcl_out_msg; // pcl::toROSMsg(*cur_pcl_un_, pcl_out_msg); // pcl_out_msg.header.stamp = ros::Time().fromSec(meas.lidar_beg_time); // pcl_out_msg.header.frame_id = "/livox"; // pub_UndistortPcl.publish(pcl_out_msg); // } t3 = omp_get_wtime(); // cout<<"[ IMU Process ]: Time: "<<t3 - t1<<endl; } #else void ImuProcess::Process( LidarMeasureGroup &lidar_meas, StatesGroup &stat, PointCloudXYZI::Ptr cur_pcl_un_ ) { double t1, t2, t3; t1 = omp_get_wtime(); ROS_ASSERT( lidar_meas.lidar != nullptr ); MeasureGroup meas = lidar_meas.measures.back(); if ( imu_need_init_ ) { if ( meas.imu.empty() ) { return; }; /// The very first lidar frame IMU_init( meas, stat, init_iter_num ); imu_need_init_ = true; last_imu_ = meas.imu.back(); if ( init_iter_num > MAX_INI_COUNT ) { cov_acc *= pow( G_m_s2 / mean_acc.norm(), 2 ); imu_need_init_ = false; ROS_INFO( "IMU Initials: Gravity: %.4f %.4f %.4f %.4f; acc covarience: %.8f %.8f %.8f; gry covarience: %.8f %.8f %.8f", stat.gravity[ 0 ], stat.gravity[ 1 ], stat.gravity[ 2 ], mean_acc.norm(), cov_acc[ 0 ], cov_acc[ 1 ], cov_acc[ 2 ], cov_gyr[ 0 ], cov_gyr[ 1 ], cov_gyr[ 2 ] ); // cout<<"mean acc: "<<mean_acc<<" acc measures in word frame:"<<state.rot_end.transpose()*mean_acc<<endl; fout_imu.open( DEBUG_FILE_DIR( "imu.txt" ), ios::out ); } return; } /// Undistort points: the first point is assummed as the base frame /// Compensate lidar points with IMU rotation (with only rotation now) if ( lidar_meas.is_lidar_end ) { /*** sort point clouds by offset time ***/ *cur_pcl_un_ = *( lidar_meas.lidar ); sort( cur_pcl_un_->points.begin(), cur_pcl_un_->points.end(), time_list ); const double &pcl_beg_time = lidar_meas.lidar_beg_time; const double &pcl_end_time = pcl_beg_time + lidar_meas.lidar->points.back().curvature / double( 1000 ); if ( imu_en ) { Forward( meas, stat, pcl_beg_time, pcl_end_time ); Backward( lidar_meas, stat, *cur_pcl_un_ ); last_lidar_end_time_ = pcl_end_time; IMUpose.clear(); } else { Forward_without_imu( lidar_meas, stat, *cur_pcl_un_ ); } // cout<<"[ IMU Process ]: Process lidar from "<<pcl_beg_time<<" to "<<pcl_end_time<<", " \ // <<meas.imu.size()<<" imu msgs from "<<imu_beg_time<<" to "<<imu_end_time<<endl; // cout<<"Time:"; // for (auto it = IMUpose.begin(); it != IMUpose.end(); ++it) { // cout<<it->offset_time<<" "; // } // cout<<endl<<"size:"<<IMUpose.size()<<endl; } else { const double &pcl_beg_time = lidar_meas.lidar_beg_time; const double &img_end_time = pcl_beg_time + meas.img_offset_time; Forward( meas, stat, pcl_beg_time, img_end_time ); } t2 = omp_get_wtime(); // { // static ros::Publisher pub_UndistortPcl = // nh.advertise<sensor_msgs::PointCloud2>("/livox_undistort", 100); // sensor_msgs::PointCloud2 pcl_out_msg; // pcl::toROSMsg(*cur_pcl_un_, pcl_out_msg); // pcl_out_msg.header.stamp = ros::Time().fromSec(meas.lidar_beg_time); // pcl_out_msg.header.frame_id = "/livox"; // pub_UndistortPcl.publish(pcl_out_msg); // } t3 = omp_get_wtime(); // cout<<"[ IMU Process ]: Time: "<<t3 - t1<<endl; } void ImuProcess::UndistortPcl( LidarMeasureGroup &lidar_meas, StatesGroup &state_inout, PointCloudXYZI &pcl_out ) { /*** add the imu of the last frame-tail to the of current frame-head ***/ MeasureGroup meas; meas = lidar_meas.measures.back(); auto v_imu = meas.imu; v_imu.push_front( last_imu_ ); const double &imu_beg_time = v_imu.front()->header.stamp.toSec(); const double &imu_end_time = v_imu.back()->header.stamp.toSec(); const double pcl_beg_time = MAX( lidar_meas.lidar_beg_time, lidar_meas.last_update_time ); // const double &pcl_beg_time = meas.lidar_beg_time; /*** sort point clouds by offset time ***/ // pcl_out.clear(); // auto pcl_it = lidar_meas.lidar->points.begin() + lidar_meas.lidar_scan_index_now; // auto pcl_it_end = lidar_meas.lidar->points.end(); // const double pcl_end_time = lidar_meas.is_lidar_end ? lidar_meas.lidar_beg_time + lidar_meas.lidar->points.back().curvature / double( 1000 ) // : lidar_meas.lidar_beg_time + lidar_meas.measures.back().img_offset_time; // // std::cout << "pcl end time:" << pcl_end_time << " pcl beg time:" << lidar_meas.lidar_beg_time << std::endl; // const double pcl_offset_time = ( pcl_end_time - lidar_meas.lidar_beg_time ) * double( 1000 ); // while ( pcl_it != pcl_it_end && pcl_it->curvature <= pcl_offset_time ) // { // pcl_out.push_back( *pcl_it ); // pcl_it++; // lidar_meas.lidar_scan_index_now++; // } // cout << "pcl_offset_time: " << pcl_offset_time << " pcl_it->curvature: " << pcl_it->curvature << endl; // cout << "lidar_meas.lidar_scan_index_now:" << lidar_meas.lidar_scan_index_now << endl; pcl_out = *( lidar_meas.lidar ); sort( pcl_out.points.begin(), pcl_out.points.end(), time_list ); const double pcl_end_time = lidar_meas.is_lidar_end ? lidar_meas.lidar_beg_time + lidar_meas.lidar->points.back().curvature / double( 1000 ) : lidar_meas.lidar_beg_time + lidar_meas.measures.back().img_offset_time; lidar_meas.last_update_time = pcl_end_time; if ( lidar_meas.is_lidar_end ) { lidar_meas.lidar_scan_index_now = 0; } // sort(pcl_out.points.begin(), pcl_out.points.end(), time_list); // lidar_meas.debug_show(); // cout<<"UndistortPcl [ IMU Process ]: Process lidar from "<<pcl_beg_time<<" to "<<pcl_end_time<<", " \ // <<meas.imu.size()<<" imu msgs from "<<imu_beg_time<<" to "<<imu_end_time<<endl; // cout<<"[ IMU Process ]: point size: "<<lidar_meas.lidar->points.size()<<endl; /*** Initialize IMU pose ***/ IMUpose.clear(); // IMUpose.push_back(set_pose6d(0.0, Zero3d, Zero3d, state.vel_end, state.pos_end, state.rot_end)); IMUpose.push_back( set_pose6d( 0.0, acc_s_last, angvel_last, state_inout.vel_end, state_inout.pos_end, state_inout.rot_end ) ); /*** forward propagation at each imu point ***/ V3D acc_imu( acc_s_last ), angvel_avr( angvel_last ), acc_avr, vel_imu( state_inout.vel_end ), pos_imu( state_inout.pos_end ); M3D R_imu( state_inout.rot_end ); MD( DIM_STATE, DIM_STATE ) F_x, cov_w; double dt = 0; for ( auto it_imu = v_imu.begin(); it_imu != v_imu.end() - 1; it_imu++ ) { auto &&head = *( it_imu ); auto &&tail = *( it_imu + 1 ); if ( tail->header.stamp.toSec() < last_lidar_end_time_ ) continue; angvel_avr << 0.5 * ( head->angular_velocity.x + tail->angular_velocity.x ), 0.5 * ( head->angular_velocity.y + tail->angular_velocity.y ), 0.5 * ( head->angular_velocity.z + tail->angular_velocity.z ); // angvel_avr<<tail->angular_velocity.x, tail->angular_velocity.y, tail->angular_velocity.z; acc_avr << 0.5 * ( head->linear_acceleration.x + tail->linear_acceleration.x ), 0.5 * ( head->linear_acceleration.y + tail->linear_acceleration.y ), 0.5 * ( head->linear_acceleration.z + tail->linear_acceleration.z ); // #ifdef DEBUG_PRINT fout_imu << setw( 10 ) << head->header.stamp.toSec() - first_lidar_time << " " << angvel_avr.transpose() << " " << acc_avr.transpose() << endl; // #endif angvel_avr -= state_inout.bias_g; acc_avr = acc_avr * G_m_s2 / mean_acc.norm() - state_inout.bias_a; if ( head->header.stamp.toSec() < last_lidar_end_time_ ) { dt = tail->header.stamp.toSec() - last_lidar_end_time_; } else { dt = tail->header.stamp.toSec() - head->header.stamp.toSec(); } /* covariance propagation */ M3D acc_avr_skew; M3D Exp_f = Exp( angvel_avr, dt ); acc_avr_skew << SKEW_SYM_MATRX( acc_avr ); F_x.setIdentity(); cov_w.setZero(); F_x.block< 3, 3 >( 0, 0 ) = Exp( angvel_avr, -dt ); F_x.block< 3, 3 >( 0, 9 ) = -Eye3d * dt; // F_x.block<3,3>(3,0) = R_imu * off_vel_skew * dt; F_x.block< 3, 3 >( 3, 6 ) = Eye3d * dt; F_x.block< 3, 3 >( 6, 0 ) = -R_imu * acc_avr_skew * dt; F_x.block< 3, 3 >( 6, 12 ) = -R_imu * dt; F_x.block< 3, 3 >( 6, 15 ) = Eye3d * dt; cov_w.block< 3, 3 >( 0, 0 ).diagonal() = cov_gyr * dt * dt; cov_w.block< 3, 3 >( 6, 6 ) = R_imu * cov_acc.asDiagonal() * R_imu.transpose() * dt * dt; cov_w.block< 3, 3 >( 9, 9 ).diagonal() = cov_bias_gyr * dt * dt; // bias gyro covariance cov_w.block< 3, 3 >( 12, 12 ).diagonal() = cov_bias_acc * dt * dt; // bias acc covariance state_inout.cov = F_x * state_inout.cov * F_x.transpose() + cov_w; /* propogation of IMU attitude */ R_imu = R_imu * Exp_f; /* Specific acceleration (global frame) of IMU */ acc_imu = R_imu * acc_avr + state_inout.gravity; /* propogation of IMU */ pos_imu = pos_imu + vel_imu * dt + 0.5 * acc_imu * dt * dt; /* velocity of IMU */ vel_imu = vel_imu + acc_imu * dt; /* save the poses at each IMU measurements */ angvel_last = angvel_avr; acc_s_last = acc_imu; double &&offs_t = tail->header.stamp.toSec() - pcl_beg_time; // cout<<setw(20)<<"offset_t: "<<offs_t<<"tail->header.stamp.toSec(): "<<tail->header.stamp.toSec()<<endl; IMUpose.push_back( set_pose6d( offs_t, acc_imu, angvel_avr, vel_imu, pos_imu, R_imu ) ); } /*** calculated the pos and attitude prediction at the frame-end ***/ if ( imu_end_time > pcl_beg_time ) { double note = pcl_end_time > imu_end_time ? 1.0 : -1.0; dt = note * ( pcl_end_time - imu_end_time ); state_inout.vel_end = vel_imu + note * acc_imu * dt; state_inout.rot_end = R_imu * Exp( V3D( note * angvel_avr ), dt ); state_inout.pos_end = pos_imu + note * vel_imu * dt + note * 0.5 * acc_imu * dt * dt; } else { double note = pcl_end_time > pcl_beg_time ? 1.0 : -1.0; dt = note * ( pcl_end_time - pcl_beg_time ); state_inout.vel_end = vel_imu + note * acc_imu * dt; state_inout.rot_end = R_imu * Exp( V3D( note * angvel_avr ), dt ); state_inout.pos_end = pos_imu + note * vel_imu * dt + note * 0.5 * acc_imu * dt * dt; } last_imu_ = v_imu.back(); last_lidar_end_time_ = pcl_end_time; // auto pos_liD_e = state_inout.pos_end + state_inout.rot_end * Lid_offset_to_IMU; // auto R_liD_e = state_inout.rot_end * Lidar_R_to_IMU; // cout<<"[ IMU Process ]: vel "<<state_inout.vel_end.transpose()<<" pos "<<state_inout.pos_end.transpose()<<" // ba"<<state_inout.bias_a.transpose()<<" bg "<<state_inout.bias_g.transpose()<<endl; cout<<"propagated cov: // "<<state_inout.cov.diagonal().transpose()<<endl; // cout<<"UndistortPcl Time:"; // for (auto it = IMUpose.begin(); it != IMUpose.end(); ++it) { // cout<<it->offset_time<<" "; // } // cout<<endl<<"UndistortPcl size:"<<IMUpose.size()<<endl; // cout<<"Undistorted pcl_out.size: "<<pcl_out.size() // <<"lidar_meas.size: "<<lidar_meas.lidar->points.size()<<endl; if ( pcl_out.points.size() < 1 ) return; /*** undistort each lidar point (backward propagation) ***/ auto it_pcl = pcl_out.points.end() - 1; // cout << __FILE__ << " " << __LINE__ << " " << __FUNCTION__ << " " << it_pcl->curvature << endl; // cout << "R mat :\r\n" << Lid_rot_to_IMU << endl; for ( auto it_kp = IMUpose.end() - 1; it_kp != IMUpose.begin(); it_kp-- ) { auto head = it_kp - 1; auto tail = it_kp; R_imu << MAT_FROM_ARRAY( head->rot ); acc_imu << VEC_FROM_ARRAY( head->acc ); // cout<<"head imu acc: "<<acc_imu.transpose()<<endl; vel_imu << VEC_FROM_ARRAY( head->vel ); pos_imu << VEC_FROM_ARRAY( head->pos ); angvel_avr << VEC_FROM_ARRAY( head->gyr ); for ( ; it_pcl->curvature / double( 1000 ) > head->offset_time; it_pcl-- ) { dt = it_pcl->curvature / double( 1000 ) - head->offset_time; /* Transform to the 'end' frame */ M3D R_i( R_imu * Exp( angvel_avr, dt ) ); V3D T_ei( pos_imu + vel_imu * dt + 0.5 * acc_imu * dt * dt - state_inout.pos_end ); V3D P_i( it_pcl->x, it_pcl->y, it_pcl->z ); V3D P_compensate = Lid_rot_to_IMU.transpose() * ( state_inout.rot_end.transpose() * ( R_i * ( Lid_rot_to_IMU * P_i + Lid_offset_to_IMU ) + T_ei ) - Lid_offset_to_IMU ); /// save Undistorted points and their rotation it_pcl->x = P_compensate( 0 ); it_pcl->y = P_compensate( 1 ); it_pcl->z = P_compensate( 2 ); if ( it_pcl == pcl_out.points.begin() ) break; } } // cout<<"[ IMU Process ]: undistort size: "<<pcl_out.points.size()<<endl; } void ImuProcess::Process2( LidarMeasureGroup &lidar_meas, StatesGroup &stat, PointCloudXYZI::Ptr cur_pcl_un_ ) { double t1, t2, t3; t1 = omp_get_wtime(); ROS_ASSERT( lidar_meas.lidar != nullptr ); if ( !imu_en ) { Forward_without_imu( lidar_meas, stat, *cur_pcl_un_ ); return; } MeasureGroup meas = lidar_meas.measures.back(); if ( imu_need_init_ ) { double pcl_end_time = lidar_meas.is_lidar_end ? lidar_meas.lidar_beg_time + lidar_meas.lidar->points.back().curvature / double( 1000 ) : lidar_meas.lidar_beg_time + lidar_meas.measures.back().img_offset_time; lidar_meas.last_update_time = pcl_end_time; if ( meas.imu.empty() ) { return; }; /// The very first lidar frame IMU_init( meas, stat, init_iter_num ); imu_need_init_ = true; last_imu_ = meas.imu.back(); if ( init_iter_num > MAX_INI_COUNT ) { // cov_acc *= pow(G_m_s2 / mean_acc.norm(), 2); imu_need_init_ = false; ROS_INFO( "IMU Initials: Gravity: %.4f %.4f %.4f %.4f; acc covarience: %.8f %.8f %.8f; gry covarience: %.8f %.8f %.8f \n", stat.gravity[ 0 ], stat.gravity[ 1 ], stat.gravity[ 2 ], mean_acc.norm(), cov_acc[ 0 ], cov_acc[ 1 ], cov_acc[ 2 ], cov_gyr[ 0 ], cov_gyr[ 1 ], cov_gyr[ 2 ] ); ROS_INFO( "IMU Initials: ba covarience: %.8f %.8f %.8f; bg covarience: %.8f %.8f %.8f", cov_bias_acc[ 0 ], cov_bias_acc[ 1 ], cov_bias_acc[ 2 ], cov_bias_gyr[ 0 ], cov_bias_gyr[ 1 ], cov_bias_gyr[ 2 ] ); fout_imu.open( DEBUG_FILE_DIR( "imu.txt" ), ios::out ); } return; } UndistortPcl( lidar_meas, stat, *cur_pcl_un_ ); } #endif
C++
3D
hku-mars/ImMesh
src/preprocess.h
.h
7,511
196
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "common_lib.h" #include <ros/ros.h> #include <pcl_conversions/pcl_conversions.h> #include <sensor_msgs/PointCloud2.h> #include <livox_ros_driver/CustomMsg.h> using namespace std; #define IS_VALID( a ) ( ( abs( a ) > 1e8 ) ? true : false ) // enum LID_TYPE{AVIA = 1, VELO16, OUST64, L515}; //{1, 2, 3} enum Feature { Nor, Poss_Plane, Real_Plane, Edge_Jump, Edge_Plane, Wire, ZeroPoint }; enum Surround { Prev, Next }; enum E_jump { Nr_nor, Nr_zero, Nr_180, Nr_inf, Nr_blind }; struct orgtype { double range; double dista; double angle[ 2 ]; double intersect; E_jump edj[ 2 ]; Feature ftype; orgtype() { range = 0; edj[ Prev ] = Nr_nor; edj[ Next ] = Nr_nor; ftype = Nor; intersect = 2; } }; /*** Velodyne ***/ namespace velodyne_ros { struct EIGEN_ALIGN16 Point { PCL_ADD_POINT4D; float intensity; float time; uint16_t ring; EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; } // namespace velodyne_ros POINT_CLOUD_REGISTER_POINT_STRUCT( velodyne_ros::Point, ( float, x, x )( float, y, y )( float, z, z )( float, intensity, intensity )( float, time, time )( uint16_t, ring, ring ) ) /****************/ /*** Ouster ***/ namespace ouster_ros { struct EIGEN_ALIGN16 Point { PCL_ADD_POINT4D; float intensity; uint32_t t; uint16_t reflectivity; uint8_t ring; uint16_t ambient; uint32_t range; EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; } // namespace ouster_ros POINT_CLOUD_REGISTER_POINT_STRUCT( ouster_ros::Point, ( float, x, x )( float, y, y )( float, z, z )( float, intensity, intensity ) // use std::uint32_t to avoid conflicting with pcl::uint32_t ( std::uint32_t, t, t )( std::uint16_t, reflectivity, reflectivity )( std::uint8_t, ring, ring )( std::uint16_t, ambient, ambient )( std::uint32_t, range, range ) ) /****************/ /*** Hesai_XT32 ***/ namespace xt32_ros { struct EIGEN_ALIGN16 Point { PCL_ADD_POINT4D; float intensity; double timestamp; uint16_t ring; EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; } // namespace xt32_ros POINT_CLOUD_REGISTER_POINT_STRUCT( xt32_ros::Point, ( float, x, x )( float, y, y )( float, z, z )( float, intensity, intensity )( double, timestamp, timestamp )( uint16_t, ring, ring ) ) /*****************/ class Preprocess { public: // EIGEN_MAKE_ALIGNED_OPERATOR_NEW Preprocess(); ~Preprocess(); void process( const livox_ros_driver::CustomMsg::ConstPtr &msg, PointCloudXYZI::Ptr &pcl_out ); void process( const sensor_msgs::PointCloud2::ConstPtr &msg, PointCloudXYZI::Ptr &pcl_out ); void set( bool feat_en, int lid_type, double bld, int pfilt_num ); // sensor_msgs::PointCloud2::ConstPtr pointcloud; PointCloudXYZI pl_full, pl_corn, pl_surf; PointCloudXYZI pl_buff[ 128 ]; // maximum 128 line lidar vector< orgtype > typess[ 128 ]; // maximum 128 line lidar int lidar_type, point_filter_num, N_SCANS, time_unit; double blind, blind_sqr; double time_unit_scale; bool feature_enabled, given_offset_time, calib_laser; ros::Publisher pub_full, pub_surf, pub_corn; private: void avia_handler( const livox_ros_driver::CustomMsg::ConstPtr &msg ); void oust64_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ); void velodyne_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ); void velodyne32_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ); void xt32_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ); void l515_handler( const sensor_msgs::PointCloud2::ConstPtr &msg ); void give_feature( PointCloudXYZI &pl, vector< orgtype > &types ); void pub_func( PointCloudXYZI &pl, const ros::Time &ct ); int plane_judge( const PointCloudXYZI &pl, vector< orgtype > &types, uint i, uint &i_nex, Eigen::Vector3d &curr_direct ); bool small_plane( const PointCloudXYZI &pl, vector< orgtype > &types, uint i_cur, uint &i_nex, Eigen::Vector3d &curr_direct ); bool edge_jump_judge( const PointCloudXYZI &pl, vector< orgtype > &types, uint i, Surround nor_dir ); int group_size; double disA, disB, inf_bound; double limit_maxmid, limit_midmin, limit_maxmin; double p2l_ratio; double jump_up_limit, jump_down_limit; double cos160; double edgea, edgeb; double smallp_intersect, smallp_ratio; double vx, vy, vz; };
Unknown
3D
hku-mars/ImMesh
src/IMU_Processing.h
.h
6,126
153
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef IMU_PROCESSING_H #define IMU_PROCESSING_H #include <cmath> #include <math.h> #include <deque> #include <mutex> #include <thread> #include <fstream> #include <csignal> #include <ros/ros.h> #include <so3_math.h> #include <Eigen/Eigen> #include <common_lib.h> #include <pcl/common/io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <condition_variable> #include <nav_msgs/Odometry.h> #include <pcl/common/transforms.h> #include <pcl/kdtree/kdtree_flann.h> #include <tf/transform_broadcaster.h> #include <eigen_conversions/eigen_msg.h> #include <pcl_conversions/pcl_conversions.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/PointCloud2.h> // #include <fast_lio/States.h> #include <geometry_msgs/Vector3.h> #ifdef USE_IKFOM #include "use-ikfom.hpp" #endif /// *************Preconfiguration // #define MAX_INI_COUNT (10) const bool time_list(PointType &x, PointType &y); //{return (x.curvature < y.curvature);}; /// *************IMU Process and undistortion class ImuProcess { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW ImuProcess(); ~ImuProcess(); void Reset(); void Reset(double start_timestamp, const sensor_msgs::ImuConstPtr &lastimu); void push_update_state(double offs_t, StatesGroup state); void set_extrinsic(const V3D &transl, const M3D &rot); void set_extrinsic(const V3D &transl); void set_extrinsic(const MD(4,4) &T); void set_gyr_cov_scale(const V3D &scaler); void set_acc_cov_scale(const V3D &scaler); void set_gyr_bias_cov(const V3D &b_g); void set_acc_bias_cov(const V3D &b_a); void set_imu_init_frame_num(const int &num); void disable_imu(); #ifdef USE_IKFOM Eigen::Matrix<double, 12, 12> Q; void Process(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, PointCloudXYZI::Ptr pcl_un_); #else void Process(LidarMeasureGroup &lidar_meas, StatesGroup &stat, PointCloudXYZI::Ptr cur_pcl_un_); void Process2(LidarMeasureGroup &lidar_meas, StatesGroup &stat, PointCloudXYZI::Ptr cur_pcl_un_); void UndistortPcl(LidarMeasureGroup &lidar_meas, StatesGroup &state_inout, PointCloudXYZI &pcl_out); #endif ros::NodeHandle nh; ofstream fout_imu; V3D cov_acc; V3D cov_gyr; V3D cov_acc_scale; V3D cov_gyr_scale; V3D cov_bias_gyr; V3D cov_bias_acc; double first_lidar_time; private: #ifdef USE_IKFOM void IMU_init(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, int &N); void UndistortPcl(const MeasureGroup &meas, esekfom::esekf<state_ikfom, 12, input_ikfom> &kf_state, PointCloudXYZI &pcl_in_out); #else void IMU_init(const MeasureGroup &meas, StatesGroup &state, int &N); // void UndistortPcl(const MeasureGroup &meas, StatesGroup &state_inout, PointCloudXYZI &pcl_in_out); void Forward(const MeasureGroup &meas, StatesGroup &state_inout, double pcl_beg_time, double end_time); void Backward(const LidarMeasureGroup &lidar_meas, StatesGroup &state_inout, PointCloudXYZI &pcl_out); void Forward_without_imu(LidarMeasureGroup &meas, StatesGroup &state_inout, PointCloudXYZI &pcl_out); #endif PointCloudXYZI::Ptr cur_pcl_un_; sensor_msgs::ImuConstPtr last_imu_; // StatesGroup last_state; deque<sensor_msgs::ImuConstPtr> v_imu_; vector<Pose6D> IMUpose; vector<M3D> v_rot_pcl_; M3D Lid_rot_to_IMU; V3D Lid_offset_to_IMU; V3D mean_acc; V3D mean_gyr; V3D angvel_last; V3D acc_s_last; V3D last_acc; V3D last_ang; double start_timestamp_; double last_lidar_end_time_; double time_last_scan; int init_iter_num = 1, MAX_INI_COUNT = 3; bool b_first_frame_ = true; bool imu_need_init_ = true; bool imu_en = true; }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/stb_image.h
.h
254,334
7,196
/* stb_image - v2.14 - public domain image loader - http://nothings.org/stb_image.h no warranty implied; use at your own risk Do this: #define STB_IMAGE_IMPLEMENTATION before you include this file in *one* C or C++ file to create the implementation. // i.e. it should look like this: #include ... #include ... #include ... #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) PNG 1/2/4/8-bit-per-channel (16 bpc not supported) TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE PSD (composited view only, no extra channels, 8/16 bit-per-channel) GIF (*comp always reports as 4-channel) HDR (radiance rgbE format) PIC (Softimage PIC) PNM (PPM and PGM binary only) Animated GIF still needs a proper API, but here's one way to do it: http://gist.github.com/urraka/685d9a6340b26b830d49 - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - decode from arbitrary I/O callbacks - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) Full documentation under "DOCUMENTATION" below. Revision 2.00 release notes: - Progressive JPEG is now supported. - PPM and PGM binary formats are now supported, thanks to Ken Miller. - x86 platforms now make use of SSE2 SIMD instructions for JPEG decoding, and ARM platforms can use NEON SIMD if requested. This work was done by Fabian "ryg" Giesen. SSE2 is used by default, but NEON must be enabled explicitly; see docs. With other JPEG optimizations included in this version, we see 2x speedup on a JPEG on an x86 machine, and a 1.5x speedup on a JPEG on an ARM machine, relative to previous versions of this library. The same results will not obtain for all JPGs and for all x86/ARM machines. (Note that progressive JPEGs are significantly slower to decode than regular JPEGs.) This doesn't mean that this is the fastest JPEG decoder in the land; rather, it brings it closer to parity with standard libraries. If you want the fastest decode, look elsewhere. (See "Philosophy" section of docs below.) See final bullet items below for more info on SIMD. - Added STBI_MALLOC, STBI_REALLOC, and STBI_FREE macros for replacing the memory allocator. Unlike other STBI libraries, these macros don't support a context parameter, so if you need to pass a context in to the allocator, you'll have to store it in a global or a thread-local variable. - Split existing STBI_NO_HDR flag into two flags, STBI_NO_HDR and STBI_NO_LINEAR. STBI_NO_HDR: suppress implementation of .hdr reader format STBI_NO_LINEAR: suppress high-dynamic-range light-linear float API - You can suppress implementation of any of the decoders to reduce your code footprint by #defining one or more of the following symbols before creating the implementation. STBI_NO_JPEG STBI_NO_PNG STBI_NO_BMP STBI_NO_PSD STBI_NO_TGA STBI_NO_GIF STBI_NO_HDR STBI_NO_PIC STBI_NO_PNM (.ppm and .pgm) - You can request *only* certain decoders and suppress all other ones (this will be more forward-compatible, as addition of new decoders doesn't require you to disable them explicitly): STBI_ONLY_JPEG STBI_ONLY_PNG STBI_ONLY_BMP STBI_ONLY_PSD STBI_ONLY_TGA STBI_ONLY_GIF STBI_ONLY_HDR STBI_ONLY_PIC STBI_ONLY_PNM (.ppm and .pgm) Note that you can define multiples of these, and you will get all of them ("only x" and "only y" is interpreted to mean "only x&y"). - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB - Compilation of all SIMD code can be suppressed with #define STBI_NO_SIMD It should not be necessary to disable SIMD unless you have issues compiling (e.g. using an x86 compiler which doesn't support SSE intrinsics or that doesn't support the method used to detect SSE2 support at run-time), and even those can be reported as bugs so I can refine the built-in compile-time checking to be smarter. - The old STBI_SIMD system which allowed installing a user-defined IDCT etc. has been removed. If you need this, don't upgrade. My assumption is that almost nobody was doing this, and those who were will find the built-in SIMD more satisfactory anyway. - RGB values computed for JPEG images are slightly different from previous versions of stb_image. (This is due to using less integer precision in SIMD.) The C code has been adjusted so that the same RGB values will be computed regardless of whether SIMD support is available, so your app should always produce consistent results. But these results are slightly different from previous versions. (Specifically, about 3% of available YCbCr values will compute different RGB results from pre-1.49 versions by +-1; most of the deviating values are one smaller in the G channel.) - If you must produce consistent results with previous versions of stb_image, #define STBI_JPEG_OLD and you will get the same results you used to; however, you will not get the SIMD speedups for the YCbCr-to-RGB conversion step (although you should still see significant JPEG speedup from the other changes). Please note that STBI_JPEG_OLD is a temporary feature; it will be removed in future versions of the library. It is only intended for near-term back-compatibility use. Latest revision history: 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 RGB-format JPEG; remove white matting in PSD; allocate large structures on the stack; correct channel count for PNG & BMP 2.10 (2016-01-22) avoid warning introduced in 2.09 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) partial animated GIF support limited 16-bit PSD support minor bugs, code cleanup, and compiler warnings See end of file for full revision history. ============================ Contributors ========================= Image formats Extensions, features Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) github:urraka (animated gif) Junggon Kim (PNM comments) Daniel Gibson (16-bit TGA) socks-the-fox (16-bit TGA) Optimizations & bugfixes Fabian "ryg" Giesen Arseny Kapoulkine Bug & warning fixes Marc LeBlanc David Woo Guillaume George Martins Mozeiko Christpher Lloyd Martin Golini Jerry Jansson Joseph Thomson Dave Moore Roy Eltham Hayaki Saito Phil Jordan Won Chun Luke Graham Johan Duparc Nathan Reed the Horde3D community Thomas Ruf Ronny Chevalier Nick Verigakis Janez Zemva John Bartholomew Michal Cichon github:svdijk Jonathan Blow Ken Hamada Tero Hanninen Baldur Karlsson Laurent Gomila Cort Stratton Sergio Gonzalez github:romigrou Aruelien Pocheville Thibault Reuille Cass Everitt Matthew Gregan Ryamond Barbiero Paul Du Bois Engin Manap github:snagar Michaelangel007@github Oriol Ferrer Mesia Dale Weiler github:Zelex Philipp Wiesemann Josh Tobin github:rlyeh github:grim210@github Blazej Dariusz Roszkowski github:sammyhw LICENSE This software is dual-licensed to the public domain and under the following license: you are granted a perpetual, irrevocable license to copy, modify, publish, and distribute this file as you see fit. */ #ifndef STBI_INCLUDE_STB_IMAGE_H #define STBI_INCLUDE_STB_IMAGE_H #define STBI_NO_DDS // Disable DDS support // DOCUMENTATION // // Limitations: // - no 16-bit-per-channel PNG // - no 12-bit-per-channel JPEG // - no JPEGs with arithmetic coding // - no 1-bit BMP // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below for HDR usage): // int x,y,n; // unsigned char *data = stbi_load(filename, &x, &y, &n, 0); // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 // stbi_image_free(data) // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *channels_in_file -- outputs # of image components in image file // int desired_channels -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is // corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. // If req_comp is non-zero, *comp has the number of components that _would_ // have been output otherwise. E.g. if you set req_comp to 4, you will always // get RGBA output, but you can check *comp to see if it's trivially opaque // because e.g. there were only 3 channels in the source image. // // An output image with N components has the following components interleaved // in this order in each pixel: // // N=#comp components // 1 grey // 2 grey, alpha // 3 red, green, blue // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, // and *x, *y, *comp will be unchanged. The function stbi_failure_reason() // can be queried for an extremely brief, end-user unfriendly explanation // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // // =========================================================================== // // Philosophy // // stb libraries are designed with the following priorities: // // 1. easy to use // 2. easy to maintain // 3. good performance // // Sometimes I let "good performance" creep up in priority over "easy to maintain", // and for best performance I may provide less-easy-to-use APIs that give higher // performance, in addition to the easy to use ones. Nevertheless, it's important // to keep in mind that from the standpoint of you, a client of this library, // all you care about is #1 and #3, and stb libraries do not emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which // make more explicit reasons why performance can't be emphasized. // // - Portable ("ease of use") // - Small footprint ("easy to maintain") // - No dependencies ("ease of use") // // =========================================================================== // // I/O callbacks // // I/O callbacks allow you to read from arbitrary sources, like packaged // files or some other source. Data read from callbacks are processed // through a small internal buffer (currently 128 bytes) to try to reduce // overhead. // // The three functions you must define are "read" (reads some bytes of data), // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). // // =========================================================================== // // SIMD support // // The JPEG decoder will try to automatically use SIMD kernels on x86 when // supported by the compiler. For ARM Neon support, you must explicitly // request it. // // (The old do-it-yourself SIMD API is no longer supported in the current // code.) // // On x86, SSE2 will automatically be used when available based on a run-time // test; if not, the generic C versions are used as a fall-back. On ARM targets, // the typical path is to have separate builds for NEON and non-NEON devices // (at least this is true for iOS and Android). Therefore, the NEON support is // toggled by a build flag: define STBI_NEON to get NEON loops. // // The output of the JPEG decoder is slightly different from versions where // SIMD support was introduced (that is, for versions before 1.49). The // difference is only +-1 in the 8-bit RGB channels, and only on a small // fraction of pixels. You can force the pre-1.49 behavior by defining // STBI_JPEG_OLD, but this will disable some of the SIMD decoding path // and hence cost some performance. // // If for some reason you do not want to use any of SIMD code, or if // you have issues compiling it, you can disable it entirely by // defining STBI_NO_SIMD. // // =========================================================================== // // HDR image support (disable by defining STBI_NO_HDR) // // stb_image now supports loading HDR images in general, and currently // the Radiance .HDR file format, although the support is provided // generically. You can still load any file through the existing interface; // if you attempt to load an HDR file, it will be automatically remapped to // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); // // (note, do not use _inverse_ constants; stbi_image will invert them // appropriately). // // Additionally, there is a new, parallel interface for loading files as // (linear) floats to preserve the full dynamic range: // // float *data = stbi_loadf(filename, &x, &y, &n, 0); // // If you load LDR images through this interface, those images will // be promoted to floating point values, run through the inverse of // constants corresponding to the above: // // stbi_ldr_to_hdr_scale(1.0f); // stbi_ldr_to_hdr_gamma(2.2f); // // Finally, given a filename (or an open file or memory block--see header // file for details) containing image data, you can query for the "most // appropriate" interface to use (that is, whether the image is HDR or // not), using: // // stbi_is_hdr(char *filename); // // =========================================================================== // // iPhone PNG support: // // By default we convert iphone-formatted PNGs back to RGB, even though // they are internally encoded differently. You can disable this conversion // by by calling stbi_convert_iphone_png_to_rgb(0), in which case // you will always just get the native iphone "format" through (which // is BGR stored in RGB). // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // #ifndef STBI_NO_STDIO #include <stdio.h> #endif // STBI_NO_STDIO #define STBI_VERSION 1 enum { STBI_default = 0, // only used for req_comp STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4 }; typedef unsigned char stbi_uc; typedef unsigned short stbi_us; #ifdef __cplusplus extern "C" { #endif #ifdef STB_IMAGE_STATIC #define STBIDEF static #else #define STBIDEF extern #endif ////////////////////////////////////////////////////////////////////////////// // // PRIMARY API - works on images of any type // // // load image by filename, open file, or memory buffer // typedef struct { int(*read) (void *user, char *data, int size); // fill 'data' with 'size' bytes. return number of bytes actually read void(*skip) (void *user, int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative int(*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; //////////////////////////////////// // // 8-bits-per-channel interface // STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif //////////////////////////////////// // // 16-bits-per-channel interface // STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif // @TODO the other variants //////////////////////////////////// // // float-per-channel interface // #ifndef STBI_NO_LINEAR STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif #endif #ifndef STBI_NO_HDR STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); STBIDEF void stbi_hdr_to_ldr_scale(float scale); #endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); STBIDEF void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr(char const *filename); STBIDEF int stbi_is_hdr_from_file(FILE *f); #endif // STBI_NO_STDIO // get a VERY brief reason for failure // NOT THREADSAFE STBIDEF const char *stbi_failure_reason(void); // free the loaded image -- this is just free() STBIDEF void stbi_image_free(void *retval_from_stbi_load); // get image dimensions & components without fully decoding STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp); STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp); #endif // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // flip the image vertically, so the first pixel in the output array is the bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); // ZLIB client - used by PNG, available for other purposes STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); #ifdef __cplusplus } #endif // // //// end header file ///////////////////////////////////////////////////// #endif // STBI_INCLUDE_STB_IMAGE_H #ifdef STB_IMAGE_IMPLEMENTATION #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ || defined(STBI_ONLY_ZLIB) #ifndef STBI_ONLY_JPEG #define STBI_NO_JPEG #endif #ifndef STBI_ONLY_PNG #define STBI_NO_PNG #endif #ifndef STBI_ONLY_BMP #define STBI_NO_BMP #endif #ifndef STBI_ONLY_PSD #define STBI_NO_PSD #endif #ifndef STBI_ONLY_TGA #define STBI_NO_TGA #endif #ifndef STBI_ONLY_GIF #define STBI_NO_GIF #endif #ifndef STBI_ONLY_HDR #define STBI_NO_HDR #endif #ifndef STBI_ONLY_PIC #define STBI_NO_PIC #endif #ifndef STBI_ONLY_PNM #define STBI_NO_PNM #endif #endif #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) #define STBI_NO_ZLIB #endif #include <stdarg.h> #include <stddef.h> // ptrdiff_t on osx #include <stdlib.h> #include <string.h> #include <limits.h> #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) #include <math.h> // ldexp #endif #ifndef STBI_NO_STDIO #include <stdio.h> #endif #ifndef STBI_ASSERT #include <assert.h> #define STBI_ASSERT(x) assert(x) #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbi_inline inline #else #define stbi_inline #endif #else #define stbi_inline __forceinline #endif #ifdef _MSC_VER typedef unsigned short stbi__uint16; typedef signed short stbi__int16; typedef unsigned int stbi__uint32; typedef signed int stbi__int32; #else #include <stdint.h> typedef uint16_t stbi__uint16; typedef int16_t stbi__int16; typedef uint32_t stbi__uint32; typedef int32_t stbi__int32; #endif // should produce compiler error if size is wrong typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1]; #ifdef _MSC_VER #define STBI_NOTUSED(v) (void)(v) #else #define STBI_NOTUSED(v) (void)sizeof(v) #endif #ifdef _MSC_VER #define STBI_HAS_LROTL #endif #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) #endif #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC #define STBI_MALLOC(sz) malloc(sz) #define STBI_REALLOC(p,newsz) realloc(p,newsz) #define STBI_FREE(p) free(p) #endif #ifndef STBI_REALLOC_SIZED #define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) #endif // x86/x64 detection #if defined(__x86_64__) || defined(_M_X64) #define STBI__X64_TARGET #elif defined(__i386) || defined(_M_IX86) #define STBI__X86_TARGET #endif #if defined(__GNUC__) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) // NOTE: not clear do we actually need this for the 64-bit path? // gcc doesn't support sse2 intrinsics unless you compile with -msse2, // (but compiling with -msse2 allows the compiler to use SSE2 everywhere; // this is just broken and gcc are jerks for not fixing it properly // http://www.virtualdub.org/blog/pivot/entry.php?id=363 ) #define STBI_NO_SIMD #endif #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET // // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not // simultaneously enabling "-mstackrealign". // // See https://github.com/nothings/stb/issues/81 for more information. // // So default to no SSE2 on 32-bit MinGW. If you've read this far and added // -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. #define STBI_NO_SIMD #endif #if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include <emmintrin.h> #ifdef _MSC_VER #if _MSC_VER >= 1400 // not VC6 #include <intrin.h> // __cpuid static int stbi__cpuid3(void) { int info[4]; __cpuid(info, 1); return info[3]; } #else static int stbi__cpuid3(void) { int res; __asm { mov eax, 1 cpuid mov res, edx } return res; } #endif #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name static int stbi__sse2_available() { int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } #else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) static int stbi__sse2_available() { #if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 408 // GCC 4.8 or later // GCC 4.8+ has a nice way to do this return __builtin_cpu_supports("sse2"); #else // portable way to do this, preferably without using GCC inline ASM? // just bail for now. return 0; #endif } #endif #endif // ARM NEON #if defined(STBI_NO_SIMD) && defined(STBI_NEON) #undef STBI_NEON #endif #ifdef STBI_NEON #include <arm_neon.h> // assume GCC or Clang on ARM targets #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #endif #ifndef STBI_SIMD_ALIGN #define STBI_SIMD_ALIGN(type, name) type name #endif /////////////////////////////////////////////// // // stbi__context struct and start_xxx functions // stbi__context structure is our basic context used by all images, so it // contains all the IO context, plus some basic image information typedef struct { stbi__uint32 img_x, img_y; int img_n, img_out_n; stbi_io_callbacks io; void *io_user_data; int read_from_callbacks; int buflen; stbi_uc buffer_start[128]; stbi_uc *img_buffer, *img_buffer_end; stbi_uc *img_buffer_original, *img_buffer_original_end; } stbi__context; static void stbi__refill_buffer(stbi__context *s); // initialize a memory-decode context static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; s->img_buffer = s->img_buffer_original = (stbi_uc *)buffer; s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *)buffer + len; } // initialize a callback-based context static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) { s->io = *c; s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; s->img_buffer_original = s->buffer_start; stbi__refill_buffer(s); s->img_buffer_original_end = s->img_buffer_end; } #ifndef STBI_NO_STDIO static int stbi__stdio_read(void *user, char *data, int size) { return (int)fread(data, 1, size, (FILE*)user); } static void stbi__stdio_skip(void *user, int n) { fseek((FILE*)user, n, SEEK_CUR); } static int stbi__stdio_eof(void *user) { return feof((FILE*)user); } static stbi_io_callbacks stbi__stdio_callbacks = { stbi__stdio_read, stbi__stdio_skip, stbi__stdio_eof, }; static void stbi__start_file(stbi__context *s, FILE *f) { stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *)f); } //static void stop_file(stbi__context *s) { } #endif // !STBI_NO_STDIO static void stbi__rewind(stbi__context *s) { // conceptually rewind SHOULD rewind to the beginning of the stream, // but we just rewind to the beginning of the initial buffer, because // we only use it after doing 'test', which only ever looks at at most 92 bytes s->img_buffer = s->img_buffer_original; s->img_buffer_end = s->img_buffer_original_end; } enum { STBI_ORDER_RGB, STBI_ORDER_BGR }; typedef struct { int bits_per_channel; int num_channels; int channel_order; } stbi__result_info; #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context *s); static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context *s); static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context *s); static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context *s); static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s); static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context *s); static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context *s); static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context *s); static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s); static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); #endif // this is not threadsafe static const char *stbi__g_failure_reason; STBIDEF const char *stbi_failure_reason(void) { return stbi__g_failure_reason; } static int stbi__err(const char *str) { stbi__g_failure_reason = str; return 0; } static void *stbi__malloc(size_t size) { return STBI_MALLOC(size); } // stb_image uses ints pervasively, including for offset calculations. // therefore the largest decoded image size we can support with the // current code, even on 64-bit targets, is INT_MAX. this is not a // significant limitation for the intended use case. // // we do, however, need to make sure our size calculations don't // overflow. hence a few helper functions for size calculations that // multiply integers together, making sure that they're non-negative // and no overflow occurs. // return 1 if the sum is valid, 0 on overflow. // negative terms are considered invalid. static int stbi__addsizes_valid(int a, int b) { if (b < 0) return 0; // now 0 <= b <= INT_MAX, hence also // 0 <= INT_MAX - b <= INTMAX. // And "a + b <= INT_MAX" (which might overflow) is the // same as a <= INT_MAX - b (no overflow) return a <= INT_MAX - b; } // returns 1 if the product is valid, 0 on overflow. // negative factors are considered invalid. static int stbi__mul2sizes_valid(int a, int b) { if (a < 0 || b < 0) return 0; if (b == 0) return 1; // mul-by-0 is always safe // portable way to check for no overflows in a*b return a <= INT_MAX / b; } // returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow static int stbi__mad2sizes_valid(int a, int b, int add) { return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); } // returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow static int stbi__mad3sizes_valid(int a, int b, int c, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__addsizes_valid(a*b*c, add); } // returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); } // mallocs with size overflow checking static void *stbi__malloc_mad2(int a, int b, int add) { if (!stbi__mad2sizes_valid(a, b, add)) return NULL; return stbi__malloc(a*b + add); } static void *stbi__malloc_mad3(int a, int b, int c, int add) { if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; return stbi__malloc(a*b*c + add); } static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) { if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; return stbi__malloc(a*b*c*d + add); } // stbi__err - error // stbi__errpf - error returning pointer to float // stbi__errpuc - error returning pointer to unsigned char #ifdef STBI_NO_FAILURE_STRINGS #define stbi__err(x,y) 0 #elif defined(STBI_FAILURE_USERMSG) #define stbi__err(x,y) stbi__err(y) #else #define stbi__err(x,y) stbi__err(x) #endif #define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) #define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) STBIDEF void stbi_image_free(void *retval_from_stbi_load) { STBI_FREE(retval_from_stbi_load); } #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); #endif #ifndef STBI_NO_HDR static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); #endif static int stbi__vertically_flip_on_load = 0; STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { stbi__vertically_flip_on_load = flag_true_if_should_flip; } static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order ri->num_channels = 0; #ifndef STBI_NO_JPEG if (stbi__jpeg_test(s)) return stbi__jpeg_load(s, x, y, comp, req_comp, ri); #endif #ifndef STBI_NO_PNG if (stbi__png_test(s)) return stbi__png_load(s, x, y, comp, req_comp, ri); #endif #ifndef STBI_NO_BMP if (stbi__bmp_test(s)) return stbi__bmp_load(s, x, y, comp, req_comp, ri); #endif #ifndef STBI_NO_GIF if (stbi__gif_test(s)) return stbi__gif_load(s, x, y, comp, req_comp, ri); #endif #ifndef STBI_NO_PSD if (stbi__psd_test(s)) return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc); #endif #ifndef STBI_NO_PIC if (stbi__pic_test(s)) return stbi__pic_load(s, x, y, comp, req_comp, ri); #endif #ifndef STBI_NO_PNM if (stbi__pnm_test(s)) return stbi__pnm_load(s, x, y, comp, req_comp, ri); #endif #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { float *hdr = stbi__hdr_load(s, x, y, comp, req_comp, ri); return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif #ifndef STBI_NO_TGA // test tga last because it's a crappy test! if (stbi__tga_test(s)) return stbi__tga_load(s, x, y, comp, req_comp, ri); #endif return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi_uc *reduced; reduced = (stbi_uc *)stbi__malloc(img_len); if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling STBI_FREE(orig); return reduced; } static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi__uint16 *enlarged; enlarged = (stbi__uint16 *)stbi__malloc(img_len * 2); if (enlarged == NULL) return (stbi__uint16 *)stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff STBI_FREE(orig); return enlarged; } static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); if (result == NULL) return NULL; if (ri.bits_per_channel != 8) { STBI_ASSERT(ri.bits_per_channel == 16); result = stbi__convert_16_to_8((stbi__uint16 *)result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 8; } // @TODO: move stbi__convert_format to here if (stbi__vertically_flip_on_load) { int w = *x, h = *y; int channels = req_comp ? req_comp : *comp; int row, col, z; stbi_uc *image = (stbi_uc *)result; // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once for (row = 0; row < (h >> 1); row++) { for (col = 0; col < w; col++) { for (z = 0; z < channels; z++) { stbi_uc temp = image[(row * w + col) * channels + z]; image[(row * w + col) * channels + z] = image[((h - row - 1) * w + col) * channels + z]; image[((h - row - 1) * w + col) * channels + z] = temp; } } } } return (unsigned char *)result; } static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); if (result == NULL) return NULL; if (ri.bits_per_channel != 16) { STBI_ASSERT(ri.bits_per_channel == 8); result = stbi__convert_8_to_16((stbi_uc *)result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 16; } // @TODO: move stbi__convert_format16 to here // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision if (stbi__vertically_flip_on_load) { int w = *x, h = *y; int channels = req_comp ? req_comp : *comp; int row, col, z; stbi__uint16 *image = (stbi__uint16 *)result; // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once for (row = 0; row < (h >> 1); row++) { for (col = 0; col < w; col++) { for (z = 0; z < channels; z++) { stbi__uint16 temp = image[(row * w + col) * channels + z]; image[(row * w + col) * channels + z] = image[((h - row - 1) * w + col) * channels + z]; image[((h - row - 1) * w + col) * channels + z] = temp; } } } } return (stbi__uint16 *)result; } #ifndef STBI_NO_HDR static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { int w = *x, h = *y; int depth = req_comp ? req_comp : *comp; int row, col, z; float temp; // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once for (row = 0; row < (h >> 1); row++) { for (col = 0; col < w; col++) { for (z = 0; z < depth; z++) { temp = result[(row * w + col) * depth + z]; result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; result[((h - row - 1) * w + col) * depth + z] = temp; } } } } } #endif #ifndef STBI_NO_STDIO static FILE *stbi__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f = 0; #else f = fopen(filename, mode); #endif return f; } STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); unsigned char *result; if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file(f, x, y, comp, req_comp); fclose(f); return result; } STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_file(&s, f); result = stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__uint16 *result; stbi__context s; stbi__start_file(&s, f); result = stbi__load_and_postprocess_16bit(&s, x, y, comp, req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); stbi__uint16 *result; if (!f) return (stbi_us *)stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file_16(f, x, y, comp, req_comp); fclose(f); return result; } #endif //!STBI_NO_STDIO STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } #ifndef STBI_NO_LINEAR static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { stbi__result_info ri; float *hdr_data = stbi__hdr_load(s, x, y, comp, req_comp, &ri); if (hdr_data) stbi__float_postprocess(hdr_data, x, y, comp, req_comp); return hdr_data; } #endif data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); } STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__loadf_main(&s, x, y, comp, req_comp); } STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); return stbi__loadf_main(&s, x, y, comp, req_comp); } #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) { float *result; FILE *f = stbi__fopen(filename, "rb"); if (!f) return stbi__errpf("can't fopen", "Unable to open file"); result = stbi_loadf_from_file(f, x, y, comp, req_comp); fclose(f); return result; } STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_file(&s, f); return stbi__loadf_main(&s, x, y, comp, req_comp); } #endif // !STBI_NO_STDIO #endif // !STBI_NO_LINEAR // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always // reports false! STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__hdr_test(&s); #else STBI_NOTUSED(buffer); STBI_NOTUSED(len); return 0; #endif } #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr(char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result = 0; if (f) { result = stbi_is_hdr_from_file(f); fclose(f); } return result; } STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_file(&s, f); return stbi__hdr_test(&s); #else STBI_NOTUSED(f); return 0; #endif } #endif // !STBI_NO_STDIO STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); return stbi__hdr_test(&s); #else STBI_NOTUSED(clbk); STBI_NOTUSED(user); return 0; #endif } #ifndef STBI_NO_LINEAR static float stbi__l2h_gamma = 2.2f, stbi__l2h_scale = 1.0f; STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif static float stbi__h2l_gamma_i = 1.0f / 2.2f, stbi__h2l_scale_i = 1.0f; STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1 / gamma; } STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1 / scale; } ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // enum { STBI__SCAN_load = 0, STBI__SCAN_type, STBI__SCAN_header }; static void stbi__refill_buffer(stbi__context *s) { int n = (s->io.read)(s->io_user_data, (char*)s->buffer_start, s->buflen); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file s->read_from_callbacks = 0; s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start + 1; *s->img_buffer = 0; } else { s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start + n; } } stbi_inline static stbi_uc stbi__get8(stbi__context *s) { if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; if (s->read_from_callbacks) { stbi__refill_buffer(s); return *s->img_buffer++; } return 0; } stbi_inline static int stbi__at_eof(stbi__context *s) { if (s->io.read) { if (!(s->io.eof)(s->io_user_data)) return 0; // if feof() is true, check if buffer = end // special case: we've only got the special 0 character at the end if (s->read_from_callbacks == 0) return 1; } return s->img_buffer >= s->img_buffer_end; } static void stbi__skip(stbi__context *s, int n) { if (n < 0) { s->img_buffer = s->img_buffer_end; return; } if (s->io.read) { int blen = (int)(s->img_buffer_end - s->img_buffer); if (blen < n) { s->img_buffer = s->img_buffer_end; (s->io.skip)(s->io_user_data, n - blen); return; } } s->img_buffer += n; } static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { int blen = (int)(s->img_buffer_end - s->img_buffer); if (blen < n) { int res, count; memcpy(buffer, s->img_buffer, blen); count = (s->io.read)(s->io_user_data, (char*)buffer + blen, n - blen); res = (count == (n - blen)); s->img_buffer = s->img_buffer_end; return res; } } if (s->img_buffer + n <= s->img_buffer_end) { memcpy(buffer, s->img_buffer, n); s->img_buffer += n; return 1; } else return 0; } static int stbi__get16be(stbi__context *s) { int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } static stbi__uint32 stbi__get32be(stbi__context *s) { stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing #else static int stbi__get16le(stbi__context *s) { int z = stbi__get8(s); return z + (stbi__get8(s) << 8); } #endif #ifndef STBI_NO_BMP static stbi__uint32 stbi__get32le(stbi__context *s) { stbi__uint32 z = stbi__get16le(s); return z + (stbi__get16le(s) << 16); } #endif #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp // individual types do this automatically as much as possible (e.g. jpeg // does all cases internally since it needs to colorspace convert anyway, // and it never has alpha, so very few cases ). png can automatically // interleave an alpha=255 channel, but falls back to this for other cases // // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing static stbi_uc stbi__compute_y(int r, int g, int b) { return (stbi_uc)(((r * 77) + (g * 150) + (29 * b)) >> 8); } static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i, j; unsigned char *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (unsigned char *)stbi__malloc_mad3(req_comp, x, y, 0); if (good == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } for (j = 0; j < (int)y; ++j) { unsigned char *src = data + j * x * img_n; unsigned char *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1, 2) { dest[0] = src[0], dest[1] = 255; } break; STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; STBI__CASE(1, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = 255; } break; STBI__CASE(2, 1) { dest[0] = src[0]; } break; STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; STBI__CASE(2, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = src[1]; } break; STBI__CASE(3, 4) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2], dest[3] = 255; } break; STBI__CASE(3, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; STBI__CASE(3, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]), dest[1] = 255; } break; STBI__CASE(4, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; STBI__CASE(4, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]), dest[1] = src[3]; } break; STBI__CASE(4, 3) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2]; } break; default: STBI_ASSERT(0); } #undef STBI__CASE } STBI_FREE(data); return good; } static stbi__uint16 stbi__compute_y_16(int r, int g, int b) { return (stbi__uint16)(((r * 77) + (g * 150) + (29 * b)) >> 8); } static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i, j; stbi__uint16 *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (stbi__uint16 *)stbi__malloc(req_comp * x * y * 2); if (good == NULL) { STBI_FREE(data); return (stbi__uint16 *)stbi__errpuc("outofmem", "Out of memory"); } for (j = 0; j < (int)y; ++j) { stbi__uint16 *src = data + j * x * img_n; stbi__uint16 *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1, 2) { dest[0] = src[0], dest[1] = 0xffff; } break; STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; STBI__CASE(1, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = 0xffff; } break; STBI__CASE(2, 1) { dest[0] = src[0]; } break; STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; STBI__CASE(2, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = src[1]; } break; STBI__CASE(3, 4) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2], dest[3] = 0xffff; } break; STBI__CASE(3, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; STBI__CASE(3, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]), dest[1] = 0xffff; } break; STBI__CASE(4, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; STBI__CASE(4, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]), dest[1] = src[3]; } break; STBI__CASE(4, 3) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2]; } break; default: STBI_ASSERT(0); } #undef STBI__CASE } STBI_FREE(data); return good; } #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i, k, n; float *output; if (!data) return NULL; output = (float *)stbi__malloc_mad4(x, y, comp, sizeof(float), 0); if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp - 1; for (i = 0; i < x*y; ++i) { for (k = 0; k < n; ++k) { output[i*comp + k] = (float)(pow(data[i*comp + k] / 255.0f, stbi__l2h_gamma) * stbi__l2h_scale); } if (k < comp) output[i*comp + k] = data[i*comp + k] / 255.0f; } STBI_FREE(data); return output; } #endif #ifndef STBI_NO_HDR #define stbi__float2int(x) ((int) (x)) static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) { int i, k, n; stbi_uc *output; if (!data) return NULL; output = (stbi_uc *)stbi__malloc_mad3(x, y, comp, 0); if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp - 1; for (i = 0; i < x*y; ++i) { for (k = 0; k < n; ++k) { float z = (float)pow(data[i*comp + k] * stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc)stbi__float2int(z); } if (k < comp) { float z = data[i*comp + k] * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc)stbi__float2int(z); } } STBI_FREE(data); return output; } #endif ////////////////////////////////////////////////////////////////////////////// // // "baseline" JPEG/JFIF decoder // // simple implementation // - doesn't support delayed output of y-dimension // - simple interface (only one output format: 8-bit interleaved RGB) // - doesn't try to recover corrupt jpegs // - doesn't allow partial loading, loading multiple at once // - still fast on x86 (copying globals into locals doesn't help x86) // - allocates lots of intermediate memory (full size of all components) // - non-interleaved case requires this anyway // - allows good upsampling (see next) // high-quality // - upsampled channels are bilinearly interpolated, even across blocks // - quality integer IDCT derived from IJG's 'slow' // performance // - fast huffman; reasonable integer IDCT // - some SIMD kernels for common paths on targets with SSE2/NEON // - uses a lot of intermediate memory, could cache poorly #ifndef STBI_NO_JPEG // huffman decoding acceleration #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache typedef struct { stbi_uc fast[1 << FAST_BITS]; // weirdly, repacking this into AoS is a 10% speed loss, instead of a win stbi__uint16 code[256]; stbi_uc values[256]; stbi_uc size[257]; unsigned int maxcode[18]; int delta[17]; // old 'firstsymbol' - old 'firstcode' } stbi__huffman; typedef struct { stbi__context *s; stbi__huffman huff_dc[4]; stbi__huffman huff_ac[4]; stbi_uc dequant[4][64]; stbi__int16 fast_ac[4][1 << FAST_BITS]; // sizes for components, interleaved MCUs int img_h_max, img_v_max; int img_mcu_x, img_mcu_y; int img_mcu_w, img_mcu_h; // definition of jpeg image component struct { int id; int h, v; int tq; int hd, ha; int dc_pred; int x, y, w2, h2; stbi_uc *data; void *raw_data, *raw_coeff; stbi_uc *linebuf; short *coeff; // progressive only int coeff_w, coeff_h; // number of 8x8 coefficient blocks } img_comp[4]; stbi__uint32 code_buffer; // jpeg entropy-coded buffer int code_bits; // number of valid bits unsigned char marker; // marker seen while filling entropy buffer int nomore; // flag if we saw a marker so must stop int progressive; int spec_start; int spec_end; int succ_high; int succ_low; int eob_run; int rgb; int scan_n, order[4]; int restart_interval, todo; // kernels void(*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); void(*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); } stbi__jpeg; static int stbi__build_huffman(stbi__huffman *h, int *count) { int i, j, k = 0, code; // build size list for each symbol (from JPEG spec) for (i = 0; i < 16; ++i) for (j = 0; j < count[i]; ++j) h->size[k++] = (stbi_uc)(i + 1); h->size[k] = 0; // compute actual symbols (from jpeg spec) code = 0; k = 0; for (j = 1; j <= 16; ++j) { // compute delta to add to code to compute symbol id h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16)(code++); if (code - 1 >= (1 << j)) return stbi__err("bad code lengths", "Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16 - j); code <<= 1; } h->maxcode[j] = 0xffffffff; // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i = 0; i < k; ++i) { int s = h->size[i]; if (s <= FAST_BITS) { int c = h->code[i] << (FAST_BITS - s); int m = 1 << (FAST_BITS - s); for (j = 0; j < m; ++j) { h->fast[c + j] = (stbi_uc)i; } } } return 1; } // build a table that decodes both magnitude and value of small ACs in // one go. static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) { int i; for (i = 0; i < (1 << FAST_BITS); ++i) { stbi_uc fast = h->fast[i]; fast_ac[i] = 0; if (fast < 255) { int rs = h->values[fast]; int run = (rs >> 4) & 15; int magbits = rs & 15; int len = h->size[fast]; if (magbits && len + magbits <= FAST_BITS) { // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); if (k < m) k += (-1 << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) fast_ac[i] = (stbi__int16)((k << 8) + (run << 4) + (len + magbits)); } } } } static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); if (c != 0) { j->marker = (unsigned char)c; j->nomore = 1; return; } } j->code_buffer |= b << (24 - j->code_bits); j->code_bits += 8; } while (j->code_bits <= 24); } // (1 << n) - 1 static stbi__uint32 stbi__bmask[17] = { 0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535 }; // decode a jpeg huffman value from the bitstream stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) { unsigned int temp; int c, k; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); // look at the top FAST_BITS and determine what symbol ID it is, // if the code is <= FAST_BITS c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); k = h->fast[c]; if (k < 255) { int s = h->size[k]; if (s > j->code_bits) return -1; j->code_buffer <<= s; j->code_bits -= s; return h->values[k]; } // naive test is to shift the code_buffer down so k bits are // valid, then test against maxcode. To speed this up, we've // preshifted maxcode left so that it has (16-k) 0s at the // end; in other words, regardless of the number of bits, it // wants to be compared against something shifted to have 16; // that way we don't need to shift inside the loop. temp = j->code_buffer >> 16; for (k = FAST_BITS + 1; ; ++k) if (temp < h->maxcode[k]) break; if (k == 17) { // error! code not found j->code_bits -= 16; return -1; } if (k > j->code_bits) return -1; // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol j->code_bits -= k; j->code_buffer <<= k; return h->values[c]; } // bias[n] = (-1<<n) + 1 static int const stbi__jbias[16] = { 0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767 }; // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n) { unsigned int k; int sgn; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB k = stbi_lrot(j->code_buffer, n); STBI_ASSERT(n >= 0 && n < (int)(sizeof(stbi__bmask) / sizeof(*stbi__bmask))); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k + (stbi__jbias[n] & ~sgn); } // get some unsigned bits stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) { unsigned int k; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k; } stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) { unsigned int k; if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); k = j->code_buffer; j->code_buffer <<= 1; --j->code_bits; return k & 0x80000000; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static stbi_uc stbi__jpeg_dezigzag[64 + 15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 }; // decode one 64-entry block-- static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi_uc *dequant) { int diff, dc, k; int t; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); t = stbi__jpeg_huff_decode(j, hdc); if (t < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data, 0, 64 * sizeof(data[0])); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short)(dc * dequant[0]); // decode AC components, see JPEG spec k = 1; do { unsigned int zig; int c, r, s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short)((r >> 8) * dequant[zig]); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (rs != 0xf0) break; // end block k += 16; } else { k += r; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short)(stbi__extend_receive(j, s) * dequant[zig]); } } } while (k < 64); return 1; } static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) { int diff, dc; int t; if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); if (j->succ_high == 0) { // first scan for DC coefficient, must be first memset(data, 0, 64 * sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short)(dc << j->succ_low); } else { // refinement scan for DC coefficient if (stbi__jpeg_get_bit(j)) data[0] += (short)(1 << j->succ_low); } return 1; } // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) { int k; if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->succ_high == 0) { int shift = j->succ_low; if (j->eob_run) { --j->eob_run; return 1; } k = j->spec_start; do { unsigned int zig; int c, r, s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short)((r >> 8) << shift); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r); if (r) j->eob_run += stbi__jpeg_get_bits(j, r); --j->eob_run; break; } k += 16; } else { k += r; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short)(stbi__extend_receive(j, s) << shift); } } } while (k <= j->spec_end); } else { // refinement scan for these AC coefficients short bit = (short)(1 << j->succ_low); if (j->eob_run) { --j->eob_run; for (k = j->spec_start; k <= j->spec_end; ++k) { short *p = &data[stbi__jpeg_dezigzag[k]]; if (*p != 0) if (stbi__jpeg_get_bit(j)) if ((*p & bit) == 0) { if (*p > 0) *p += bit; else *p -= bit; } } } else { k = j->spec_start; do { int r, s; int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r) - 1; if (r) j->eob_run += stbi__jpeg_get_bits(j, r); r = 64; // force end of block } else { // r=15 s=0 should write 16 0s, so we just do // a run of 15 0s and then write s (which is 0), // so we don't have to do anything special here } } else { if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); // sign bit if (stbi__jpeg_get_bit(j)) s = bit; else s = -bit; } // advance by r while (k <= j->spec_end) { short *p = &data[stbi__jpeg_dezigzag[k++]]; if (*p != 0) { if (stbi__jpeg_get_bit(j)) if ((*p & bit) == 0) { if (*p > 0) *p += bit; else *p -= bit; } } else { if (r == 0) { *p = (short)s; break; } --r; } } } while (k <= j->spec_end); } } return 1; } // take a -128..127 value and stbi__clamp it and convert to 0..255 stbi_inline static stbi_uc stbi__clamp(int x) { // trick to use a single test to catch both cases if ((unsigned int)x > 255) { if (x < 0) return 0; if (x > 255) return 255; } return (stbi_uc)x; } #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) #define stbi__fsh(x) ((x) << 12) // derived from jidctint -- DCT_ISLOW #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ p2 = s2; \ p3 = s6; \ p1 = (p2+p3) * stbi__f2f(0.5411961f); \ t2 = p1 + p3*stbi__f2f(-1.847759065f); \ t3 = p1 + p2*stbi__f2f( 0.765366865f); \ p2 = s0; \ p3 = s4; \ t0 = stbi__fsh(p2+p3); \ t1 = stbi__fsh(p2-p3); \ x0 = t0+t3; \ x3 = t0-t3; \ x1 = t1+t2; \ x2 = t1-t2; \ t0 = s7; \ t1 = s5; \ t2 = s3; \ t3 = s1; \ p3 = t0+t2; \ p4 = t1+t3; \ p1 = t0+t3; \ p2 = t1+t2; \ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ t0 = t0*stbi__f2f( 0.298631336f); \ t1 = t1*stbi__f2f( 2.053119869f); \ t2 = t2*stbi__f2f( 3.072711026f); \ t3 = t3*stbi__f2f( 1.501321110f); \ p1 = p5 + p1*stbi__f2f(-0.899976223f); \ p2 = p5 + p2*stbi__f2f(-2.562915447f); \ p3 = p3*stbi__f2f(-1.961570560f); \ p4 = p4*stbi__f2f(-0.390180644f); \ t3 += p1+p4; \ t2 += p2+p3; \ t1 += p2+p4; \ t0 += p1+p3; static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) { int i, val[64], *v = val; stbi_uc *o; short *d = data; // columns for (i = 0; i < 8; ++i, ++d, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0 && d[48] == 0 && d[56] == 0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0] << 2; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[0] = (x0 + t3) >> 10; v[56] = (x0 - t3) >> 10; v[8] = (x1 + t2) >> 10; v[48] = (x1 - t2) >> 10; v[16] = (x2 + t1) >> 10; v[40] = (x2 - t1) >> 10; v[24] = (x3 + t0) >> 10; v[32] = (x3 - t0) >> 10; } } for (i = 0, v = val, o = out; i < 8; ++i, v += 8, o += out_stride) { // no fast case since the first 1D IDCT spread components out STBI__IDCT_1D(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. // so we want to round that, which means adding 0.5 * 1<<17, // aka 65536. Also, we'll end up with -128 to 127 that we want // to encode as 0..255 by adding 128, so we'll add that before the shift x0 += 65536 + (128 << 17); x1 += 65536 + (128 << 17); x2 += 65536 + (128 << 17); x3 += 65536 + (128 << 17); // tried computing the shifts into temps, or'ing the temps to see // if any were out of range, but that was slower o[0] = stbi__clamp((x0 + t3) >> 17); o[7] = stbi__clamp((x0 - t3) >> 17); o[1] = stbi__clamp((x1 + t2) >> 17); o[6] = stbi__clamp((x1 - t2) >> 17); o[2] = stbi__clamp((x2 + t1) >> 17); o[5] = stbi__clamp((x2 - t1) >> 17); o[3] = stbi__clamp((x3 + t0) >> 17); o[4] = stbi__clamp((x3 - t0) >> 17); } } #ifdef STBI_SSE2 // sse2 integer IDCT. not the fastest possible implementation but it // produces bit-identical results to the generic C version so it's // fully "transparent". static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { // This is constructed to match our regular (generic) integer IDCT exactly. __m128i row0, row1, row2, row3, row4, row5, row6, row7; __m128i tmp; // dot product constant: even elems=x, odd elems=y #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) // out(1) = c1[even]*x + c1[odd]*y #define dct_rot(out0,out1, x,y,c0,c1) \ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) // out = in << 12 (in 16-bit, out 32-bit) #define dct_widen(out, in) \ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) // wide add #define dct_wadd(out, a, b) \ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_add_epi32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) // butterfly a/b, add bias, then shift by "s" and pack #define dct_bfly32o(out0, out1, a,b,bias,s) \ { \ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ dct_wadd(sum, abiased, b); \ dct_wsub(dif, abiased, b); \ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ } // 8-bit interleave step (for transposes) #define dct_interleave8(a, b) \ tmp = a; \ a = _mm_unpacklo_epi8(a, b); \ b = _mm_unpackhi_epi8(tmp, b) // 16-bit interleave step (for transposes) #define dct_interleave16(a, b) \ tmp = a; \ a = _mm_unpacklo_epi16(a, b); \ b = _mm_unpackhi_epi16(tmp, b) #define dct_pass(bias,shift) \ { \ /* even part */ \ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ __m128i sum04 = _mm_add_epi16(row0, row4); \ __m128i dif04 = _mm_sub_epi16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ __m128i sum17 = _mm_add_epi16(row1, row7); \ __m128i sum35 = _mm_add_epi16(row3, row5); \ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ dct_wadd(x4, y0o, y4o); \ dct_wadd(x5, y1o, y5o); \ dct_wadd(x6, y2o, y5o); \ dct_wadd(x7, y3o, y4o); \ dct_bfly32o(row0,row7, x0,x7,bias,shift); \ dct_bfly32o(row1,row6, x1,x6,bias,shift); \ dct_bfly32o(row2,row5, x2,x5,bias,shift); \ dct_bfly32o(row3,row4, x3,x4,bias,shift); \ } __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), stbi__f2f(0.5411961f)); __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), stbi__f2f(-1.961570560f)); __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f)); __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), stbi__f2f(-0.390180644f)); __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f)); // rounding biases in column/row passes, see stbi__idct_block for explanation. __m128i bias_0 = _mm_set1_epi32(512); __m128i bias_1 = _mm_set1_epi32(65536 + (128 << 17)); // load row0 = _mm_load_si128((const __m128i *) (data + 0 * 8)); row1 = _mm_load_si128((const __m128i *) (data + 1 * 8)); row2 = _mm_load_si128((const __m128i *) (data + 2 * 8)); row3 = _mm_load_si128((const __m128i *) (data + 3 * 8)); row4 = _mm_load_si128((const __m128i *) (data + 4 * 8)); row5 = _mm_load_si128((const __m128i *) (data + 5 * 8)); row6 = _mm_load_si128((const __m128i *) (data + 6 * 8)); row7 = _mm_load_si128((const __m128i *) (data + 7 * 8)); // column pass dct_pass(bias_0, 10); { // 16bit 8x8 transpose pass 1 dct_interleave16(row0, row4); dct_interleave16(row1, row5); dct_interleave16(row2, row6); dct_interleave16(row3, row7); // transpose pass 2 dct_interleave16(row0, row2); dct_interleave16(row1, row3); dct_interleave16(row4, row6); dct_interleave16(row5, row7); // transpose pass 3 dct_interleave16(row0, row1); dct_interleave16(row2, row3); dct_interleave16(row4, row5); dct_interleave16(row6, row7); } // row pass dct_pass(bias_1, 17); { // pack __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 __m128i p1 = _mm_packus_epi16(row2, row3); __m128i p2 = _mm_packus_epi16(row4, row5); __m128i p3 = _mm_packus_epi16(row6, row7); // 8bit 8x8 transpose pass 1 dct_interleave8(p0, p2); // a0e0a1e1... dct_interleave8(p1, p3); // c0g0c1g1... // transpose pass 2 dct_interleave8(p0, p1); // a0c0e0g0... dct_interleave8(p2, p3); // b0d0f0h0... // transpose pass 3 dct_interleave8(p0, p2); // a0b0c0d0... dct_interleave8(p1, p3); // a4b4c4d4... // store _mm_storel_epi64((__m128i *) out, p0); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p2); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p1); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p3); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); } #undef dct_const #undef dct_rot #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_interleave8 #undef dct_interleave16 #undef dct_pass } #endif // STBI_SSE2 #ifdef STBI_NEON // NEON integer IDCT. should produce bit-identical // results to the generic C version. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); int16x4_t rot0_2 = vdup_n_s16(stbi__f2f(0.765366865f)); int16x4_t rot1_0 = vdup_n_s16(stbi__f2f(1.175875602f)); int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); int16x4_t rot3_0 = vdup_n_s16(stbi__f2f(0.298631336f)); int16x4_t rot3_1 = vdup_n_s16(stbi__f2f(2.053119869f)); int16x4_t rot3_2 = vdup_n_s16(stbi__f2f(3.072711026f)); int16x4_t rot3_3 = vdup_n_s16(stbi__f2f(1.501321110f)); #define dct_long_mul(out, inq, coeff) \ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) #define dct_long_mac(out, acc, inq, coeff) \ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) #define dct_widen(out, inq) \ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) // wide add #define dct_wadd(out, a, b) \ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ int32x4_t out##_h = vaddq_s32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ int32x4_t out##_h = vsubq_s32(a##_h, b##_h) // butterfly a/b, then shift using "shiftop" by "s" and pack #define dct_bfly32o(out0,out1, a,b,shiftop,s) \ { \ dct_wadd(sum, a, b); \ dct_wsub(dif, a, b); \ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ } #define dct_pass(shiftop, shift) \ { \ /* even part */ \ int16x8_t sum26 = vaddq_s16(row2, row6); \ dct_long_mul(p1e, sum26, rot0_0); \ dct_long_mac(t2e, p1e, row6, rot0_1); \ dct_long_mac(t3e, p1e, row2, rot0_2); \ int16x8_t sum04 = vaddq_s16(row0, row4); \ int16x8_t dif04 = vsubq_s16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ int16x8_t sum15 = vaddq_s16(row1, row5); \ int16x8_t sum17 = vaddq_s16(row1, row7); \ int16x8_t sum35 = vaddq_s16(row3, row5); \ int16x8_t sum37 = vaddq_s16(row3, row7); \ int16x8_t sumodd = vaddq_s16(sum17, sum35); \ dct_long_mul(p5o, sumodd, rot1_0); \ dct_long_mac(p1o, p5o, sum17, rot1_1); \ dct_long_mac(p2o, p5o, sum35, rot1_2); \ dct_long_mul(p3o, sum37, rot2_0); \ dct_long_mul(p4o, sum15, rot2_1); \ dct_wadd(sump13o, p1o, p3o); \ dct_wadd(sump24o, p2o, p4o); \ dct_wadd(sump23o, p2o, p3o); \ dct_wadd(sump14o, p1o, p4o); \ dct_long_mac(x4, sump13o, row7, rot3_0); \ dct_long_mac(x5, sump24o, row5, rot3_1); \ dct_long_mac(x6, sump23o, row3, rot3_2); \ dct_long_mac(x7, sump14o, row1, rot3_3); \ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ } // load row0 = vld1q_s16(data + 0 * 8); row1 = vld1q_s16(data + 1 * 8); row2 = vld1q_s16(data + 2 * 8); row3 = vld1q_s16(data + 3 * 8); row4 = vld1q_s16(data + 4 * 8); row5 = vld1q_s16(data + 5 * 8); row6 = vld1q_s16(data + 6 * 8); row7 = vld1q_s16(data + 7 * 8); // add DC bias row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); // column pass dct_pass(vrshrn_n_s32, 10); // 16bit 8x8 transpose { // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. // whether compilers actually get this is another story, sadly. #define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } #define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } // pass 1 dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 dct_trn16(row2, row3); dct_trn16(row4, row5); dct_trn16(row6, row7); // pass 2 dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 dct_trn32(row1, row3); dct_trn32(row4, row6); dct_trn32(row5, row7); // pass 3 dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 dct_trn64(row1, row5); dct_trn64(row2, row6); dct_trn64(row3, row7); #undef dct_trn16 #undef dct_trn32 #undef dct_trn64 } // row pass // vrshrn_n_s32 only supports shifts up to 16, we need // 17. so do a non-rounding shift of 16 first then follow // up with a rounding shift by 1. dct_pass(vshrn_n_s32, 16); { // pack and round uint8x8_t p0 = vqrshrun_n_s16(row0, 1); uint8x8_t p1 = vqrshrun_n_s16(row1, 1); uint8x8_t p2 = vqrshrun_n_s16(row2, 1); uint8x8_t p3 = vqrshrun_n_s16(row3, 1); uint8x8_t p4 = vqrshrun_n_s16(row4, 1); uint8x8_t p5 = vqrshrun_n_s16(row5, 1); uint8x8_t p6 = vqrshrun_n_s16(row6, 1); uint8x8_t p7 = vqrshrun_n_s16(row7, 1); // again, these can translate into one instruction, but often don't. #define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } #define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } // sadly can't use interleaved stores here since we only write // 8 bytes to each scan line! // 8x8 8-bit transpose pass 1 dct_trn8_8(p0, p1); dct_trn8_8(p2, p3); dct_trn8_8(p4, p5); dct_trn8_8(p6, p7); // pass 2 dct_trn8_16(p0, p2); dct_trn8_16(p1, p3); dct_trn8_16(p4, p6); dct_trn8_16(p5, p7); // pass 3 dct_trn8_32(p0, p4); dct_trn8_32(p1, p5); dct_trn8_32(p2, p6); dct_trn8_32(p3, p7); // store vst1_u8(out, p0); out += out_stride; vst1_u8(out, p1); out += out_stride; vst1_u8(out, p2); out += out_stride; vst1_u8(out, p3); out += out_stride; vst1_u8(out, p4); out += out_stride; vst1_u8(out, p5); out += out_stride; vst1_u8(out, p6); out += out_stride; vst1_u8(out, p7); #undef dct_trn8_8 #undef dct_trn8_16 #undef dct_trn8_32 } #undef dct_long_mul #undef dct_long_mac #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_pass } #endif // STBI_NEON #define STBI__MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value static stbi_uc stbi__get_marker(stbi__jpeg *j) { stbi_uc x; if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } x = stbi__get8(j->s); if (x != 0xff) return STBI__MARKER_none; while (x == 0xff) x = stbi__get8(j->s); return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, stbi__jpeg_reset the entropy decoder and // the dc prediction static void stbi__jpeg_reset(stbi__jpeg *j) { j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; j->marker = STBI__MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; j->eob_run = 0; // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, // since we don't even allow 1<<30 pixels } static int stbi__parse_entropy_coded_data(stbi__jpeg *z) { stbi__jpeg_reset(z); if (!z->progressive) { if (z->scan_n == 1) { int i, j; STBI_SIMD_ALIGN(short, data[64]); int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x + 7) >> 3; int h = (z->img_comp[n].y + 7) >> 3; for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2*j * 8 + i * 8, z->img_comp[n].w2, data); // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i, j, k, x, y; STBI_SIMD_ALIGN(short, data[64]); for (j = 0; j < z->img_mcu_y; ++j) { for (i = 0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k = 0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y = 0; y < z->img_comp[n].v; ++y) { for (x = 0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x) * 8; int y2 = (j*z->img_comp[n].v + y) * 8; int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2*y2 + x2, z->img_comp[n].w2, data); } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } else { if (z->scan_n == 1) { int i, j; int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x + 7) >> 3; int h = (z->img_comp[n].y + 7) >> 3; for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); if (z->spec_start == 0) { if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } else { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) return 0; } // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i, j, k, x, y; for (j = 0; j < z->img_mcu_y; ++j) { for (i = 0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k = 0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y = 0; y < z->img_comp[n].v; ++y) { for (x = 0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x); int y2 = (j*z->img_comp[n].v + y); short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } } static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant) { int i; for (i = 0; i < 64; ++i) data[i] *= dequant[i]; } static void stbi__jpeg_finish(stbi__jpeg *z) { if (z->progressive) { // dequantize and idct the data int i, j, n; for (n = 0; n < z->s->img_n; ++n) { int w = (z->img_comp[n].x + 7) >> 3; int h = (z->img_comp[n].y + 7) >> 3; for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2*j * 8 + i * 8, z->img_comp[n].w2, data); } } } } } static int stbi__process_marker(stbi__jpeg *z, int m) { int L; switch (m) { case STBI__MARKER_none: // no marker found return stbi__err("expected marker", "Corrupt JPEG"); case 0xDD: // DRI - specify restart interval if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len", "Corrupt JPEG"); z->restart_interval = stbi__get16be(z->s); return 1; case 0xDB: // DQT - define quantization table L = stbi__get16be(z->s) - 2; while (L > 0) { int q = stbi__get8(z->s); int p = q >> 4; int t = q & 15, i; if (p != 0) return stbi__err("bad DQT type", "Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table", "Corrupt JPEG"); for (i = 0; i < 64; ++i) z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s); L -= 65; } return L == 0; case 0xC4: // DHT - define huffman table L = stbi__get16be(z->s) - 2; while (L > 0) { stbi_uc *v; int sizes[16], i, n = 0; int q = stbi__get8(z->s); int tc = q >> 4; int th = q & 15; if (tc > 1 || th > 3) return stbi__err("bad DHT header", "Corrupt JPEG"); for (i = 0; i < 16; ++i) { sizes[i] = stbi__get8(z->s); n += sizes[i]; } L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc + th, sizes)) return 0; v = z->huff_dc[th].values; } else { if (!stbi__build_huffman(z->huff_ac + th, sizes)) return 0; v = z->huff_ac[th].values; } for (i = 0; i < n; ++i) v[i] = stbi__get8(z->s); if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); L -= n; } return L == 0; } // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { stbi__skip(z->s, stbi__get16be(z->s) - 2); return 1; } return 0; } // after we see SOS static int stbi__process_scan_header(stbi__jpeg *z) { int i; int Ls = stbi__get16be(z->s); z->scan_n = stbi__get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int)z->s->img_n) return stbi__err("bad SOS component count", "Corrupt JPEG"); if (Ls != 6 + 2 * z->scan_n) return stbi__err("bad SOS len", "Corrupt JPEG"); for (i = 0; i < z->scan_n; ++i) { int id = stbi__get8(z->s), which; int q = stbi__get8(z->s); for (which = 0; which < z->s->img_n; ++which) if (z->img_comp[which].id == id) break; if (which == z->s->img_n) return 0; // no match z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff", "Corrupt JPEG"); z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff", "Corrupt JPEG"); z->order[i] = which; } { int aa; z->spec_start = stbi__get8(z->s); z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 aa = stbi__get8(z->s); z->succ_high = (aa >> 4); z->succ_low = (aa & 15); if (z->progressive) { if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) return stbi__err("bad SOS", "Corrupt JPEG"); } else { if (z->spec_start != 0) return stbi__err("bad SOS", "Corrupt JPEG"); if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS", "Corrupt JPEG"); z->spec_end = 63; } } return 1; } static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) { int i; for (i = 0; i < ncomp; ++i) { if (z->img_comp[i].raw_data) { STBI_FREE(z->img_comp[i].raw_data); z->img_comp[i].raw_data = NULL; z->img_comp[i].data = NULL; } if (z->img_comp[i].raw_coeff) { STBI_FREE(z->img_comp[i].raw_coeff); z->img_comp[i].raw_coeff = 0; z->img_comp[i].coeff = 0; } if (z->img_comp[i].linebuf) { STBI_FREE(z->img_comp[i].linebuf); z->img_comp[i].linebuf = NULL; } } return why; } static int stbi__process_frame_header(stbi__jpeg *z, int scan) { stbi__context *s = z->s; int Lf, p, i, q, h_max = 1, v_max = 1, c; Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit", "JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires c = stbi__get8(s); if (c != 3 && c != 1) return stbi__err("bad component count", "Corrupt JPEG"); // JFIF requires s->img_n = c; for (i = 0; i < c; ++i) { z->img_comp[i].data = NULL; z->img_comp[i].linebuf = NULL; } if (Lf != 8 + 3 * s->img_n) return stbi__err("bad SOF len", "Corrupt JPEG"); z->rgb = 0; for (i = 0; i < s->img_n; ++i) { static unsigned char rgb[3] = { 'R', 'G', 'B' }; z->img_comp[i].id = stbi__get8(s); if (z->img_comp[i].id != i + 1) // JFIF requires if (z->img_comp[i].id != i) { // some version of jpegtran outputs non-JFIF-compliant files! // somethings output this (see http://fileformats.archiveteam.org/wiki/JPEG#Color_format) if (z->img_comp[i].id != rgb[i]) return stbi__err("bad component ID", "Corrupt JPEG"); ++z->rgb; } q = stbi__get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H", "Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V", "Corrupt JPEG"); z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ", "Corrupt JPEG"); } if (scan != STBI__SCAN_load) return 1; if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); for (i = 0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; // these sizes can't be more than 17 bits z->img_mcu_x = (s->img_x + z->img_mcu_w - 1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h - 1) / z->img_mcu_h; for (i = 0; i < s->img_n; ++i) { // number of effective pixels (e.g. for non-interleaved MCU) z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max - 1) / h_max; z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max - 1) / v_max; // to simplify generation, we'll allocate enough memory to decode // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion // // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) // so these muls can't overflow with 32-bit ints (which we require) z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; z->img_comp[i].coeff = 0; z->img_comp[i].raw_coeff = 0; z->img_comp[i].linebuf = NULL; z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); if (z->img_comp[i].raw_data == NULL) return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory")); // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc*)(((size_t)z->img_comp[i].raw_data + 15) & ~15); if (z->progressive) { // w2, h2 are multiples of 8 (see above) z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); if (z->img_comp[i].raw_coeff == NULL) return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory")); z->img_comp[i].coeff = (short*)(((size_t)z->img_comp[i].raw_coeff + 15) & ~15); } } return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) #define stbi__DNL(x) ((x) == 0xdc) #define stbi__SOI(x) ((x) == 0xd8) #define stbi__EOI(x) ((x) == 0xd9) #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) #define stbi__SOS(x) ((x) == 0xda) #define stbi__SOF_progressive(x) ((x) == 0xc2) static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) { int m; z->marker = STBI__MARKER_none; // initialize cached marker to empty m = stbi__get_marker(z); if (!stbi__SOI(m)) return stbi__err("no SOI", "Corrupt JPEG"); if (scan == STBI__SCAN_type) return 1; m = stbi__get_marker(z); while (!stbi__SOF(m)) { if (!stbi__process_marker(z, m)) return 0; m = stbi__get_marker(z); while (m == STBI__MARKER_none) { // some files have extra padding after their blocks, so ok, we'll scan if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); m = stbi__get_marker(z); } } z->progressive = stbi__SOF_progressive(m); if (!stbi__process_frame_header(z, scan)) return 0; return 1; } // decode image to YCbCr format static int stbi__decode_jpeg_image(stbi__jpeg *j) { int m; for (m = 0; m < 4; m++) { j->img_comp[m].raw_data = NULL; j->img_comp[m].raw_coeff = NULL; } j->restart_interval = 0; if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; m = stbi__get_marker(j); while (!stbi__EOI(m)) { if (stbi__SOS(m)) { if (!stbi__process_scan_header(j)) return 0; if (!stbi__parse_entropy_coded_data(j)) return 0; if (j->marker == STBI__MARKER_none) { // handle 0s at the end of image data from IP Kamera 9060 while (!stbi__at_eof(j->s)) { int x = stbi__get8(j->s); if (x == 255) { j->marker = stbi__get8(j->s); break; } else if (x != 0) { return stbi__err("junk before marker", "Corrupt JPEG"); } } // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 } } else { if (!stbi__process_marker(j, m)) return 0; } m = stbi__get_marker(j); } if (j->progressive) stbi__jpeg_finish(j); return 1; } // static jfif-centered resampling (across block boundaries) typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, int w, int hs); #define stbi__div4(x) ((stbi_uc) ((x) >> 2)) static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); STBI_NOTUSED(hs); return in_near; } static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); for (i = 0; i < w; ++i) out[i] = stbi__div4(3 * in_near[i] + in_far[i] + 2); return out; } static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; stbi_uc *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation out[0] = out[1] = input[0]; return out; } out[0] = input[0]; out[1] = stbi__div4(input[0] * 3 + input[1] + 2); for (i = 1; i < w - 1; ++i) { int n = 3 * input[i] + 2; out[i * 2 + 0] = stbi__div4(n + input[i - 1]); out[i * 2 + 1] = stbi__div4(n + input[i + 1]); } out[i * 2 + 0] = stbi__div4(input[w - 2] * 3 + input[w - 1] + 2); out[i * 2 + 1] = input[w - 1]; STBI_NOTUSED(in_far); STBI_NOTUSED(hs); return out; } #define stbi__div16(x) ((stbi_uc) ((x) >> 4)) static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i, t0, t1; if (w == 1) { out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); return out; } t1 = 3 * in_near[0] + in_far[0]; out[0] = stbi__div4(t1 + 2); for (i = 1; i < w; ++i) { t0 = t1; t1 = 3 * in_near[i] + in_far[i]; out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); out[i * 2] = stbi__div16(3 * t1 + t0 + 8); } out[w * 2 - 1] = stbi__div4(t1 + 2); STBI_NOTUSED(hs); return out; } #if defined(STBI_SSE2) || defined(STBI_NEON) static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i = 0, t0, t1; if (w == 1) { out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); return out; } t1 = 3 * in_near[0] + in_far[0]; // process groups of 8 pixels for as long as we can. // note we can't handle the last pixel in a row in this loop // because we need to handle the filter boundary conditions. for (; i < ((w - 1) & ~7); i += 8) { #if defined(STBI_SSE2) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) __m128i zero = _mm_setzero_si128(); __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); __m128i farw = _mm_unpacklo_epi8(farb, zero); __m128i nearw = _mm_unpacklo_epi8(nearb, zero); __m128i diff = _mm_sub_epi16(farw, nearw); __m128i nears = _mm_slli_epi16(nearw, 2); __m128i curr = _mm_add_epi16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. __m128i prv0 = _mm_slli_si128(curr, 2); __m128i nxt0 = _mm_srli_si128(curr, 2); __m128i prev = _mm_insert_epi16(prv0, t1, 0); __m128i next = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. __m128i bias = _mm_set1_epi16(8); __m128i curs = _mm_slli_epi16(curr, 2); __m128i prvd = _mm_sub_epi16(prev, curr); __m128i nxtd = _mm_sub_epi16(next, curr); __m128i curb = _mm_add_epi16(curs, bias); __m128i even = _mm_add_epi16(prvd, curb); __m128i odd = _mm_add_epi16(nxtd, curb); // interleave even and odd pixels, then undo scaling. __m128i int0 = _mm_unpacklo_epi16(even, odd); __m128i int1 = _mm_unpackhi_epi16(even, odd); __m128i de0 = _mm_srli_epi16(int0, 4); __m128i de1 = _mm_srli_epi16(int1, 4); // pack and write output __m128i outv = _mm_packus_epi16(de0, de1); _mm_storeu_si128((__m128i *) (out + i * 2), outv); #elif defined(STBI_NEON) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) uint8x8_t farb = vld1_u8(in_far + i); uint8x8_t nearb = vld1_u8(in_near + i); int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); int16x8_t curr = vaddq_s16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. int16x8_t prv0 = vextq_s16(curr, curr, 7); int16x8_t nxt0 = vextq_s16(curr, curr, 1); int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); int16x8_t next = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. int16x8_t curs = vshlq_n_s16(curr, 2); int16x8_t prvd = vsubq_s16(prev, curr); int16x8_t nxtd = vsubq_s16(next, curr); int16x8_t even = vaddq_s16(curs, prvd); int16x8_t odd = vaddq_s16(curs, nxtd); // undo scaling and round, then store with even/odd phases interleaved uint8x8x2_t o; o.val[0] = vqrshrun_n_s16(even, 4); o.val[1] = vqrshrun_n_s16(odd, 4); vst2_u8(out + i * 2, o); #endif // "previous" value for next iter t1 = 3 * in_near[i + 7] + in_far[i + 7]; } t0 = t1; t1 = 3 * in_near[i] + in_far[i]; out[i * 2] = stbi__div16(3 * t1 + t0 + 8); for (++i; i < w; ++i) { t0 = t1; t1 = 3 * in_near[i] + in_far[i]; out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); out[i * 2] = stbi__div16(3 * t1 + t0 + 8); } out[w * 2 - 1] = stbi__div4(t1 + 2); STBI_NOTUSED(hs); return out; } #endif static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // resample with nearest-neighbor int i, j; STBI_NOTUSED(in_far); for (i = 0; i < w; ++i) for (j = 0; j < hs; ++j) out[i*hs + j] = in_near[i]; return out; } #ifdef STBI_JPEG_OLD // this is the same YCbCr-to-RGB calculation that stb_image has used // historically before the algorithm changes in 1.49 #define float2fixed(x) ((int) ((x) * 65536 + 0.5)) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; for (i = 0; i < count; ++i) { int y_fixed = (y[i] << 16) + 32768; // rounding int r, g, b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr*float2fixed(1.40200f); g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); b = y_fixed + cb*float2fixed(1.77200f); r >>= 16; g >>= 16; b >>= 16; if ((unsigned)r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned)g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned)b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #else // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar #define float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; for (i = 0; i < count; ++i) { int y_fixed = (y[i] << 20) + (1 << 19); // rounding int r, g, b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* float2fixed(1.40200f); g = y_fixed + (cr*-float2fixed(0.71414f)) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned)r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned)g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned)b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #endif #if defined(STBI_SSE2) || defined(STBI_NEON) static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) { int i = 0; #ifdef STBI_SSE2 // step == 3 is pretty ugly on the final interleave, and i'm not convinced // it's useful in practice (you wouldn't use it for textures, for example). // so just accelerate step == 4 case. if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. __m128i signflip = _mm_set1_epi8(-0x80); __m128i cr_const0 = _mm_set1_epi16((short)(1.40200f*4096.0f + 0.5f)); __m128i cr_const1 = _mm_set1_epi16(-(short)(0.71414f*4096.0f + 0.5f)); __m128i cb_const0 = _mm_set1_epi16(-(short)(0.34414f*4096.0f + 0.5f)); __m128i cb_const1 = _mm_set1_epi16((short)(1.77200f*4096.0f + 0.5f)); __m128i y_bias = _mm_set1_epi8((char)(unsigned char)128); __m128i xw = _mm_set1_epi16(255); // alpha channel for (; i + 7 < count; i += 8) { // load __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y + i)); __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr + i)); __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb + i)); __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 // unpack to short (and left-shift cr, cb by 8) __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); // color transform __m128i yws = _mm_srli_epi16(yw, 4); __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); __m128i rws = _mm_add_epi16(cr0, yws); __m128i gwt = _mm_add_epi16(cb0, yws); __m128i bws = _mm_add_epi16(yws, cb1); __m128i gws = _mm_add_epi16(gwt, cr1); // descale __m128i rw = _mm_srai_epi16(rws, 4); __m128i bw = _mm_srai_epi16(bws, 4); __m128i gw = _mm_srai_epi16(gws, 4); // back to byte, set up for transpose __m128i brb = _mm_packus_epi16(rw, bw); __m128i gxb = _mm_packus_epi16(gw, xw); // transpose to interleave channels __m128i t0 = _mm_unpacklo_epi8(brb, gxb); __m128i t1 = _mm_unpackhi_epi8(brb, gxb); __m128i o0 = _mm_unpacklo_epi16(t0, t1); __m128i o1 = _mm_unpackhi_epi16(t0, t1); // store _mm_storeu_si128((__m128i *) (out + 0), o0); _mm_storeu_si128((__m128i *) (out + 16), o1); out += 32; } } #endif #ifdef STBI_NEON // in this version, step=3 support would be easy to add. but is there demand? if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. uint8x8_t signflip = vdup_n_u8(0x80); int16x8_t cr_const0 = vdupq_n_s16((short)(1.40200f*4096.0f + 0.5f)); int16x8_t cr_const1 = vdupq_n_s16(-(short)(0.71414f*4096.0f + 0.5f)); int16x8_t cb_const0 = vdupq_n_s16(-(short)(0.34414f*4096.0f + 0.5f)); int16x8_t cb_const1 = vdupq_n_s16((short)(1.77200f*4096.0f + 0.5f)); for (; i + 7 < count; i += 8) { // load uint8x8_t y_bytes = vld1_u8(y + i); uint8x8_t cr_bytes = vld1_u8(pcr + i); uint8x8_t cb_bytes = vld1_u8(pcb + i); int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); // expand to s16 int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); int16x8_t crw = vshll_n_s8(cr_biased, 7); int16x8_t cbw = vshll_n_s8(cb_biased, 7); // color transform int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); int16x8_t rws = vaddq_s16(yws, cr0); int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); int16x8_t bws = vaddq_s16(yws, cb1); // undo scaling, round, convert to byte uint8x8x4_t o; o.val[0] = vqrshrun_n_s16(rws, 4); o.val[1] = vqrshrun_n_s16(gws, 4); o.val[2] = vqrshrun_n_s16(bws, 4); o.val[3] = vdup_n_u8(255); // store, interleaving r/g/b/a vst4_u8(out, o); out += 8 * 4; } } #endif for (; i < count; ++i) { int y_fixed = (y[i] << 20) + (1 << 19); // rounding int r, g, b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* float2fixed(1.40200f); g = y_fixed + cr*-float2fixed(0.71414f) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned)r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned)g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned)b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #endif // set up the kernels static void stbi__setup_jpeg(stbi__jpeg *j) { j->idct_block_kernel = stbi__idct_block; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; #ifdef STBI_SSE2 if (stbi__sse2_available()) { j->idct_block_kernel = stbi__idct_simd; #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; } #endif #ifdef STBI_NEON j->idct_block_kernel = stbi__idct_simd; #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } // clean up the temporary component buffers static void stbi__cleanup_jpeg(stbi__jpeg *j) { stbi__free_jpeg_components(j, j->s->img_n, 0); } typedef struct { resample_row_func resample; stbi_uc *line0, *line1; int hs, vs; // expansion factor in each axis int w_lores; // horizontal pixels pre-expansion int ystep; // how far through vertical expansion we are int ypos; // which pre-expansion row we're on } stbi__resample; static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { int n, decode_n; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); // load a jpeg image from whichever source, but leave in YCbCr format if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } // determine actual number of components to generate n = req_comp ? req_comp : z->s->img_n; if (z->s->img_n == 3 && n < 3) decode_n = 1; else decode_n = z->s->img_n; // resample and color-convert { int k; unsigned int i, j; stbi_uc *output; stbi_uc *coutput[4]; stbi__resample res_comp[4]; for (k = 0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; // allocate line buffer big enough for upsampling off the edges // with upsample factor of 4 z->img_comp[k].linebuf = (stbi_uc *)stbi__malloc(z->s->img_x + 3); if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } r->hs = z->img_h_max / z->img_comp[k].h; r->vs = z->img_v_max / z->img_comp[k].v; r->ystep = r->vs >> 1; r->w_lores = (z->s->img_x + r->hs - 1) / r->hs; r->ypos = 0; r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; else r->resample = stbi__resample_row_generic; } // can't error after this so, this is safe output = (stbi_uc *)stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } // now go ahead and resample for (j = 0; j < z->s->img_y; ++j) { stbi_uc *out = output + n * z->s->img_x * j; for (k = 0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { if (z->rgb == 3) { for (i = 0; i < z->s->img_x; ++i) { out[0] = y[i]; out[1] = coutput[1][i]; out[2] = coutput[2][i]; out[3] = 255; out += n; } } else { z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else for (i = 0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; out[3] = 255; // not used if n==3 out += n; } } else { stbi_uc *y = coutput[0]; if (n == 1) for (i = 0; i < z->s->img_x; ++i) out[i] = y[i]; else for (i = 0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; } } stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; if (comp) *comp = z->s->img_n; // report original components, not output return output; } } static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { unsigned char* result; stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); j->s = s; stbi__setup_jpeg(j); result = load_jpeg_image(j, x, y, comp, req_comp); STBI_FREE(j); return result; } static int stbi__jpeg_test(stbi__context *s) { int r; stbi__jpeg j; j.s = s; stbi__setup_jpeg(&j); r = stbi__decode_jpeg_header(&j, STBI__SCAN_type); stbi__rewind(s); return r; } static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) { if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { stbi__rewind(j->s); return 0; } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; if (comp) *comp = j->s->img_n; return 1; } static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) { int result; stbi__jpeg* j = (stbi__jpeg*)(stbi__malloc(sizeof(stbi__jpeg))); j->s = s; result = stbi__jpeg_info_raw(j, x, y, comp); STBI_FREE(j); return result; } #endif // public domain zlib decode v0.2 Sean Barrett 2006-11-18 // simple implementation // - all input must be provided in an upfront buffer // - all output is written to a single output buffer (can malloc/realloc) // performance // - fast huffman #ifndef STBI_NO_ZLIB // fast-way is faster to check than jpeg huffman, but slow way is slower #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) typedef struct { stbi__uint16 fast[1 << STBI__ZFAST_BITS]; stbi__uint16 firstcode[16]; int maxcode[17]; stbi__uint16 firstsymbol[16]; stbi_uc size[288]; stbi__uint16 value[288]; } stbi__zhuffman; stbi_inline static int stbi__bitreverse16(int n) { n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); return n; } stbi_inline static int stbi__bit_reverse(int v, int bits) { STBI_ASSERT(bits <= 16); // to bit reverse n bits, reverse 16 and shift // e.g. 11 bits, bit reverse and shift away 5 return stbi__bitreverse16(v) >> (16 - bits); } static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num) { int i, k = 0; int code, next_code[16], sizes[17]; // DEFLATE spec for generating codes memset(sizes, 0, sizeof(sizes)); memset(z->fast, 0, sizeof(z->fast)); for (i = 0; i < num; ++i) ++sizes[sizelist[i]]; sizes[0] = 0; for (i = 1; i < 16; ++i) if (sizes[i] >(1 << i)) return stbi__err("bad sizes", "Corrupt PNG"); code = 0; for (i = 1; i < 16; ++i) { next_code[i] = code; z->firstcode[i] = (stbi__uint16)code; z->firstsymbol[i] = (stbi__uint16)k; code = (code + sizes[i]); if (sizes[i]) if (code - 1 >= (1 << i)) return stbi__err("bad codelengths", "Corrupt PNG"); z->maxcode[i] = code << (16 - i); // preshift for inner loop code <<= 1; k += sizes[i]; } z->maxcode[16] = 0x10000; // sentinel for (i = 0; i < num; ++i) { int s = sizelist[i]; if (s) { int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; stbi__uint16 fastv = (stbi__uint16)((s << 9) | i); z->size[c] = (stbi_uc)s; z->value[c] = (stbi__uint16)i; if (s <= STBI__ZFAST_BITS) { int j = stbi__bit_reverse(next_code[s], s); while (j < (1 << STBI__ZFAST_BITS)) { z->fast[j] = fastv; j += (1 << s); } } ++next_code[s]; } } return 1; } // zlib-from-memory implementation for PNG reading // because PNG allows splitting the zlib stream arbitrarily, // and it's annoying structurally to have PNG call ZLIB call PNG, // we require PNG read all the IDATs and combine them into a single // memory buffer typedef struct { stbi_uc *zbuffer, *zbuffer_end; int num_bits; stbi__uint32 code_buffer; char *zout; char *zout_start; char *zout_end; int z_expandable; stbi__zhuffman z_length, z_distance; } stbi__zbuf; stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) { if (z->zbuffer >= z->zbuffer_end) return 0; return *z->zbuffer++; } static void stbi__fill_bits(stbi__zbuf *z) { do { STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); z->code_buffer |= (unsigned int)stbi__zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); } stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) { unsigned int k; if (z->num_bits < n) stbi__fill_bits(z); k = z->code_buffer & ((1 << n) - 1); z->code_buffer >>= n; z->num_bits -= n; return k; } static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) { int b, s, k; // not resolved by fast table, so compute it the slow way // use jpeg approach, which requires MSbits at top k = stbi__bit_reverse(a->code_buffer, 16); for (s = STBI__ZFAST_BITS + 1; ; ++s) if (k < z->maxcode[s]) break; if (s == 16) return -1; // invalid code! // code size is s, so: b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s]; STBI_ASSERT(z->size[b] == s); a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) { int b, s; if (a->num_bits < 16) stbi__fill_bits(a); b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; if (b) { s = b >> 9; a->code_buffer >>= s; a->num_bits -= s; return b & 511; } return stbi__zhuffman_decode_slowpath(a, z); } static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes { char *q; int cur, limit, old_limit; z->zout = zout; if (!z->z_expandable) return stbi__err("output buffer limit", "Corrupt PNG"); cur = (int)(z->zout - z->zout_start); limit = old_limit = (int)(z->zout_end - z->zout_start); while (cur + n > limit) limit *= 2; q = (char *)STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); STBI_NOTUSED(old_limit); if (q == NULL) return stbi__err("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; z->zout_end = q + limit; return 1; } static int stbi__zlength_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static int stbi__zlength_extra[31] = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0 }; static int stbi__zdist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; static int stbi__parse_huffman_block(stbi__zbuf *a) { char *zout = a->zout; for (;;) { int z = stbi__zhuffman_decode(a, &a->z_length); if (z < 256) { if (z < 0) return stbi__err("bad huffman code", "Corrupt PNG"); // error in huffman codes if (zout >= a->zout_end) { if (!stbi__zexpand(a, zout, 1)) return 0; zout = a->zout; } *zout++ = (char)z; } else { stbi_uc *p; int len, dist; if (z == 256) { a->zout = zout; return 1; } z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); if (z < 0) return stbi__err("bad huffman code", "Corrupt PNG"); dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist", "Corrupt PNG"); if (zout + len > a->zout_end) { if (!stbi__zexpand(a, zout, len)) return 0; zout = a->zout; } p = (stbi_uc *)(zout - dist); if (dist == 1) { // run of one byte; common in images. stbi_uc v = *p; if (len) { do *zout++ = v; while (--len); } } else { if (len) { do *zout++ = *p++; while (--len); } } } } } static int stbi__compute_huffman_codes(stbi__zbuf *a) { static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; stbi__zhuffman z_codelength; stbi_uc lencodes[286 + 32 + 137];//padding for maximum single op stbi_uc codelength_sizes[19]; int i, n; int hlit = stbi__zreceive(a, 5) + 257; int hdist = stbi__zreceive(a, 5) + 1; int hclen = stbi__zreceive(a, 4) + 4; int ntot = hlit + hdist; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i = 0; i < hclen; ++i) { int s = stbi__zreceive(a, 3); codelength_sizes[length_dezigzag[i]] = (stbi_uc)s; } if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; while (n < ntot) { int c = stbi__zhuffman_decode(a, &z_codelength); if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc)c; else { stbi_uc fill = 0; if (c == 16) { c = stbi__zreceive(a, 2) + 3; if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); fill = lencodes[n - 1]; } else if (c == 17) c = stbi__zreceive(a, 3) + 3; else { STBI_ASSERT(c == 18); c = stbi__zreceive(a, 7) + 11; } if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); memset(lencodes + n, fill, c); n += c; } } if (n != ntot) return stbi__err("bad codelengths", "Corrupt PNG"); if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, lencodes + hlit, hdist)) return 0; return 1; } static int stbi__parse_uncompressed_block(stbi__zbuf *a) { stbi_uc header[4]; int len, nlen, k; if (a->num_bits & 7) stbi__zreceive(a, a->num_bits & 7); // discard // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { header[k++] = (stbi_uc)(a->code_buffer & 255); // suppress MSVC run-time check a->code_buffer >>= 8; a->num_bits -= 8; } STBI_ASSERT(a->num_bits == 0); // now fill header the normal way while (k < 4) header[k++] = stbi__zget8(a); len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt", "Corrupt PNG"); if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer", "Corrupt PNG"); if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, a->zout, len)) return 0; memcpy(a->zout, a->zbuffer, len); a->zbuffer += len; a->zout += len; return 1; } static int stbi__parse_zlib_header(stbi__zbuf *a) { int cmf = stbi__zget8(a); int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); if ((cmf * 256 + flg) % 31 != 0) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict", "Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression", "Corrupt PNG"); // DEFLATE required for png // window = 1 << (8 + cinfo)... but who cares, we fully buffer output return 1; } // @TODO: should statically initialize these for optimal thread safety static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32]; static void stbi__init_zdefaults(void) { int i; // use <= to match clearly with spec for (i = 0; i <= 143; ++i) stbi__zdefault_length[i] = 8; for (; i <= 255; ++i) stbi__zdefault_length[i] = 9; for (; i <= 279; ++i) stbi__zdefault_length[i] = 7; for (; i <= 287; ++i) stbi__zdefault_length[i] = 8; for (i = 0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; } static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) { int final, type; if (parse_header) if (!stbi__parse_zlib_header(a)) return 0; a->num_bits = 0; a->code_buffer = 0; do { final = stbi__zreceive(a, 1); type = stbi__zreceive(a, 2); if (type == 0) { if (!stbi__parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths if (!stbi__zdefault_distance[31]) stbi__init_zdefaults(); if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, 288)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; } if (!stbi__parse_huffman_block(a)) return 0; } } while (!final); return 1; } static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; a->z_expandable = exp; return stbi__parse_zlib(a, parse_header); } STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) { stbi__zbuf a; char *p = (char *)stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *)buffer; a.zbuffer_end = (stbi_uc *)buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { if (outlen) *outlen = (int)(a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) { stbi__zbuf a; char *p = (char *)stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *)buffer; a.zbuffer_end = (stbi_uc *)buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { if (outlen) *outlen = (int)(a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *)ibuffer; a.zbuffer_end = (stbi_uc *)ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) return (int)(a.zout - a.zout_start); else return -1; } STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) { stbi__zbuf a; char *p = (char *)stbi__malloc(16384); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *)buffer; a.zbuffer_end = (stbi_uc *)buffer + len; if (stbi__do_zlib(&a, p, 16384, 1, 0)) { if (outlen) *outlen = (int)(a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *)ibuffer; a.zbuffer_end = (stbi_uc *)ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) return (int)(a.zout - a.zout_start); else return -1; } #endif // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 // simple implementation // - only 8-bit samples // - no CRC checking // - allocates lots of intermediate memory // - avoids problem of streaming data between subsystems // - avoids explicit window management // performance // - uses stb_zlib, a PD zlib implementation with fast huffman decoding #ifndef STBI_NO_PNG typedef struct { stbi__uint32 length; stbi__uint32 type; } stbi__pngchunk; static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) { stbi__pngchunk c; c.length = stbi__get32be(s); c.type = stbi__get32be(s); return c; } static int stbi__check_png_header(stbi__context *s) { static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i = 0; i < 8; ++i) if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig", "Not a PNG"); return 1; } typedef struct { stbi__context *s; stbi_uc *idata, *expanded, *out; int depth; } stbi__png; enum { STBI__F_none = 0, STBI__F_sub = 1, STBI__F_up = 2, STBI__F_avg = 3, STBI__F_paeth = 4, // synthetic filters used for first scanline to avoid needing a dummy row of 0s STBI__F_avg_first, STBI__F_paeth_first }; static stbi_uc first_row_filter[5] = { STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first }; static int stbi__paeth(int a, int b, int c) { int p = a + b - c; int pa = abs(p - a); int pb = abs(p - b); int pc = abs(p - c); if (pa <= pb && pa <= pc) return a; if (pb <= pc) return b; return c; } static stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { int bytes = (depth == 16 ? 2 : 1); stbi__context *s = a->s; stbi__uint32 i, j, stride = x*out_n*bytes; stbi__uint32 img_len, img_width_bytes; int k; int img_n = s->img_n; // copy it into a local for later int output_bytes = out_n*bytes; int filter_bytes = img_n*bytes; int width = x; STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1); a->out = (stbi_uc *)stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); img_width_bytes = (((img_n * x * depth) + 7) >> 3); img_len = (img_width_bytes + 1) * y; if (s->img_x == x && s->img_y == y) { if (raw_len != img_len) return stbi__err("not enough pixels", "Corrupt PNG"); } else { // interlaced: if (raw_len < img_len) return stbi__err("not enough pixels", "Corrupt PNG"); } for (j = 0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *prior = cur - stride; int filter = *raw++; if (filter > 4) return stbi__err("invalid filter", "Corrupt PNG"); if (depth < 8) { STBI_ASSERT(img_width_bytes <= x); cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place filter_bytes = 1; width = img_width_bytes; } // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; // handle first byte explicitly for (k = 0; k < filter_bytes; ++k) { switch (filter) { case STBI__F_none: cur[k] = raw[k]; break; case STBI__F_sub: cur[k] = raw[k]; break; case STBI__F_up: cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; case STBI__F_avg: cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1)); break; case STBI__F_paeth: cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0, prior[k], 0)); break; case STBI__F_avg_first: cur[k] = raw[k]; break; case STBI__F_paeth_first: cur[k] = raw[k]; break; } } if (depth == 8) { if (img_n != out_n) cur[img_n] = 255; // first pixel raw += img_n; cur += out_n; prior += out_n; } else if (depth == 16) { if (img_n != out_n) { cur[filter_bytes] = 255; // first pixel top byte cur[filter_bytes + 1] = 255; // first pixel bottom byte } raw += filter_bytes; cur += output_bytes; prior += output_bytes; } else { raw += 1; cur += 1; prior += 1; } // this is a little gross, so that we don't switch per-pixel or per-component if (depth < 8 || img_n == out_n) { int nk = (width - 1)*filter_bytes; #define STBI__CASE(f) \ case f: \ for (k=0; k < nk; ++k) switch (filter) { // "none" filter turns into a memcpy here; make that explicit. case STBI__F_none: memcpy(cur, raw, nk); break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - filter_bytes], prior[k], prior[k - filter_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - filter_bytes], 0, 0)); } break; } #undef STBI__CASE raw += nk; } else { STBI_ASSERT(img_n + 1 == out_n); #define STBI__CASE(f) \ case f: \ for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ for (k=0; k < filter_bytes; ++k) switch (filter) { STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k - output_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - output_bytes]) >> 1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - output_bytes], prior[k], prior[k - output_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k - output_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - output_bytes], 0, 0)); } break; } #undef STBI__CASE // the loop above sets the high byte of the pixels' alpha, but for // 16 bit png files we also need the low byte set. we'll do that here. if (depth == 16) { cur = a->out + stride*j; // start at the beginning of the row again for (i = 0; i < x; ++i, cur += output_bytes) { cur[filter_bytes + 1] = 255; } } } } // we make a separate pass to expand bits to pixels; for performance, // this could run two scanlines behind the above code, so it won't // intefere with filtering but will still be in the cache. if (depth < 8) { for (j = 0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range // note that the final byte might overshoot and write more data than desired. // we can allocate enough data that this never writes out of memory, but it // could also overwrite the next scanline. can it overwrite non-empty data // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. // so we need to explicitly clamp the final ones if (depth == 4) { for (k = x*img_n; k >= 2; k -= 2, ++in) { *cur++ = scale * ((*in >> 4)); *cur++ = scale * ((*in) & 0x0f); } if (k > 0) *cur++ = scale * ((*in >> 4)); } else if (depth == 2) { for (k = x*img_n; k >= 4; k -= 4, ++in) { *cur++ = scale * ((*in >> 6)); *cur++ = scale * ((*in >> 4) & 0x03); *cur++ = scale * ((*in >> 2) & 0x03); *cur++ = scale * ((*in) & 0x03); } if (k > 0) *cur++ = scale * ((*in >> 6)); if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); } else if (depth == 1) { for (k = x*img_n; k >= 8; k -= 8, ++in) { *cur++ = scale * ((*in >> 7)); *cur++ = scale * ((*in >> 6) & 0x01); *cur++ = scale * ((*in >> 5) & 0x01); *cur++ = scale * ((*in >> 4) & 0x01); *cur++ = scale * ((*in >> 3) & 0x01); *cur++ = scale * ((*in >> 2) & 0x01); *cur++ = scale * ((*in >> 1) & 0x01); *cur++ = scale * ((*in) & 0x01); } if (k > 0) *cur++ = scale * ((*in >> 7)); if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); } if (img_n != out_n) { int q; // insert alpha = 255 cur = a->out + stride*j; if (img_n == 1) { for (q = x - 1; q >= 0; --q) { cur[q * 2 + 1] = 255; cur[q * 2 + 0] = cur[q]; } } else { STBI_ASSERT(img_n == 3); for (q = x - 1; q >= 0; --q) { cur[q * 4 + 3] = 255; cur[q * 4 + 2] = cur[q * 3 + 2]; cur[q * 4 + 1] = cur[q * 3 + 1]; cur[q * 4 + 0] = cur[q * 3 + 0]; } } } } } else if (depth == 16) { // force the image data from big-endian to platform-native. // this is done in a separate pass due to the decoding relying // on the data being untouched, but could probably be done // per-line during decode if care is taken. stbi_uc *cur = a->out; stbi__uint16 *cur16 = (stbi__uint16*)cur; for (i = 0; i < x*y*out_n; ++i, cur16++, cur += 2) { *cur16 = (cur[0] << 8) | cur[1]; } } return 1; } static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { int bytes = (depth == 16 ? 2 : 1); int out_bytes = out_n * bytes; stbi_uc *final; int p; if (!interlaced) return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); // de-interlacing final = (stbi_uc *)stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); for (p = 0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; int xspc[] = { 8,8,4,4,2,2,1 }; int yspc[] = { 8,8,8,4,4,2,2 }; int i, j, x, y; // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p]; if (x && y) { stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { STBI_FREE(final); return 0; } for (j = 0; j < y; ++j) { for (i = 0; i < x; ++i) { int out_y = j*yspc[p] + yorig[p]; int out_x = i*xspc[p] + xorig[p]; memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, a->out + (j*x + i)*out_bytes, out_bytes); } } STBI_FREE(a->out); image_data += img_len; image_data_len -= img_len; } } a->out = final; return 1; } static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; // compute color-based transparency, assuming we've // already got 255 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i = 0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 255); p += 2; } } else { for (i = 0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi__uint16 *p = (stbi__uint16*)z->out; // compute color-based transparency, assuming we've // already got 65535 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i = 0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 65535); p += 2; } } else { for (i = 0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; p = (stbi_uc *)stbi__malloc_mad2(pixel_count, pal_img_n, 0); if (p == NULL) return stbi__err("outofmem", "Out of memory"); // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { for (i = 0; i < pixel_count; ++i) { int n = orig[i] * 4; p[0] = palette[n]; p[1] = palette[n + 1]; p[2] = palette[n + 2]; p += 3; } } else { for (i = 0; i < pixel_count; ++i) { int n = orig[i] * 4; p[0] = palette[n]; p[1] = palette[n + 1]; p[2] = palette[n + 2]; p[3] = palette[n + 3]; p += 4; } } STBI_FREE(a->out); a->out = temp_out; STBI_NOTUSED(len); return 1; } static int stbi__unpremultiply_on_load = 0; static int stbi__de_iphone_flag = 0; STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; } STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { stbi__de_iphone_flag = flag_true_if_should_convert; } static void stbi__de_iphone(stbi__png *z) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; if (s->img_out_n == 3) { // convert bgr to rgb for (i = 0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 3; } } else { STBI_ASSERT(s->img_out_n == 4); if (stbi__unpremultiply_on_load) { // convert bgr to rgb and unpremultiply for (i = 0; i < pixel_count; ++i) { stbi_uc a = p[3]; stbi_uc t = p[0]; if (a) { p[0] = p[2] * 255 / a; p[1] = p[1] * 255 / a; p[2] = t * 255 / a; } else { p[0] = p[2]; p[2] = t; } p += 4; } } else { // convert bgr to rgb for (i = 0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 4; } } } } #define STBI__PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n = 0; stbi_uc has_trans = 0, tc[3]; stbi__uint16 tc16[3]; stbi__uint32 ioff = 0, idata_limit = 0, i, pal_len = 0; int first = 1, k, interlace = 0, color = 0, is_iphone = 0; stbi__context *s = z->s; z->expanded = NULL; z->idata = NULL; z->out = NULL; if (!stbi__check_png_header(s)) return 0; if (scan == STBI__SCAN_type) return 1; for (;;) { stbi__pngchunk c = stbi__get_chunk_header(s); switch (c.type) { case STBI__PNG_TYPE('C', 'g', 'B', 'I'): is_iphone = 1; stbi__skip(s, c.length); break; case STBI__PNG_TYPE('I', 'H', 'D', 'R'): { int comp, filter; if (!first) return stbi__err("multiple IHDR", "Corrupt PNG"); first = 0; if (c.length != 13) return stbi__err("bad IHDR len", "Corrupt PNG"); s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large", "Very large image (corrupt?)"); s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large", "Very large image (corrupt?)"); z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only", "PNG not supported: 1/2/4/8/16-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype", "Corrupt PNG"); if (color == 3 && z->depth == 16) return stbi__err("bad ctype", "Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype", "Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method", "Corrupt PNG"); filter = stbi__get8(s); if (filter) return stbi__err("bad filter method", "Corrupt PNG"); interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method", "Corrupt PNG"); if (!s->img_x || !s->img_y) return stbi__err("0-pixel image", "Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); if (scan == STBI__SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large", "Corrupt PNG"); // if SCAN_header, have to scan to see if we have a tRNS } break; } case STBI__PNG_TYPE('P', 'L', 'T', 'E'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (c.length > 256 * 3) return stbi__err("invalid PLTE", "Corrupt PNG"); pal_len = c.length / 3; if (pal_len * 3 != c.length) return stbi__err("invalid PLTE", "Corrupt PNG"); for (i = 0; i < pal_len; ++i) { palette[i * 4 + 0] = stbi__get8(s); palette[i * 4 + 1] = stbi__get8(s); palette[i * 4 + 2] = stbi__get8(s); palette[i * 4 + 3] = 255; } break; } case STBI__PNG_TYPE('t', 'R', 'N', 'S'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (z->idata) return stbi__err("tRNS after IDAT", "Corrupt PNG"); if (pal_img_n) { if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } if (pal_len == 0) return stbi__err("tRNS before PLTE", "Corrupt PNG"); if (c.length > pal_len) return stbi__err("bad tRNS len", "Corrupt PNG"); pal_img_n = 4; for (i = 0; i < c.length; ++i) palette[i * 4 + 3] = stbi__get8(s); } else { if (!(s->img_n & 1)) return stbi__err("tRNS with alpha", "Corrupt PNG"); if (c.length != (stbi__uint32)s->img_n * 2) return stbi__err("bad tRNS len", "Corrupt PNG"); has_trans = 1; if (z->depth == 16) { for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is } else { for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger } } break; } case STBI__PNG_TYPE('I', 'D', 'A', 'T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return stbi__err("no PLTE", "Corrupt PNG"); if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; STBI_NOTUSED(idata_limit_old); p = (stbi_uc *)STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata + ioff, c.length)) return stbi__err("outofdata", "Corrupt PNG"); ioff += c.length; break; } case STBI__PNG_TYPE('I', 'E', 'N', 'D'): { stbi__uint32 raw_len, bpl; if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (scan != STBI__SCAN_load) return 1; if (z->idata == NULL) return stbi__err("no IDAT", "Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *)stbi_zlib_decode_malloc_guesssize_headerflag((char *)z->idata, ioff, raw_len, (int *)&raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error STBI_FREE(z->idata); z->idata = NULL; if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n + 1; else s->img_out_n = s->img_n; if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; if (has_trans) { if (z->depth == 16) { if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; } else { if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; } } if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; } STBI_FREE(z->expanded); z->expanded = NULL; return 1; } default: // if critical, fail if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if ((c.type & (1 << 29)) == 0) { #ifndef STBI_NO_FAILURE_STRINGS // not threadsafe static char invalid_chunk[] = "XXXX PNG chunk not known"; invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); #endif return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); } stbi__skip(s, c.length); break; } // end of PNG chunk, read and skip CRC stbi__get32be(s); } } static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) { void *result = NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { if (p->depth < 8) ri->bits_per_channel = 8; else ri->bits_per_channel = p->depth; result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { if (ri->bits_per_channel == 8) result = stbi__convert_format((unsigned char *)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); else result = stbi__convert_format16((stbi__uint16 *)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; if (n) *n = p->s->img_n; } STBI_FREE(p->out); p->out = NULL; STBI_FREE(p->expanded); p->expanded = NULL; STBI_FREE(p->idata); p->idata = NULL; return result; } static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi__png p; p.s = s; return stbi__do_png(&p, x, y, comp, req_comp, ri); } static int stbi__png_test(stbi__context *s) { int r; r = stbi__check_png_header(s); stbi__rewind(s); return r; } static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) { if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { stbi__rewind(p->s); return 0; } if (x) *x = p->s->img_x; if (y) *y = p->s->img_y; if (comp) *comp = p->s->img_n; return 1; } static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) { stbi__png p; p.s = s; return stbi__png_info_raw(&p, x, y, comp); } #endif // Microsoft/Windows BMP image #ifndef STBI_NO_BMP static int stbi__bmp_test_raw(stbi__context *s) { int r; int sz; if (stbi__get8(s) != 'B') return 0; if (stbi__get8(s) != 'M') return 0; stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved stbi__get32le(s); // discard data offset sz = stbi__get32le(s); r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); return r; } static int stbi__bmp_test(stbi__context *s) { int r = stbi__bmp_test_raw(s); stbi__rewind(s); return r; } // returns 0..31 for the highest set bit static int stbi__high_bit(unsigned int z) { int n = 0; if (z == 0) return -1; if (z >= 0x10000) n += 16, z >>= 16; if (z >= 0x00100) n += 8, z >>= 8; if (z >= 0x00010) n += 4, z >>= 4; if (z >= 0x00004) n += 2, z >>= 2; if (z >= 0x00002) n += 1, z >>= 1; return n; } static int stbi__bitcount(unsigned int a) { a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits a = (a + (a >> 8)); // max 16 per 8 bits a = (a + (a >> 16)); // max 32 per 8 bits return a & 0xff; } static int stbi__shiftsigned(int v, int shift, int bits) { int result; int z = 0; if (shift < 0) v <<= -shift; else v >>= shift; result = v; z = bits; while (z < 8) { result += v >> z; z += bits; } return result; } typedef struct { int bpp, offset, hsz; unsigned int mr, mg, mb, ma, all_a; } stbi__bmp_data; static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) { int hsz; if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved info->offset = stbi__get32le(s); info->hsz = hsz = stbi__get32le(s); info->mr = info->mg = info->mb = info->ma = 0; if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = stbi__get16le(s); s->img_y = stbi__get16le(s); } else { s->img_x = stbi__get32le(s); s->img_y = stbi__get32le(s); } if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); info->bpp = stbi__get16le(s); if (info->bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit"); if (hsz != 12) { int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres stbi__get32le(s); // discard colorsused stbi__get32le(s); // discard max important if (hsz == 40 || hsz == 56) { if (hsz == 56) { stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); } if (info->bpp == 16 || info->bpp == 32) { if (compress == 0) { if (info->bpp == 32) { info->mr = 0xffu << 16; info->mg = 0xffu << 8; info->mb = 0xffu << 0; info->ma = 0xffu << 24; info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 } else { info->mr = 31u << 10; info->mg = 31u << 5; info->mb = 31u << 0; } } else if (compress == 3) { info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); // not documented, but generated by photoshop and handled by mspaint if (info->mr == info->mg && info->mg == info->mb) { // ?!?!? return stbi__errpuc("bad BMP", "bad BMP"); } } else return stbi__errpuc("bad BMP", "bad BMP"); } } else { int i; if (hsz != 108 && hsz != 124) return stbi__errpuc("bad BMP", "bad BMP"); info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->ma = stbi__get32le(s); stbi__get32le(s); // discard color space for (i = 0; i < 12; ++i) stbi__get32le(s); // discard color space parameters if (hsz == 124) { stbi__get32le(s); // discard rendering intent stbi__get32le(s); // discard offset of profile data stbi__get32le(s); // discard size of profile data stbi__get32le(s); // discard reserved } } } return (void *)1; } static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a; stbi_uc pal[256][4]; int psize = 0, i, j, width; int flip_vertically, pad, target; stbi__bmp_data info; STBI_NOTUSED(ri); info.all_a = 255; if (stbi__bmp_parse_header(s, &info) == NULL) return NULL; // error code already set flip_vertically = ((int)s->img_y) > 0; s->img_y = abs((int)s->img_y); mr = info.mr; mg = info.mg; mb = info.mb; ma = info.ma; all_a = info.all_a; if (info.hsz == 12) { if (info.bpp < 24) psize = (info.offset - 14 - 24) / 3; } else { if (info.bpp < 16) psize = (info.offset - 14 - info.hsz) >> 2; } s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert // sanity-check size if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) return stbi__errpuc("too large", "Corrupt BMP"); out = (stbi_uc *)stbi__malloc_mad3(target, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); if (info.bpp < 16) { int z = 0; if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } for (i = 0; i < psize; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } stbi__skip(s, info.offset - 14 - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); if (info.bpp == 4) width = (s->img_x + 1) >> 1; else if (info.bpp == 8) width = s->img_x; else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } pad = (-width) & 3; for (j = 0; j < (int)s->img_y; ++j) { for (i = 0; i < (int)s->img_x; i += 2) { int v = stbi__get8(s), v2 = 0; if (info.bpp == 4) { v2 = v & 15; v >>= 4; } out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; if (i + 1 == (int)s->img_x) break; v = (info.bpp == 8) ? stbi__get8(s) : v2; out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; } stbi__skip(s, pad); } } else { int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, gcount = 0, bcount = 0, acount = 0; int z = 0; int easy = 0; stbi__skip(s, info.offset - 14 - info.hsz); if (info.bpp == 24) width = 3 * s->img_x; else if (info.bpp == 16) width = 2 * s->img_x; else /* bpp = 32 and pad = 0 */ width = 0; pad = (-width) & 3; if (info.bpp == 24) { easy = 1; } else if (info.bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } // right shift amt to put high bit in position #7 rshift = stbi__high_bit(mr) - 7; rcount = stbi__bitcount(mr); gshift = stbi__high_bit(mg) - 7; gcount = stbi__bitcount(mg); bshift = stbi__high_bit(mb) - 7; bcount = stbi__bitcount(mb); ashift = stbi__high_bit(ma) - 7; acount = stbi__bitcount(ma); } for (j = 0; j < (int)s->img_y; ++j) { if (easy) { for (i = 0; i < (int)s->img_x; ++i) { unsigned char a; out[z + 2] = stbi__get8(s); out[z + 1] = stbi__get8(s); out[z + 0] = stbi__get8(s); z += 3; a = (easy == 2 ? stbi__get8(s) : 255); all_a |= a; if (target == 4) out[z++] = a; } } else { int bpp = info.bpp; for (i = 0; i < (int)s->img_x; ++i) { stbi__uint32 v = (bpp == 16 ? (stbi__uint32)stbi__get16le(s) : stbi__get32le(s)); int a; out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); all_a |= a; if (target == 4) out[z++] = STBI__BYTECAST(a); } } stbi__skip(s, pad); } } // if alpha channel is all 0s, replace with all 255s if (target == 4 && all_a == 0) for (i = 4 * s->img_x*s->img_y - 1; i >= 0; i -= 4) out[i] = 255; if (flip_vertically) { stbi_uc t; for (j = 0; j < (int)s->img_y >> 1; ++j) { stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y - 1 - j)*s->img_x*target; for (i = 0; i < (int)s->img_x*target; ++i) { t = p1[i], p1[i] = p2[i], p2[i] = t; } } } if (req_comp && req_comp != target) { out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; return out; } #endif // Targa Truevision - TGA // by Jonathan Dummer #ifndef STBI_NO_TGA // returns STBI_rgb or whatever, 0 on error static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) { // only RGB or RGBA (incl. 16bit) or grey allowed if (is_rgb16) *is_rgb16 = 0; switch (bits_per_pixel) { case 8: return STBI_grey; case 16: if (is_grey) return STBI_grey_alpha; // else: fall-through case 15: if (is_rgb16) *is_rgb16 = 1; return STBI_rgb; case 24: // fall-through case 32: return bits_per_pixel / 8; default: return 0; } } static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) { int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; int sz, tga_colormap_type; stbi__get8(s); // discard Offset tga_colormap_type = stbi__get8(s); // colormap type if (tga_colormap_type > 1) { stbi__rewind(s); return 0; // only RGB or indexed allowed } tga_image_type = stbi__get8(s); // image type if (tga_colormap_type == 1) { // colormapped (paletted) image if (tga_image_type != 1 && tga_image_type != 9) { stbi__rewind(s); return 0; } stbi__skip(s, 4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) { stbi__rewind(s); return 0; } stbi__skip(s, 4); // skip image x and y origin tga_colormap_bpp = sz; } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE if ((tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11)) { stbi__rewind(s); return 0; // only RGB or grey allowed, +/- RLE } stbi__skip(s, 9); // skip colormap specification and image x/y origin tga_colormap_bpp = 0; } tga_w = stbi__get16le(s); if (tga_w < 1) { stbi__rewind(s); return 0; // test width } tga_h = stbi__get16le(s); if (tga_h < 1) { stbi__rewind(s); return 0; // test height } tga_bits_per_pixel = stbi__get8(s); // bits per pixel stbi__get8(s); // ignore alpha bits if (tga_colormap_bpp != 0) { if ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { // when using a colormap, tga_bits_per_pixel is the size of the indexes // I don't think anything but 8 or 16bit indexes makes sense stbi__rewind(s); return 0; } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); } if (!tga_comp) { stbi__rewind(s); return 0; } if (x) *x = tga_w; if (y) *y = tga_h; if (comp) *comp = tga_comp; return 1; // seems to have passed everything } static int stbi__tga_test(stbi__context *s) { int res = 0; int sz, tga_color_type; stbi__get8(s); // discard Offset tga_color_type = stbi__get8(s); // color type if (tga_color_type > 1) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type if (tga_color_type == 1) { // colormapped (paletted) image if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 stbi__skip(s, 4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; stbi__skip(s, 4); // skip image x and y origin } else { // "normal" image w/o colormap if ((sz != 2) && (sz != 3) && (sz != 10) && (sz != 11)) goto errorEnd; // only RGB or grey allowed, +/- RLE stbi__skip(s, 9); // skip colormap specification and image x/y origin } if (stbi__get16le(s) < 1) goto errorEnd; // test width if (stbi__get16le(s) < 1) goto errorEnd; // test height sz = stbi__get8(s); // bits per pixel if ((tga_color_type == 1) && (sz != 8) && (sz != 16)) goto errorEnd; // for colormapped images, bpp is size of an index if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; res = 1; // if we got this far, everything's good and we can return 1 instead of 0 errorEnd: stbi__rewind(s); return res; } // read 16bit value and convert to 24bit RGB static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) { stbi__uint16 px = (stbi__uint16)stbi__get16le(s); stbi__uint16 fiveBitMask = 31; // we have 3 channels with 5bits each int r = (px >> 10) & fiveBitMask; int g = (px >> 5) & fiveBitMask; int b = px & fiveBitMask; // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later out[0] = (stbi_uc)((r * 255) / 31); out[1] = (stbi_uc)((g * 255) / 31); out[2] = (stbi_uc)((b * 255) / 31); // some people claim that the most significant bit might be used for alpha // (possibly if an alpha-bit is set in the "image descriptor byte") // but that only made 16bit test images completely translucent.. // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { // read in the TGA header stuff int tga_offset = stbi__get8(s); int tga_indexed = stbi__get8(s); int tga_image_type = stbi__get8(s); int tga_is_RLE = 0; int tga_palette_start = stbi__get16le(s); int tga_palette_len = stbi__get16le(s); int tga_palette_bits = stbi__get8(s); int tga_x_origin = stbi__get16le(s); int tga_y_origin = stbi__get16le(s); int tga_width = stbi__get16le(s); int tga_height = stbi__get16le(s); int tga_bits_per_pixel = stbi__get8(s); int tga_comp, tga_rgb16 = 0; int tga_inverted = stbi__get8(s); // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; unsigned char raw_data[4] = { 0 }; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; STBI_NOTUSED(ri); // do a tiny bit of precessing if (tga_image_type >= 8) { tga_image_type -= 8; tga_is_RLE = 1; } tga_inverted = 1 - ((tga_inverted >> 5) & 1); // If I'm paletted, then I'll use the number of bits from the palette if (tga_indexed) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); if (!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); // tga info *x = tga_width; *y = tga_height; if (comp) *comp = tga_comp; if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) return stbi__errpuc("too large", "Corrupt TGA"); tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) stbi__skip(s, tga_offset); if (!tga_indexed && !tga_is_RLE && !tga_rgb16) { for (i = 0; i < tga_height; ++i) { int row = tga_inverted ? tga_height - i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; stbi__getn(s, tga_row, tga_width * tga_comp); } } else { // do I need to load a palette? if (tga_indexed) { // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start); // load the palette tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); } if (tga_rgb16) { stbi_uc *pal_entry = tga_palette; STBI_ASSERT(tga_comp == STBI_rgb); for (i = 0; i < tga_palette_len; ++i) { stbi__tga_read_rgb16(s, pal_entry); pal_entry += tga_comp; } } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { STBI_FREE(tga_data); STBI_FREE(tga_palette); return stbi__errpuc("bad palette", "Corrupt TGA"); } } // load the data for (i = 0; i < tga_width * tga_height; ++i) { // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? if (tga_is_RLE) { if (RLE_count == 0) { // yep, get the next byte as a RLE command int RLE_cmd = stbi__get8(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; } else if (!RLE_repeating) { read_next_pixel = 1; } } else { read_next_pixel = 1; } // OK, if I need to read a pixel, do it now if (read_next_pixel) { // load however much data we did have if (tga_indexed) { // read in index, then perform the lookup int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); if (pal_idx >= tga_palette_len) { // invalid index pal_idx = 0; } pal_idx *= tga_comp; for (j = 0; j < tga_comp; ++j) { raw_data[j] = tga_palette[pal_idx + j]; } } else if (tga_rgb16) { STBI_ASSERT(tga_comp == STBI_rgb); stbi__tga_read_rgb16(s, raw_data); } else { // read in the data raw for (j = 0; j < tga_comp; ++j) { raw_data[j] = stbi__get8(s); } } // clear the reading flag for the next pixel read_next_pixel = 0; } // end of reading a pixel // copy data for (j = 0; j < tga_comp; ++j) tga_data[i*tga_comp + j] = raw_data[j]; // in case we're in RLE mode, keep counting down --RLE_count; } // do I need to invert the image? if (tga_inverted) { for (j = 0; j * 2 < tga_height; ++j) { int index1 = j * tga_width * tga_comp; int index2 = (tga_height - 1 - j) * tga_width * tga_comp; for (i = tga_width * tga_comp; i > 0; --i) { unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; ++index2; } } } // clear my palette, if I had one if (tga_palette != NULL) { STBI_FREE(tga_palette); } } // swap RGB - if the source data was RGB16, it already is in the right order if (tga_comp >= 3 && !tga_rgb16) { unsigned char* tga_pixel = tga_data; for (i = 0; i < tga_width * tga_height; ++i) { unsigned char temp = tga_pixel[0]; tga_pixel[0] = tga_pixel[2]; tga_pixel[2] = temp; tga_pixel += tga_comp; } } // convert to target component count if (req_comp && req_comp != tga_comp) tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; // OK, done return tga_data; } #endif // ************************************************************************************************* // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s) { int r = (stbi__get32be(s) == 0x38425053); stbi__rewind(s); return r; } static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) { int count, nleft, len; count = 0; while ((nleft = pixelCount - count) > 0) { len = stbi__get8(s); if (len == 128) { // No-op. } else if (len < 128) { // Copy next len+1 bytes literally. len++; if (len > nleft) return 0; // corrupt data count += len; while (len) { *p = stbi__get8(s); p += 4; len--; } } else if (len > 128) { stbi_uc val; // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) len = 257 - len; if (len > nleft) return 0; // corrupt data val = stbi__get8(s); count += len; while (len) { *p = val; p += 4; len--; } } } return 1; } static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { int pixelCount; int channelCount, compression; int channel, i; int bitdepth; int w, h; stbi_uc *out; STBI_NOTUSED(ri); // Check identifier if (stbi__get32be(s) != 0x38425053) // "8BPS" return stbi__errpuc("not PSD", "Corrupt PSD image"); // Check file type version. if (stbi__get16be(s) != 1) return stbi__errpuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. stbi__skip(s, 6); // Read the number of channels (R, G, B, A, etc). channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); // Read the rows and columns of the image. h = stbi__get32be(s); w = stbi__get32be(s); // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color if (stbi__get16be(s) != 3) return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) stbi__skip(s, stbi__get32be(s)); // Skip the image resources. (resolution, pen tool paths, etc) stbi__skip(s, stbi__get32be(s)); // Skip the reserved data. stbi__skip(s, stbi__get32be(s)); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed compression = stbi__get16be(s); if (compression > 1) return stbi__errpuc("bad compression", "PSD has an unknown compression format"); // Check size if (!stbi__mad3sizes_valid(4, w, h, 0)) return stbi__errpuc("too large", "Corrupt PSD"); // Create the destination image. if (!compression && bitdepth == 16 && bpc == 16) { out = (stbi_uc *)stbi__malloc_mad3(8, w, h, 0); ri->bits_per_channel = 16; } else out = (stbi_uc *)stbi__malloc(4 * w*h); if (!out) return stbi__errpuc("outofmem", "Out of memory"); pixelCount = w*h; // Initialize the data to zero. //memset( out, 0, pixelCount * 4 ); // Finally, the image data. if (compression) { // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, // which we're going to just skip. stbi__skip(s, h * channelCount * 2); // Read the RLE data by channel. for (channel = 0; channel < 4; channel++) { stbi_uc *p; p = out + channel; if (channel >= channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++, p += 4) *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. if (!stbi__psd_decode_rle(s, p, pixelCount)) { STBI_FREE(out); return stbi__errpuc("corrupt", "bad RLE data"); } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { if (channel >= channelCount) { // Fill this channel with default data. if (bitdepth == 16 && bpc == 16) { stbi__uint16 *q = ((stbi__uint16 *)out) + channel; stbi__uint16 val = channel == 3 ? 65535 : 0; for (i = 0; i < pixelCount; i++, q += 4) *q = val; } else { stbi_uc *p = out + channel; stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) *p = val; } } else { if (ri->bits_per_channel == 16) { // output bpc stbi__uint16 *q = ((stbi__uint16 *)out) + channel; for (i = 0; i < pixelCount; i++, q += 4) *q = (stbi__uint16)stbi__get16be(s); } else { stbi_uc *p = out + channel; if (bitdepth == 16) { // input bpc for (i = 0; i < pixelCount; i++, p += 4) *p = (stbi_uc)(stbi__get16be(s) >> 8); } else { for (i = 0; i < pixelCount; i++, p += 4) *p = stbi__get8(s); } } } } } // remove weird white matte from PSD if (channelCount >= 4) { if (ri->bits_per_channel == 16) { for (i = 0; i < w*h; ++i) { stbi__uint16 *pixel = (stbi__uint16 *)out + 4 * i; if (pixel[3] != 0 && pixel[3] != 65535) { float a = pixel[3] / 65535.0f; float ra = 1.0f / a; float inv_a = 65535.0f * (1 - ra); pixel[0] = (stbi__uint16)(pixel[0] * ra + inv_a); pixel[1] = (stbi__uint16)(pixel[1] * ra + inv_a); pixel[2] = (stbi__uint16)(pixel[2] * ra + inv_a); } } } else { for (i = 0; i < w*h; ++i) { unsigned char *pixel = out + 4 * i; if (pixel[3] != 0 && pixel[3] != 255) { float a = pixel[3] / 255.0f; float ra = 1.0f / a; float inv_a = 255.0f * (1 - ra); pixel[0] = (unsigned char)(pixel[0] * ra + inv_a); pixel[1] = (unsigned char)(pixel[1] * ra + inv_a); pixel[2] = (unsigned char)(pixel[2] * ra + inv_a); } } } } // convert to desired output format if (req_comp && req_comp != 4) { if (ri->bits_per_channel == 16) out = (stbi_uc *)stbi__convert_format16((stbi__uint16 *)out, 4, req_comp, w, h); else out = stbi__convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // stbi__convert_format frees input on failure } if (comp) *comp = 4; *y = h; *x = w; return out; } #endif // ************************************************************************************************* // Softimage PIC loader // by Tom Seddon // // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ #ifndef STBI_NO_PIC static int stbi__pic_is4(stbi__context *s, const char *str) { int i; for (i = 0; i<4; ++i) if (stbi__get8(s) != (stbi_uc)str[i]) return 0; return 1; } static int stbi__pic_test_core(stbi__context *s) { int i; if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) return 0; for (i = 0; i<84; ++i) stbi__get8(s); if (!stbi__pic_is4(s, "PICT")) return 0; return 1; } typedef struct { stbi_uc size, type, channel; } stbi__pic_packet; static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) { int mask = 0x80, i; for (i = 0; i<4; ++i, mask >>= 1) { if (channel & mask) { if (stbi__at_eof(s)) return stbi__errpuc("bad file", "PIC file too short"); dest[i] = stbi__get8(s); } } return dest; } static void stbi__copyval(int channel, stbi_uc *dest, const stbi_uc *src) { int mask = 0x80, i; for (i = 0; i<4; ++i, mask >>= 1) if (channel&mask) dest[i] = src[i]; } static stbi_uc *stbi__pic_load_core(stbi__context *s, int width, int height, int *comp, stbi_uc *result) { int act_comp = 0, num_packets = 0, y, chained; stbi__pic_packet packets[10]; // this will (should...) cater for even some bizarre stuff like having data // for the same channel in multiple packets. do { stbi__pic_packet *packet; if (num_packets == sizeof(packets) / sizeof(packets[0])) return stbi__errpuc("bad format", "too many packets"); packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (reading packets)"); if (packet->size != 8) return stbi__errpuc("bad format", "packet isn't 8bpp"); } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? for (y = 0; y<height; ++y) { int packet_idx; for (packet_idx = 0; packet_idx < num_packets; ++packet_idx) { stbi__pic_packet *packet = &packets[packet_idx]; stbi_uc *dest = result + y*width * 4; switch (packet->type) { default: return stbi__errpuc("bad format", "packet has bad compression type"); case 0: {//uncompressed int x; for (x = 0; x<width; ++x, dest += 4) if (!stbi__readval(s, packet->channel, dest)) return 0; break; } case 1://Pure RLE { int left = width, i; while (left>0) { stbi_uc count, value[4]; count = stbi__get8(s); if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pure read count)"); if (count > left) count = (stbi_uc)left; if (!stbi__readval(s, packet->channel, value)) return 0; for (i = 0; i<count; ++i, dest += 4) stbi__copyval(packet->channel, dest, value); left -= count; } } break; case 2: {//Mixed RLE int left = width; while (left>0) { int count = stbi__get8(s), i; if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (mixed read count)"); if (count >= 128) { // Repeated stbi_uc value[4]; if (count == 128) count = stbi__get16be(s); else count -= 127; if (count > left) return stbi__errpuc("bad file", "scanline overrun"); if (!stbi__readval(s, packet->channel, value)) return 0; for (i = 0; i<count; ++i, dest += 4) stbi__copyval(packet->channel, dest, value); } else { // Raw ++count; if (count>left) return stbi__errpuc("bad file", "scanline overrun"); for (i = 0; i<count; ++i, dest += 4) if (!stbi__readval(s, packet->channel, dest)) return 0; } left -= count; } break; } } } } return result; } static void *stbi__pic_load(stbi__context *s, int *px, int *py, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *result; int i, x, y; STBI_NOTUSED(ri); for (i = 0; i<92; ++i) stbi__get8(s); x = stbi__get16be(s); y = stbi__get16be(s); if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pic header)"); if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); stbi__get32be(s); //skip `ratio' stbi__get16be(s); //skip `fields' stbi__get16be(s); //skip `pad' // intermediate buffer is RGBA result = (stbi_uc *)stbi__malloc_mad3(x, y, 4, 0); memset(result, 0xff, x*y * 4); if (!stbi__pic_load_core(s, x, y, comp, result)) { STBI_FREE(result); result = 0; } *px = x; *py = y; if (req_comp == 0) req_comp = *comp; result = stbi__convert_format(result, 4, req_comp, x, y); return result; } static int stbi__pic_test(stbi__context *s) { int r = stbi__pic_test_core(s); stbi__rewind(s); return r; } #endif // ************************************************************************************************* // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb #ifndef STBI_NO_GIF typedef struct { stbi__int16 prefix; stbi_uc first; stbi_uc suffix; } stbi__gif_lzw; typedef struct { int w, h; stbi_uc *out, *old_out; // output buffer (always 4 components) int flags, bgindex, ratio, transparent, eflags, delay; stbi_uc pal[256][4]; stbi_uc lpal[256][4]; stbi__gif_lzw codes[4096]; stbi_uc *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; } stbi__gif; static int stbi__gif_test_raw(stbi__context *s) { int sz; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; sz = stbi__get8(s); if (sz != '9' && sz != '7') return 0; if (stbi__get8(s) != 'a') return 0; return 1; } static int stbi__gif_test(stbi__context *s) { int r = stbi__gif_test_raw(s); stbi__rewind(s); return r; } static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) { int i; for (i = 0; i < num_entries; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); pal[i][3] = transp == i ? 0 : 255; } } static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) { stbi_uc version; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return stbi__err("not GIF", "Corrupt GIF"); version = stbi__get8(s); if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); stbi__g_failure_reason = ""; g->w = stbi__get16le(s); g->h = stbi__get16le(s); g->flags = stbi__get8(s); g->bgindex = stbi__get8(s); g->ratio = stbi__get8(s); g->transparent = -1; if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; if (g->flags & 0x80) stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1); return 1; } static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) { stbi__gif* g = (stbi__gif*)stbi__malloc(sizeof(stbi__gif)); if (!stbi__gif_header(s, g, comp, 1)) { STBI_FREE(g); stbi__rewind(s); return 0; } if (x) *x = g->w; if (y) *y = g->h; STBI_FREE(g); return 1; } static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) { stbi_uc *p, *c; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix); if (g->cur_y >= g->max_y) return; p = &g->out[g->cur_x + g->cur_y]; c = &g->color_table[g->codes[code].suffix * 4]; if (c[3] >= 128) { p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = c[3]; } g->cur_x += 4; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) { stbi_uc lzw_cs; stbi__int32 len, init_code; stbi__uint32 first; stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; stbi__gif_lzw *p; lzw_cs = stbi__get8(s); if (lzw_cs > 12) return NULL; clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (init_code = 0; init_code < clear; init_code++) { g->codes[init_code].prefix = -1; g->codes[init_code].first = (stbi_uc)init_code; g->codes[init_code].suffix = (stbi_uc)init_code; } // support no starting clear code avail = clear + 2; oldcode = -1; len = 0; for (;;) { if (valid_bits < codesize) { if (len == 0) { len = stbi__get8(s); // start new block if (len == 0) return g->out; } --len; bits |= (stbi__int32)stbi__get8(s) << valid_bits; valid_bits += 8; } else { stbi__int32 code = bits & codemask; bits >>= codesize; valid_bits -= codesize; // @OPTIMIZE: is there some way we can accelerate the non-clear path? if (code == clear) { // clear code codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { // end of stream code stbi__skip(s, len); while ((len = stbi__get8(s)) > 0) stbi__skip(s, len); return g->out; } else if (code <= avail) { if (first) return stbi__errpuc("no clear code", "Corrupt GIF"); if (oldcode >= 0) { p = &g->codes[avail++]; if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF"); p->prefix = (stbi__int16)oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } else if (code == avail) return stbi__errpuc("illegal code in raster", "Corrupt GIF"); stbi__out_gif_code(g, (stbi__uint16)code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { return stbi__errpuc("illegal code in raster", "Corrupt GIF"); } } } } static void stbi__fill_gif_background(stbi__gif *g, int x0, int y0, int x1, int y1) { int x, y; stbi_uc *c = g->pal[g->bgindex]; for (y = y0; y < y1; y += 4 * g->w) { for (x = x0; x < x1; x += 4) { stbi_uc *p = &g->out[y + x]; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = 0; } } } // this function is designed to support animated gifs, although stb_image doesn't support it static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp) { int i; stbi_uc *prev_out = 0; if (g->out == 0 && !stbi__gif_header(s, g, comp, 0)) return 0; // stbi__g_failure_reason set by stbi__gif_header if (!stbi__mad3sizes_valid(g->w, g->h, 4, 0)) return stbi__errpuc("too large", "GIF too large"); prev_out = g->out; g->out = (stbi_uc *)stbi__malloc_mad3(4, g->w, g->h, 0); if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); switch ((g->eflags & 0x1C) >> 2) { case 0: // unspecified (also always used on 1st frame) stbi__fill_gif_background(g, 0, 0, 4 * g->w, 4 * g->w * g->h); break; case 1: // do not dispose if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); g->old_out = prev_out; break; case 2: // dispose to background if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); stbi__fill_gif_background(g, g->start_x, g->start_y, g->max_x, g->max_y); break; case 3: // dispose to previous if (g->old_out) { for (i = g->start_y; i < g->max_y; i += 4 * g->w) memcpy(&g->out[i + g->start_x], &g->old_out[i + g->start_x], g->max_x - g->start_x); } break; } for (;;) { switch (stbi__get8(s)) { case 0x2C: /* Image Descriptor */ { int prev_trans = -1; stbi__int32 x, y, w, h; stbi_uc *o; x = stbi__get16le(s); y = stbi__get16le(s); w = stbi__get16le(s); h = stbi__get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); g->line_size = g->w * 4; g->start_x = x * 4; g->start_y = y * g->line_size; g->max_x = g->start_x + w * 4; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; g->lflags = stbi__get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; // first interlaced spacing g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *)g->lpal; } else if (g->flags & 0x80) { if (g->transparent >= 0 && (g->eflags & 0x01)) { prev_trans = g->pal[g->transparent][3]; g->pal[g->transparent][3] = 0; } g->color_table = (stbi_uc *)g->pal; } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); if (o == NULL) return NULL; if (prev_trans != -1) g->pal[g->transparent][3] = (stbi_uc)prev_trans; return o; } case 0x21: // Comment Extension. { int len; if (stbi__get8(s) == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); g->delay = stbi__get16le(s); g->transparent = stbi__get8(s); } else { stbi__skip(s, len); break; } } while ((len = stbi__get8(s)) != 0) stbi__skip(s, len); break; } case 0x3B: // gif stream termination code return (stbi_uc *)s; // using '1' causes warning on some compilers default: return stbi__errpuc("unknown code", "Corrupt GIF"); } } STBI_NOTUSED(req_comp); } static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *u = 0; stbi__gif* g = (stbi__gif*)stbi__malloc(sizeof(stbi__gif)); memset(g, 0, sizeof(*g)); STBI_NOTUSED(ri); u = stbi__gif_load_next(s, g, comp, req_comp); if (u == (stbi_uc *)s) u = 0; // end of animated gif marker if (u) { *x = g->w; *y = g->h; if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g->w, g->h); } else if (g->out) STBI_FREE(g->out); STBI_FREE(g); return u; } static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) { return stbi__gif_info_raw(s, x, y, comp); } #endif // ************************************************************************************************* // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR static int stbi__hdr_test_core(stbi__context *s, const char *signature) { int i; for (i = 0; signature[i]; ++i) if (stbi__get8(s) != signature[i]) return 0; stbi__rewind(s); return 1; } static int stbi__hdr_test(stbi__context* s) { int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); stbi__rewind(s); if (!r) { r = stbi__hdr_test_core(s, "#?RGBE\n"); stbi__rewind(s); } return r; } #define STBI__HDR_BUFLEN 1024 static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) { int len = 0; char c = '\0'; c = (char)stbi__get8(z); while (!stbi__at_eof(z) && c != '\n') { buffer[len++] = c; if (len == STBI__HDR_BUFLEN - 1) { // flush to end of line while (!stbi__at_eof(z) && stbi__get8(z) != '\n') ; break; } c = (char)stbi__get8(z); } buffer[len] = 0; return buffer; } static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) { if (input[3] != 0) { float f1; // Exponent f1 = (float)ldexp(1.0f, input[3] - (int)(128 + 8)); if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; output[2] = input[2] * f1; } if (req_comp == 2) output[1] = 1; if (req_comp == 4) output[3] = 1; } else { switch (req_comp) { case 4: output[3] = 1; /* fallthrough */ case 3: output[0] = output[1] = output[2] = 0; break; case 2: output[1] = 1; /* fallthrough */ case 1: output[0] = 0; break; } } } static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; float *hdr_data; int len; unsigned char count, value; int i, j, k, c1, c2, z; const char *headerToken; STBI_NOTUSED(ri); // Check identifier headerToken = stbi__hdr_gettoken(s, buffer); if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header for (;;) { token = stbi__hdr_gettoken(s, buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = stbi__hdr_gettoken(s, buffer); if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; height = (int)strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; width = (int)strtol(token, NULL, 10); *x = width; *y = height; if (comp) *comp = 3; if (req_comp == 0) req_comp = 3; if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) return stbi__errpf("too large", "HDR image is too large"); // Read data hdr_data = (float *)stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); if (!hdr_data) return stbi__errpf("outofmem", "Out of memory"); // Load image data // image data is stored as some number of sca if (width < 8 || width >= 32768) { // Read flat data for (j = 0; j < height; ++j) { for (i = 0; i < width; ++i) { stbi_uc rgbe[4]; main_decode_loop: stbi__getn(s, rgbe, 4); stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); } } } else { // Read RLE-encoded data scanline = NULL; for (j = 0; j < height; ++j) { c1 = stbi__get8(s); c2 = stbi__get8(s); len = stbi__get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) stbi_uc rgbe[4]; rgbe[0] = (stbi_uc)c1; rgbe[1] = (stbi_uc)c2; rgbe[2] = (stbi_uc)len; rgbe[3] = (stbi_uc)stbi__get8(s); stbi__hdr_convert(hdr_data, rgbe, req_comp); i = 1; j = 0; STBI_FREE(scanline); goto main_decode_loop; // yes, this makes no sense } len <<= 8; len |= stbi__get8(s); if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) { scanline = (stbi_uc *)stbi__malloc_mad2(width, 4, 0); if (!scanline) { STBI_FREE(hdr_data); return stbi__errpf("outofmem", "Out of memory"); } } for (k = 0; k < 4; ++k) { int nleft; i = 0; while ((nleft = width - i) > 0) { count = stbi__get8(s); if (count > 128) { // Run value = stbi__get8(s); count -= 128; if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } } } for (i = 0; i < width; ++i) stbi__hdr_convert(hdr_data + (j*width + i)*req_comp, scanline + i * 4, req_comp); } if (scanline) STBI_FREE(scanline); } return hdr_data; } static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; if (stbi__hdr_test(s) == 0) { stbi__rewind(s); return 0; } for (;;) { token = stbi__hdr_gettoken(s, buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) { stbi__rewind(s); return 0; } token = stbi__hdr_gettoken(s, buffer); if (strncmp(token, "-Y ", 3)) { stbi__rewind(s); return 0; } token += 3; *y = (int)strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) { stbi__rewind(s); return 0; } token += 3; *x = (int)strtol(token, NULL, 10); *comp = 3; return 1; } #endif // STBI_NO_HDR #ifndef STBI_NO_BMP static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) { void *p; stbi__bmp_data info; info.all_a = 255; p = stbi__bmp_parse_header(s, &info); stbi__rewind(s); if (p == NULL) return 0; *x = s->img_x; *y = s->img_y; *comp = info.ma ? 4 : 3; return 1; } #endif #ifndef STBI_NO_PSD static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) { int channelCount; if (stbi__get32be(s) != 0x38425053) { stbi__rewind(s); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind(s); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind(s); return 0; } *y = stbi__get32be(s); *x = stbi__get32be(s); if (stbi__get16be(s) != 8) { stbi__rewind(s); return 0; } if (stbi__get16be(s) != 3) { stbi__rewind(s); return 0; } *comp = 4; return 1; } #endif #ifndef STBI_NO_PIC static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) { int act_comp = 0, num_packets = 0, chained; stbi__pic_packet packets[10]; if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) { stbi__rewind(s); return 0; } stbi__skip(s, 88); *x = stbi__get16be(s); *y = stbi__get16be(s); if (stbi__at_eof(s)) { stbi__rewind(s); return 0; } if ((*x) != 0 && (1 << 28) / (*x) < (*y)) { stbi__rewind(s); return 0; } stbi__skip(s, 8); do { stbi__pic_packet *packet; if (num_packets == sizeof(packets) / sizeof(packets[0])) return 0; packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) { stbi__rewind(s); return 0; } if (packet->size != 8) { stbi__rewind(s); return 0; } } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); return 1; } #endif // ************************************************************************************************* // Portable Gray Map and Portable Pixel Map loader // by Ken Miller // // PGM: http://netpbm.sourceforge.net/doc/pgm.html // PPM: http://netpbm.sourceforge.net/doc/ppm.html // // Known limitations: // Does not support comments in the header section // Does not support ASCII image data (formats P2 and P3) // Does not support 16-bit-per-channel #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s) { char p, t; p = (char)stbi__get8(s); t = (char)stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind(s); return 0; } return 1; } static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; STBI_NOTUSED(ri); if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) return 0; *x = s->img_x; *y = s->img_y; *comp = s->img_n; if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) return stbi__errpuc("too large", "PNM too large"); out = (stbi_uc *)stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); stbi__getn(s, out, s->img_n * s->img_x * s->img_y); if (req_comp && req_comp != s->img_n) { out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; } static int stbi__pnm_isspace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; } static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) { for (;;) { while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char)stbi__get8(s); if (stbi__at_eof(s) || *c != '#') break; while (!stbi__at_eof(s) && *c != '\n' && *c != '\r') *c = (char)stbi__get8(s); } } static int stbi__pnm_isdigit(char c) { return c >= '0' && c <= '9'; } static int stbi__pnm_getinteger(stbi__context *s, char *c) { int value = 0; while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { value = value * 10 + (*c - '0'); *c = (char)stbi__get8(s); } return value; } static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) { int maxv; char c, p, t; stbi__rewind(s); // Get identifier p = (char)stbi__get8(s); t = (char)stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind(s); return 0; } *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm c = (char)stbi__get8(s); stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value if (maxv > 255) return stbi__err("max value > 255", "PPM image not 8-bit"); else return 1; } #endif static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) { #ifndef STBI_NO_JPEG if (stbi__jpeg_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNG if (stbi__png_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_GIF if (stbi__gif_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_BMP if (stbi__bmp_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PIC if (stbi__pic_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNM if (stbi__pnm_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_HDR if (stbi__hdr_info(s, x, y, comp)) return 1; #endif // test tga last because it's a crappy test! #ifndef STBI_NO_TGA if (stbi__tga_info(s, x, y, comp)) return 1; #endif return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_info_from_file(f, x, y, comp); fclose(f); return result; } STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__info_main(&s, x, y, comp); fseek(f, pos, SEEK_SET); return r; } #endif // !STBI_NO_STDIO STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__info_main(&s, x, y, comp); } STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *)c, user); return stbi__info_main(&s, x, y, comp); } #endif // STB_IMAGE_IMPLEMENTATION /* revision history: 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) allocate large structures on the stack remove white matting for transparent PSD fix reported channel count for PNG & BMP re-enable SSE2 in non-gcc 64-bit support RGB-formatted JPEG read 16-bit PNGs (only as 8-bit) 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED 2.09 (2016-01-16) allow comments in PNM files 16-bit-per-pixel TGA (not bit-per-component) info() for TGA could break due to .hdr handling info() for BMP to shares code instead of sloppy parse can use STBI_REALLOC_SIZED if allocator doesn't support realloc code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit 2.03 (2015-04-12) extra corruption checking (mmozeiko) stbi_set_flip_vertically_on_load (nguillemot) fix NEON support; fix mingw support 2.02 (2015-01-19) fix incorrect assert, fix warning 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) progressive JPEG (stb) PGM/PPM support (Ken Miller) STBI_MALLOC,STBI_REALLOC,STBI_FREE GIF bugfix -- seemingly never worked STBI_NO_*, STBI_ONLY_* 1.48 (2014-12-14) fix incorrectly-named assert() 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) optimize PNG (ryg) fix bug in interlaced PNG with user-specified channel count (stb) 1.46 (2014-08-26) fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG 1.45 (2014-08-16) fix MSVC-ARM internal compiler error by wrapping malloc 1.44 (2014-08-07) various warning fixes from Ronny Chevalier 1.43 (2014-07-15) fix MSVC-only compiler problem in code changed in 1.42 1.42 (2014-07-09) don't define _CRT_SECURE_NO_WARNINGS (affects user code) fixes to stbi__cleanup_jpeg path added STBI_ASSERT to avoid requiring assert.h 1.41 (2014-06-25) fix search&replace from 1.36 that messed up comments/error messages 1.40 (2014-06-22) fix gcc struct-initialization warning 1.39 (2014-06-15) fix to TGA optimization when req_comp != number of components in TGA; fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) add support for BMP version 5 (more ignored fields) 1.38 (2014-06-06) suppress MSVC warnings on integer casts truncating values fix accidental rename of 'skip' field of I/O 1.37 (2014-06-04) remove duplicate typedef 1.36 (2014-06-03) convert to header file single-file library if de-iphone isn't set, load iphone images color-swapped instead of returning NULL 1.35 (2014-05-27) various warnings fix broken STBI_SIMD path fix bug where stbi_load_from_file no longer left file pointer in correct place fix broken non-easy path for 32-bit BMP (possibly never used) TGA optimization by Arseny Kapoulkine 1.34 (unknown) use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case 1.33 (2011-07-14) make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements 1.32 (2011-07-13) support for "info" function for all supported filetypes (SpartanJ) 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) fix inefficiency in decoding 32-bit BMP (David Woo) 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ) 1.27 (2010-08-01) cast-to-stbi_uc to fix warnings 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ 1.25 (2010-07-17) refix trans_data warning (Won Chun) 1.24 (2010-07-12) perf improvements reading from files on platforms with lock-heavy fgetc() minor perf improvements for jpeg deprecated type-specific functions so we'll get feedback if they're needed attempt to fix trans_data warning (Won Chun) 1.23 fixed bug in iPhone support 1.22 (2010-07-10) removed image *writing* support stbi_info support from Jetro Lauha GIF support from Jean-Marc Lienher iPhone PNG-extensions from James Brown warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) 1.21 fix use of 'stbi_uc' in header (reported by jon blow) 1.20 added support for Softimage PIC, by Tom Seddon 1.19 bug in interlaced PNG corruption check (found by ryg) 1.18 (2008-08-02) fix a threading bug (local mutable static) 1.17 support interlaced PNG 1.16 major bugfix - stbi__convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant 0.50 (2006-11-19) first released version */
Unknown
3D
hku-mars/ImMesh
src/shader/stb_image_aug.c
.c
113,757
3,683
/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c when you control the images you're loading QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline (no JPEG progressive, no oddball channel decimations) PNG non-interlaced BMP non-1bpp, non-RLE TGA (not sure what subset, if a subset) PSD (composited view only, no extra channels) HDR (radiance rgbE format) writes BMP,TGA (define STBI_NO_WRITE to remove code) decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code) supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD) TODO: stbi_info_* history: 1.16 major bugfix - convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant */ #include "stb_image_aug.h" #ifndef STBI_NO_HDR #include <math.h> // ldexp #include <string.h> // strcmp #endif #ifndef STBI_NO_STDIO #include <stdio.h> #endif #include <stdlib.h> #include <memory.h> #include <assert.h> #include <stdarg.h> #ifndef _MSC_VER #ifdef __cplusplus #define __forceinline inline #else #define __forceinline #endif #endif // implementation: typedef unsigned char uint8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; typedef unsigned int uint; // should produce compiler error if size is wrong typedef unsigned char validate_uint32[sizeof(uint32)==4]; #if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE) #define STBI_NO_WRITE #endif #define STBI_NO_DDS #ifndef STBI_NO_DDS #include "stbi_DDS_aug.h" #endif // I (JLD) want full messages for SOIL #define STBI_FAILURE_USERMSG 1 ////////////////////////////////////////////////////////////////////////////// // // Generic API that works on all image types // // this is not threadsafe static char *failure_reason; char *stbi_failure_reason(void) { return failure_reason; } static int e(char *str) { failure_reason = str; return 0; } #ifdef STBI_NO_FAILURE_STRINGS #define e(x,y) 0 #elif defined(STBI_FAILURE_USERMSG) #define e(x,y) e(y) #else #define e(x,y) e(x) #endif #define epf(x,y) ((float *) (e(x,y)?NULL:NULL)) #define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL)) void stbi_image_free(void *retval_from_stbi_load) { free(retval_from_stbi_load); } #define MAX_LOADERS 32 stbi_loader *loaders[MAX_LOADERS]; static int max_loaders = 0; int stbi_register_loader(stbi_loader *loader) { int i; for (i=0; i < MAX_LOADERS; ++i) { // already present? if (loaders[i] == loader) return 1; // end of the list? if (loaders[i] == NULL) { loaders[i] = loader; max_loaders = i+1; return 1; } } // no room for it return 0; } #ifndef STBI_NO_HDR static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp); static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp); #endif #ifndef STBI_NO_STDIO unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = fopen(filename, "rb"); unsigned char *result; if (!f) return epuc("can't fopen", "Unable to open file"); result = stbi_load_from_file(f,x,y,comp,req_comp); fclose(f); return result; } unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { int i; if (stbi_jpeg_test_file(f)) return stbi_jpeg_load_from_file(f,x,y,comp,req_comp); if (stbi_png_test_file(f)) return stbi_png_load_from_file(f,x,y,comp,req_comp); if (stbi_bmp_test_file(f)) return stbi_bmp_load_from_file(f,x,y,comp,req_comp); if (stbi_psd_test_file(f)) return stbi_psd_load_from_file(f,x,y,comp,req_comp); #ifndef STBI_NO_DDS if (stbi_dds_test_file(f)) return stbi_dds_load_from_file(f,x,y,comp,req_comp); #endif #ifndef STBI_NO_HDR if (stbi_hdr_test_file(f)) { float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp); return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif for (i=0; i < max_loaders; ++i) if (loaders[i]->test_file(f)) return loaders[i]->load_from_file(f,x,y,comp,req_comp); // test tga last because it's a crappy test! if (stbi_tga_test_file(f)) return stbi_tga_load_from_file(f,x,y,comp,req_comp); return epuc("unknown image type", "Image not of any known type, or corrupt"); } #endif unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { int i; if (stbi_jpeg_test_memory(buffer,len)) return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp); if (stbi_png_test_memory(buffer,len)) return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp); if (stbi_bmp_test_memory(buffer,len)) return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp); if (stbi_psd_test_memory(buffer,len)) return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp); #ifndef STBI_NO_DDS if (stbi_dds_test_memory(buffer,len)) return stbi_dds_load_from_memory(buffer,len,x,y,comp,req_comp); #endif #ifndef STBI_NO_HDR if (stbi_hdr_test_memory(buffer, len)) { float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp); return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif for (i=0; i < max_loaders; ++i) if (loaders[i]->test_memory(buffer,len)) return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp); // test tga last because it's a crappy test! if (stbi_tga_test_memory(buffer,len)) return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp); return epuc("unknown image type", "Image not of any known type, or corrupt"); } #ifndef STBI_NO_HDR #ifndef STBI_NO_STDIO float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = fopen(filename, "rb"); float *result; if (!f) return epf("can't fopen", "Unable to open file"); result = stbi_loadf_from_file(f,x,y,comp,req_comp); fclose(f); return result; } float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi_hdr_test_file(f)) return stbi_hdr_load_from_file(f,x,y,comp,req_comp); #endif data = stbi_load_from_file(f, x, y, comp, req_comp); if (data) return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return epf("unknown image type", "Image not of any known type, or corrupt"); } #endif float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi_uc *data; #ifndef STBI_NO_HDR if (stbi_hdr_test_memory(buffer, len)) return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp); #endif data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp); if (data) return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return epf("unknown image type", "Image not of any known type, or corrupt"); } #endif // these is-hdr-or-not is defined independent of whether STBI_NO_HDR is // defined, for API simplicity; if STBI_NO_HDR is defined, it always // reports false! int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) { #ifndef STBI_NO_HDR return stbi_hdr_test_memory(buffer, len); #else return 0; #endif } #ifndef STBI_NO_STDIO extern int stbi_is_hdr (char const *filename) { FILE *f = fopen(filename, "rb"); int result=0; if (f) { result = stbi_is_hdr_from_file(f); fclose(f); } return result; } extern int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR return stbi_hdr_test_file(f); #else return 0; #endif } #endif // @TODO: get image dimensions & components without fully decoding #ifndef STBI_NO_STDIO extern int stbi_info (char const *filename, int *x, int *y, int *comp); extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); #endif extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); #ifndef STBI_NO_HDR static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f; static float l2h_gamma=2.2f, l2h_scale=1.0f; void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; } void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; } void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; } void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; } #endif ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // enum { SCAN_load=0, SCAN_type, SCAN_header, }; typedef struct { uint32 img_x, img_y; int img_n, img_out_n; #ifndef STBI_NO_STDIO FILE *img_file; #endif uint8 *img_buffer, *img_buffer_end; } stbi; #ifndef STBI_NO_STDIO static void start_file(stbi *s, FILE *f) { s->img_file = f; } #endif static void start_mem(stbi *s, uint8 const *buffer, int len) { #ifndef STBI_NO_STDIO s->img_file = NULL; #endif s->img_buffer = (uint8 *) buffer; s->img_buffer_end = (uint8 *) buffer+len; } __forceinline static int get8(stbi *s) { #ifndef STBI_NO_STDIO if (s->img_file) { int c = fgetc(s->img_file); return c == EOF ? 0 : c; } #endif if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; return 0; } __forceinline static int at_eof(stbi *s) { #ifndef STBI_NO_STDIO if (s->img_file) return feof(s->img_file); #endif return s->img_buffer >= s->img_buffer_end; } __forceinline static uint8 get8u(stbi *s) { return (uint8) get8(s); } static void skip(stbi *s, int n) { #ifndef STBI_NO_STDIO if (s->img_file) fseek(s->img_file, n, SEEK_CUR); else #endif s->img_buffer += n; } static int get16(stbi *s) { int z = get8(s); return (z << 8) + get8(s); } static uint32 get32(stbi *s) { uint32 z = get16(s); return (z << 16) + get16(s); } static int get16le(stbi *s) { int z = get8(s); return z + (get8(s) << 8); } static uint32 get32le(stbi *s) { uint32 z = get16le(s); return z + (get16le(s) << 16); } static void getn(stbi *s, stbi_uc *buffer, int n) { #ifndef STBI_NO_STDIO if (s->img_file) { fread(buffer, 1, n, s->img_file); return; } #endif memcpy(buffer, s->img_buffer, n); s->img_buffer += n; } ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp // individual types do this automatically as much as possible (e.g. jpeg // does all cases internally since it needs to colorspace convert anyway, // and it never has alpha, so very few cases ). png can automatically // interleave an alpha=255 channel, but falls back to this for other cases // // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing static uint8 compute_y(int r, int g, int b) { return (uint8) (((r*77) + (g*150) + (29*b)) >> 8); } static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y) { int i,j; unsigned char *good; if (req_comp == img_n) return data; assert(req_comp >= 1 && req_comp <= 4); good = (unsigned char *) malloc(req_comp * x * y); if (good == NULL) { free(data); return epuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; #define COMBO(a,b) ((a)*8+(b)) #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch(COMBO(img_n, req_comp)) { CASE(1,2) dest[0]=src[0], dest[1]=255; break; CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break; CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break; CASE(2,1) dest[0]=src[0]; break; CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break; CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break; CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break; CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break; CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break; CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break; CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break; CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break; default: assert(0); } #undef CASE } free(data); return good; } #ifndef STBI_NO_HDR static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; float *output = (float *) malloc(x * y * comp * sizeof(float)); if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale; } if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; } free(data); return output; } #define float2int(x) ((int) (x)) static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; stbi_uc *output = (stbi_uc *) malloc(x * y * comp); if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = float2int(z); } if (k < comp) { float z = data[i*comp+k] * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = float2int(z); } } free(data); return output; } #endif ////////////////////////////////////////////////////////////////////////////// // // "baseline" JPEG/JFIF decoder (not actually fully baseline implementation) // // simple implementation // - channel subsampling of at most 2 in each dimension // - doesn't support delayed output of y-dimension // - simple interface (only one output format: 8-bit interleaved RGB) // - doesn't try to recover corrupt jpegs // - doesn't allow partial loading, loading multiple at once // - still fast on x86 (copying globals into locals doesn't help x86) // - allocates lots of intermediate memory (full size of all components) // - non-interleaved case requires this anyway // - allows good upsampling (see next) // high-quality // - upsampled channels are bilinearly interpolated, even across blocks // - quality integer IDCT derived from IJG's 'slow' // performance // - fast huffman; reasonable integer IDCT // - uses a lot of intermediate memory, could cache poorly // - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4 // stb_jpeg: 1.34 seconds (MSVC6, default release build) // stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro) // IJL11.dll: 1.08 seconds (compiled by intel) // IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG) // IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro) // huffman decoding acceleration #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache typedef struct { uint8 fast[1 << FAST_BITS]; // weirdly, repacking this into AoS is a 10% speed loss, instead of a win uint16 code[256]; uint8 values[256]; uint8 size[257]; unsigned int maxcode[18]; int delta[17]; // old 'firstsymbol' - old 'firstcode' } huffman; typedef struct { #if STBI_SIMD unsigned short dequant2[4][64]; #endif stbi s; huffman huff_dc[4]; huffman huff_ac[4]; uint8 dequant[4][64]; // sizes for components, interleaved MCUs int img_h_max, img_v_max; int img_mcu_x, img_mcu_y; int img_mcu_w, img_mcu_h; // definition of jpeg image component struct { int id; int h,v; int tq; int hd,ha; int dc_pred; int x,y,w2,h2; uint8 *data; void *raw_data; uint8 *linebuf; } img_comp[4]; uint32 code_buffer; // jpeg entropy-coded buffer int code_bits; // number of valid bits unsigned char marker; // marker seen while filling entropy buffer int nomore; // flag if we saw a marker so must stop int scan_n, order[4]; int restart_interval, todo; } jpeg; static int build_huffman(huffman *h, int *count) { int i,j,k=0,code; // build size list for each symbol (from JPEG spec) for (i=0; i < 16; ++i) for (j=0; j < count[i]; ++j) h->size[k++] = (uint8) (i+1); h->size[k] = 0; // compute actual symbols (from jpeg spec) code = 0; k = 0; for(j=1; j <= 16; ++j) { // compute delta to add to code to compute symbol id h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (uint16) (code++); if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); code <<= 1; } h->maxcode[j] = 0xffffffff; // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i=0; i < k; ++i) { int s = h->size[i]; if (s <= FAST_BITS) { int c = h->code[i] << (FAST_BITS-s); int m = 1 << (FAST_BITS-s); for (j=0; j < m; ++j) { h->fast[c+j] = (uint8) i; } } } return 1; } static void grow_buffer_unsafe(jpeg *j) { do { int b = j->nomore ? 0 : get8(&j->s); if (b == 0xff) { int c = get8(&j->s); if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; return; } } j->code_buffer = (j->code_buffer << 8) | b; j->code_bits += 8; } while (j->code_bits <= 24); } // (1 << n) - 1 static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream __forceinline static int decode(jpeg *j, huffman *h) { unsigned int temp; int c,k; if (j->code_bits < 16) grow_buffer_unsafe(j); // look at the top FAST_BITS and determine what symbol ID it is, // if the code is <= FAST_BITS c = (j->code_buffer >> (j->code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1); k = h->fast[c]; if (k < 255) { if (h->size[k] > j->code_bits) return -1; j->code_bits -= h->size[k]; return h->values[k]; } // naive test is to shift the code_buffer down so k bits are // valid, then test against maxcode. To speed this up, we've // preshifted maxcode left so that it has (16-k) 0s at the // end; in other words, regardless of the number of bits, it // wants to be compared against something shifted to have 16; // that way we don't need to shift inside the loop. if (j->code_bits < 16) temp = (j->code_buffer << (16 - j->code_bits)) & 0xffff; else temp = (j->code_buffer >> (j->code_bits - 16)) & 0xffff; for (k=FAST_BITS+1 ; ; ++k) if (temp < h->maxcode[k]) break; if (k == 17) { // error! code not found j->code_bits -= 16; return -1; } if (k > j->code_bits) return -1; // convert the huffman code to the symbol id c = ((j->code_buffer >> (j->code_bits - k)) & bmask[k]) + h->delta[k]; assert((((j->code_buffer) >> (j->code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol j->code_bits -= k; return h->values[c]; } // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. __forceinline static int extend_receive(jpeg *j, int n) { unsigned int m = 1 << (n-1); unsigned int k; if (j->code_bits < n) grow_buffer_unsafe(j); k = (j->code_buffer >> (j->code_bits - n)) & bmask[n]; j->code_bits -= n; // the following test is probably a random branch that won't // predict well. I tried to table accelerate it but failed. // maybe it's compiling as a conditional move? if (k < m) return (-1 << n) + k + 1; else return k; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static uint8 dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 }; // decode one 64-entry block-- static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b) { int diff,dc,k; int t = decode(j, hdc); if (t < 0) return e("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) dc; // decode AC components, see JPEG spec k = 1; do { int r,s; int rs = decode(j, hac); if (rs < 0) return e("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (rs != 0xf0) break; // end block k += 16; } else { k += r; // decode into unzigzag'd location data[dezigzag[k++]] = (short) extend_receive(j,s); } } while (k < 64); return 1; } // take a -128..127 value and clamp it and convert to 0..255 __forceinline static uint8 clamp(int x) { x += 128; // trick to use a single test to catch both cases if ((unsigned int) x > 255) { if (x < 0) return 0; if (x > 255) return 255; } return (uint8) x; } #define f2f(x) (int) (((x) * 4096 + 0.5)) #define fsh(x) ((x) << 12) // derived from jidctint -- DCT_ISLOW #define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ p2 = s2; \ p3 = s6; \ p1 = (p2+p3) * f2f(0.5411961f); \ t2 = p1 + p3*f2f(-1.847759065f); \ t3 = p1 + p2*f2f( 0.765366865f); \ p2 = s0; \ p3 = s4; \ t0 = fsh(p2+p3); \ t1 = fsh(p2-p3); \ x0 = t0+t3; \ x3 = t0-t3; \ x1 = t1+t2; \ x2 = t1-t2; \ t0 = s7; \ t1 = s5; \ t2 = s3; \ t3 = s1; \ p3 = t0+t2; \ p4 = t1+t3; \ p1 = t0+t3; \ p2 = t1+t2; \ p5 = (p3+p4)*f2f( 1.175875602f); \ t0 = t0*f2f( 0.298631336f); \ t1 = t1*f2f( 2.053119869f); \ t2 = t2*f2f( 3.072711026f); \ t3 = t3*f2f( 1.501321110f); \ p1 = p5 + p1*f2f(-0.899976223f); \ p2 = p5 + p2*f2f(-2.562915447f); \ p3 = p3*f2f(-1.961570560f); \ p4 = p4*f2f(-0.390180644f); \ t3 += p1+p4; \ t2 += p2+p3; \ t1 += p2+p4; \ t0 += p1+p3; #if !STBI_SIMD // .344 seconds on 3*anemones.jpg static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize) { int i,val[64],*v=val; uint8 *o,*dq = dequantize; short *d = data; // columns for (i=0; i < 8; ++i,++d,++dq, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 && d[40]==0 && d[48]==0 && d[56]==0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0] * dq[0] << 2; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24], d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[ 0] = (x0+t3) >> 10; v[56] = (x0-t3) >> 10; v[ 8] = (x1+t2) >> 10; v[48] = (x1-t2) >> 10; v[16] = (x2+t1) >> 10; v[40] = (x2-t1) >> 10; v[24] = (x3+t0) >> 10; v[32] = (x3-t0) >> 10; } } for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { // no fast case since the first 1D IDCT spread components out IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536; o[0] = clamp((x0+t3) >> 17); o[7] = clamp((x0-t3) >> 17); o[1] = clamp((x1+t2) >> 17); o[6] = clamp((x1-t2) >> 17); o[2] = clamp((x2+t1) >> 17); o[5] = clamp((x2-t1) >> 17); o[3] = clamp((x3+t0) >> 17); o[4] = clamp((x3-t0) >> 17); } } #else static void idct_block(uint8 *out, int out_stride, short data[64], unsigned short *dequantize) { int i,val[64],*v=val; uint8 *o; unsigned short *dq = dequantize; short *d = data; // columns for (i=0; i < 8; ++i,++d,++dq, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 && d[40]==0 && d[48]==0 && d[56]==0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0] * dq[0] << 2; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24], d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[ 0] = (x0+t3) >> 10; v[56] = (x0-t3) >> 10; v[ 8] = (x1+t2) >> 10; v[48] = (x1-t2) >> 10; v[16] = (x2+t1) >> 10; v[40] = (x2-t1) >> 10; v[24] = (x3+t0) >> 10; v[32] = (x3-t0) >> 10; } } for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { // no fast case since the first 1D IDCT spread components out IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536; o[0] = clamp((x0+t3) >> 17); o[7] = clamp((x0-t3) >> 17); o[1] = clamp((x1+t2) >> 17); o[6] = clamp((x1-t2) >> 17); o[2] = clamp((x2+t1) >> 17); o[5] = clamp((x2-t1) >> 17); o[3] = clamp((x3+t0) >> 17); o[4] = clamp((x3-t0) >> 17); } } static stbi_idct_8x8 stbi_idct_installed = idct_block; extern void stbi_install_idct(stbi_idct_8x8 func) { stbi_idct_installed = func; } #endif #define MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value static uint8 get_marker(jpeg *j) { uint8 x; if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; } x = get8u(&j->s); if (x != 0xff) return MARKER_none; while (x == 0xff) x = get8u(&j->s); return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] #define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, reset the entropy decoder and // the dc prediction static void reset(jpeg *j) { j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; j->marker = MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, // since we don't even allow 1<<30 pixels } static int parse_entropy_coded_data(jpeg *z) { reset(z); if (z->scan_n == 1) { int i,j; #if STBI_SIMD __declspec(align(16)) #endif short data[64]; int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0; #if STBI_SIMD stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]); #else idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]); #endif // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!RESTART(z->marker)) return 1; reset(z); } } } } else { // interleaved! int i,j,k,x,y; short data[64]; for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x)*8; int y2 = (j*z->img_comp[n].v + y)*8; if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0; #if STBI_SIMD stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]); #else idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]); #endif } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!RESTART(z->marker)) return 1; reset(z); } } } } return 1; } static int process_marker(jpeg *z, int m) { int L; switch (m) { case MARKER_none: // no marker found return e("expected marker","Corrupt JPEG"); case 0xC2: // SOF - progressive return e("progressive jpeg","JPEG format not supported (progressive)"); case 0xDD: // DRI - specify restart interval if (get16(&z->s) != 4) return e("bad DRI len","Corrupt JPEG"); z->restart_interval = get16(&z->s); return 1; case 0xDB: // DQT - define quantization table L = get16(&z->s)-2; while (L > 0) { int q = get8(&z->s); int p = q >> 4; int t = q & 15,i; if (p != 0) return e("bad DQT type","Corrupt JPEG"); if (t > 3) return e("bad DQT table","Corrupt JPEG"); for (i=0; i < 64; ++i) z->dequant[t][dezigzag[i]] = get8u(&z->s); #if STBI_SIMD for (i=0; i < 64; ++i) z->dequant2[t][i] = dequant[t][i]; #endif L -= 65; } return L==0; case 0xC4: // DHT - define huffman table L = get16(&z->s)-2; while (L > 0) { uint8 *v; int sizes[16],i,m=0; int q = get8(&z->s); int tc = q >> 4; int th = q & 15; if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG"); for (i=0; i < 16; ++i) { sizes[i] = get8(&z->s); m += sizes[i]; } L -= 17; if (tc == 0) { if (!build_huffman(z->huff_dc+th, sizes)) return 0; v = z->huff_dc[th].values; } else { if (!build_huffman(z->huff_ac+th, sizes)) return 0; v = z->huff_ac[th].values; } for (i=0; i < m; ++i) v[i] = get8u(&z->s); L -= m; } return L==0; } // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { skip(&z->s, get16(&z->s)-2); return 1; } return 0; } // after we see SOS static int process_scan_header(jpeg *z) { int i; int Ls = get16(&z->s); z->scan_n = get8(&z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s.img_n) return e("bad SOS component count","Corrupt JPEG"); if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG"); for (i=0; i < z->scan_n; ++i) { int id = get8(&z->s), which; int q = get8(&z->s); for (which = 0; which < z->s.img_n; ++which) if (z->img_comp[which].id == id) break; if (which == z->s.img_n) return 0; z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG"); z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG"); z->order[i] = which; } if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG"); get8(&z->s); // should be 63, but might be 0 if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG"); return 1; } static int process_frame_header(jpeg *z, int scan) { stbi *s = &z->s; int Lf,p,i,q, h_max=1,v_max=1,c; Lf = get16(s); if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG p = get8(s); if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = get16(s); if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = get16(s); if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires c = get8(s); if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG"); // JFIF requires s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; z->img_comp[i].linebuf = NULL; } if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG"); for (i=0; i < s->img_n; ++i) { z->img_comp[i].id = get8(s); if (z->img_comp[i].id != i+1) // JFIF requires if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files! return e("bad component ID","Corrupt JPEG"); q = get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG"); z->img_comp[i].tq = get8(s); if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG"); } if (scan != SCAN_load) return 1; if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; for (i=0; i < s->img_n; ++i) { // number of effective pixels (e.g. for non-interleaved MCU) z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; // to simplify generation, we'll allocate enough memory to decode // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15); if (z->img_comp[i].raw_data == NULL) { for(--i; i >= 0; --i) { free(z->img_comp[i].raw_data); z->img_comp[i].data = NULL; } return e("outofmem", "Out of memory"); } // align blocks for installable-idct using mmx/sse z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); z->img_comp[i].linebuf = NULL; } return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) #define DNL(x) ((x) == 0xdc) #define SOI(x) ((x) == 0xd8) #define EOI(x) ((x) == 0xd9) #define SOF(x) ((x) == 0xc0 || (x) == 0xc1) #define SOS(x) ((x) == 0xda) static int decode_jpeg_header(jpeg *z, int scan) { int m; z->marker = MARKER_none; // initialize cached marker to empty m = get_marker(z); if (!SOI(m)) return e("no SOI","Corrupt JPEG"); if (scan == SCAN_type) return 1; m = get_marker(z); while (!SOF(m)) { if (!process_marker(z,m)) return 0; m = get_marker(z); while (m == MARKER_none) { // some files have extra padding after their blocks, so ok, we'll scan if (at_eof(&z->s)) return e("no SOF", "Corrupt JPEG"); m = get_marker(z); } } if (!process_frame_header(z, scan)) return 0; return 1; } static int decode_jpeg_image(jpeg *j) { int m; j->restart_interval = 0; if (!decode_jpeg_header(j, SCAN_load)) return 0; m = get_marker(j); while (!EOI(m)) { if (SOS(m)) { if (!process_scan_header(j)) return 0; if (!parse_entropy_coded_data(j)) return 0; } else { if (!process_marker(j, m)) return 0; } m = get_marker(j); } return 1; } // static jfif-centered resampling (across block boundaries) typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1, int w, int hs); #define div4(x) ((uint8) ((x) >> 2)) static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { return in_near; } static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; for (i=0; i < w; ++i) out[i] = div4(3*in_near[i] + in_far[i] + 2); return out; } static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; uint8 *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation out[0] = out[1] = input[0]; return out; } out[0] = input[0]; out[1] = div4(input[0]*3 + input[1] + 2); for (i=1; i < w-1; ++i) { int n = 3*input[i]+2; out[i*2+0] = div4(n+input[i-1]); out[i*2+1] = div4(n+input[i+1]); } out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2); out[i*2+1] = input[w-1]; return out; } #define div16(x) ((uint8) ((x) >> 4)) static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i,t0,t1; if (w == 1) { out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; out[0] = div4(t1+2); for (i=1; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = div16(3*t0 + t1 + 8); out[i*2 ] = div16(3*t1 + t0 + 8); } out[w*2-1] = div4(t1+2); return out; } static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // resample with nearest-neighbor int i,j; for (i=0; i < w; ++i) for (j=0; j < hs; ++j) out[i*hs+j] = in_near[i]; return out; } #define float2fixed(x) ((int) ((x) * 65536 + 0.5)) // 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro) // VC6 without processor=Pro is generating multiple LEAs per multiply! static void YCbCr_to_RGB_row(uint8 *out, uint8 *y, uint8 *pcb, uint8 *pcr, int count, int step) { int i; for (i=0; i < count; ++i) { int y_fixed = (y[i] << 16) + 32768; // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr*float2fixed(1.40200f); g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); b = y_fixed + cb*float2fixed(1.77200f); r >>= 16; g >>= 16; b >>= 16; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (uint8)r; out[1] = (uint8)g; out[2] = (uint8)b; out[3] = 255; out += step; } } #if STBI_SIMD static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row; void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func) { stbi_YCbCr_installed = func; } #endif // clean up the temporary component buffers static void cleanup_jpeg(jpeg *j) { int i; for (i=0; i < j->s.img_n; ++i) { if (j->img_comp[i].data) { free(j->img_comp[i].raw_data); j->img_comp[i].data = NULL; } if (j->img_comp[i].linebuf) { free(j->img_comp[i].linebuf); j->img_comp[i].linebuf = NULL; } } } typedef struct { resample_row_func resample; uint8 *line0,*line1; int hs,vs; // expansion factor in each axis int w_lores; // horizontal pixels pre-expansion int ystep; // how far through vertical expansion we are int ypos; // which pre-expansion row we're on } stbi_resample; static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { int n, decode_n; // validate req_comp if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error"); z->s.img_n = 0; // load a jpeg image from whichever source if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; } // determine actual number of components to generate n = req_comp ? req_comp : z->s.img_n; if (z->s.img_n == 3 && n < 3) decode_n = 1; else decode_n = z->s.img_n; // resample and color-convert { int k; uint i,j; uint8 *output; uint8 *coutput[4]; stbi_resample res_comp[4]; for (k=0; k < decode_n; ++k) { stbi_resample *r = &res_comp[k]; // allocate line buffer big enough for upsampling off the edges // with upsample factor of 4 z->img_comp[k].linebuf = (uint8 *) malloc(z->s.img_x + 3); if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); } r->hs = z->img_h_max / z->img_comp[k].h; r->vs = z->img_v_max / z->img_comp[k].v; r->ystep = r->vs >> 1; r->w_lores = (z->s.img_x + r->hs-1) / r->hs; r->ypos = 0; r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2; else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2; else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2; else r->resample = resample_row_generic; } // can't error after this so, this is safe output = (uint8 *) malloc(n * z->s.img_x * z->s.img_y + 1); if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); } // now go ahead and resample for (j=0; j < z->s.img_y; ++j) { uint8 *out = output + n * z->s.img_x * j; for (k=0; k < decode_n; ++k) { stbi_resample *r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { uint8 *y = coutput[0]; if (z->s.img_n == 3) { #if STBI_SIMD stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n); #else YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s.img_x, n); #endif } else for (i=0; i < z->s.img_x; ++i) { out[0] = out[1] = out[2] = y[i]; out[3] = 255; // not used if n==3 out += n; } } else { uint8 *y = coutput[0]; if (n == 1) for (i=0; i < z->s.img_x; ++i) out[i] = y[i]; else for (i=0; i < z->s.img_x; ++i) *out++ = y[i], *out++ = 255; } } cleanup_jpeg(z); *out_x = z->s.img_x; *out_y = z->s.img_y; if (comp) *comp = z->s.img_n; // report original components, not output return output; } } #ifndef STBI_NO_STDIO unsigned char *stbi_jpeg_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { jpeg j; start_file(&j.s, f); return load_jpeg_image(&j, x,y,comp,req_comp); } unsigned char *stbi_jpeg_load(char const *filename, int *x, int *y, int *comp, int req_comp) { unsigned char *data; FILE *f = fopen(filename, "rb"); if (!f) return NULL; data = stbi_jpeg_load_from_file(f,x,y,comp,req_comp); fclose(f); return data; } #endif unsigned char *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { jpeg j; start_mem(&j.s, buffer,len); return load_jpeg_image(&j, x,y,comp,req_comp); } #ifndef STBI_NO_STDIO int stbi_jpeg_test_file(FILE *f) { int n,r; jpeg j; n = ftell(f); start_file(&j.s, f); r = decode_jpeg_header(&j, SCAN_type); fseek(f,n,SEEK_SET); return r; } #endif int stbi_jpeg_test_memory(stbi_uc const *buffer, int len) { jpeg j; start_mem(&j.s, buffer,len); return decode_jpeg_header(&j, SCAN_type); } // @TODO: #ifndef STBI_NO_STDIO extern int stbi_jpeg_info (char const *filename, int *x, int *y, int *comp); extern int stbi_jpeg_info_from_file (FILE *f, int *x, int *y, int *comp); #endif extern int stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); // public domain zlib decode v0.2 Sean Barrett 2006-11-18 // simple implementation // - all input must be provided in an upfront buffer // - all output is written to a single output buffer (can malloc/realloc) // performance // - fast huffman // fast-way is faster to check than jpeg huffman, but slow way is slower #define ZFAST_BITS 9 // accelerate all cases in default tables #define ZFAST_MASK ((1 << ZFAST_BITS) - 1) // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) typedef struct { uint16 fast[1 << ZFAST_BITS]; uint16 firstcode[16]; int maxcode[17]; uint16 firstsymbol[16]; uint8 size[288]; uint16 value[288]; } zhuffman; __forceinline static int bitreverse16(int n) { n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); return n; } __forceinline static int bit_reverse(int v, int bits) { assert(bits <= 16); // to bit reverse n bits, reverse 16 and shift // e.g. 11 bits, bit reverse and shift away 5 return bitreverse16(v) >> (16-bits); } static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; // DEFLATE spec for generating codes memset(sizes, 0, sizeof(sizes)); memset(z->fast, 255, sizeof(z->fast)); for (i=0; i < num; ++i) ++sizes[sizelist[i]]; sizes[0] = 0; for (i=1; i < 16; ++i) assert(sizes[i] <= (1 << i)); code = 0; for (i=1; i < 16; ++i) { next_code[i] = code; z->firstcode[i] = (uint16) code; z->firstsymbol[i] = (uint16) k; code = (code + sizes[i]); if (sizes[i]) if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG"); z->maxcode[i] = code << (16-i); // preshift for inner loop code <<= 1; k += sizes[i]; } z->maxcode[16] = 0x10000; // sentinel for (i=0; i < num; ++i) { int s = sizelist[i]; if (s) { int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; z->size[c] = (uint8)s; z->value[c] = (uint16)i; if (s <= ZFAST_BITS) { int k = bit_reverse(next_code[s],s); while (k < (1 << ZFAST_BITS)) { z->fast[k] = (uint16) c; k += (1 << s); } } ++next_code[s]; } } return 1; } // zlib-from-memory implementation for PNG reading // because PNG allows splitting the zlib stream arbitrarily, // and it's annoying structurally to have PNG call ZLIB call PNG, // we require PNG read all the IDATs and combine them into a single // memory buffer typedef struct { uint8 *zbuffer, *zbuffer_end; int num_bits; uint32 code_buffer; char *zout; char *zout_start; char *zout_end; int z_expandable; zhuffman z_length, z_distance; } zbuf; __forceinline static int zget8(zbuf *z) { if (z->zbuffer >= z->zbuffer_end) return 0; return *z->zbuffer++; } static void fill_bits(zbuf *z) { do { assert(z->code_buffer < (1U << z->num_bits)); z->code_buffer |= zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); } __forceinline static unsigned int zreceive(zbuf *z, int n) { unsigned int k; if (z->num_bits < n) fill_bits(z); k = z->code_buffer & ((1 << n) - 1); z->code_buffer >>= n; z->num_bits -= n; return k; } __forceinline static int zhuffman_decode(zbuf *a, zhuffman *z) { int b,s,k; if (a->num_bits < 16) fill_bits(a); b = z->fast[a->code_buffer & ZFAST_MASK]; if (b < 0xffff) { s = z->size[b]; a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } // not resolved by fast table, so compute it the slow way // use jpeg approach, which requires MSbits at top k = bit_reverse(a->code_buffer, 16); for (s=ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; if (s == 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; assert(z->size[b] == s); a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } static int expand(zbuf *z, int n) // need to make room for n bytes { char *q; int cur, limit; if (!z->z_expandable) return e("output buffer limit","Corrupt PNG"); cur = (int) (z->zout - z->zout_start); limit = (int) (z->zout_end - z->zout_start); while (cur + n > limit) limit *= 2; q = (char *) realloc(z->zout_start, limit); if (q == NULL) return e("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; z->zout_end = q + limit; return 1; } static int length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static int length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static int dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static int parse_huffman_block(zbuf *a) { for(;;) { int z = zhuffman_decode(a, &a->z_length); if (z < 256) { if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0; *a->zout++ = (char) z; } else { uint8 *p; int len,dist; if (z == 256) return 1; z -= 257; len = length_base[z]; if (length_extra[z]) len += zreceive(a, length_extra[z]); z = zhuffman_decode(a, &a->z_distance); if (z < 0) return e("bad huffman code","Corrupt PNG"); dist = dist_base[z]; if (dist_extra[z]) dist += zreceive(a, dist_extra[z]); if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0; p = (uint8 *) (a->zout - dist); while (len--) *a->zout++ = *p++; } } } static int compute_huffman_codes(zbuf *a) { static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; static zhuffman z_codelength; // static just to save stack space uint8 lencodes[286+32+137];//padding for maximum single op uint8 codelength_sizes[19]; int i,n; int hlit = zreceive(a,5) + 257; int hdist = zreceive(a,5) + 1; int hclen = zreceive(a,4) + 4; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { int s = zreceive(a,3); codelength_sizes[length_dezigzag[i]] = (uint8) s; } if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; while (n < hlit + hdist) { int c = zhuffman_decode(a, &z_codelength); assert(c >= 0 && c < 19); if (c < 16) lencodes[n++] = (uint8) c; else if (c == 16) { c = zreceive(a,2)+3; memset(lencodes+n, lencodes[n-1], c); n += c; } else if (c == 17) { c = zreceive(a,3)+3; memset(lencodes+n, 0, c); n += c; } else { assert(c == 18); c = zreceive(a,7)+11; memset(lencodes+n, 0, c); n += c; } } if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG"); if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } static int parse_uncompressed_block(zbuf *a) { uint8 header[4]; int len,nlen,k; if (a->num_bits & 7) zreceive(a, a->num_bits & 7); // discard // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns? a->code_buffer >>= 8; a->num_bits -= 8; } assert(a->num_bits == 0); // now fill header the normal way while (k < 4) header[k++] = (uint8) zget8(a); len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG"); if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0; memcpy(a->zout, a->zbuffer, len); a->zbuffer += len; a->zout += len; return 1; } static int parse_zlib_header(zbuf *a) { int cmf = zget8(a); int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = zget8(a); if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png // window = 1 << (8 + cinfo)... but who cares, we fully buffer output return 1; } // @TODO: should statically initialize these for optimal thread safety static uint8 default_length[288], default_distance[32]; static void init_defaults(void) { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) default_length[i] = 8; for ( ; i <= 255; ++i) default_length[i] = 9; for ( ; i <= 279; ++i) default_length[i] = 7; for ( ; i <= 287; ++i) default_length[i] = 8; for (i=0; i <= 31; ++i) default_distance[i] = 5; } static int parse_zlib(zbuf *a, int parse_header) { int final, type; if (parse_header) if (!parse_zlib_header(a)) return 0; a->num_bits = 0; a->code_buffer = 0; do { final = zreceive(a,1); type = zreceive(a,2); if (type == 0) { if (!parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths if (!default_distance[31]) init_defaults(); if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0; if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0; } else { if (!compute_huffman_codes(a)) return 0; } if (!parse_huffman_block(a)) return 0; } } while (!final); return 1; } static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; a->z_expandable = exp; return parse_zlib(a, parse_header); } char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) { zbuf a; char *p = (char *) malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (uint8 *) buffer; a.zbuffer_end = (uint8 *) buffer + len; if (do_zlib(&a, p, initial_size, 1, 1)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { free(a.zout_start); return NULL; } } char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) { zbuf a; a.zbuffer = (uint8 *) ibuffer; a.zbuffer_end = (uint8 *) ibuffer + ilen; if (do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start); else return -1; } char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) { zbuf a; char *p = (char *) malloc(16384); if (p == NULL) return NULL; a.zbuffer = (uint8 *) buffer; a.zbuffer_end = (uint8 *) buffer+len; if (do_zlib(&a, p, 16384, 1, 0)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { free(a.zout_start); return NULL; } } int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) { zbuf a; a.zbuffer = (uint8 *) ibuffer; a.zbuffer_end = (uint8 *) ibuffer + ilen; if (do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start); else return -1; } // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 // simple implementation // - only 8-bit samples // - no CRC checking // - allocates lots of intermediate memory // - avoids problem of streaming data between subsystems // - avoids explicit window management // performance // - uses stb_zlib, a PD zlib implementation with fast huffman decoding typedef struct { uint32 length; uint32 type; } chunk; #define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) static chunk get_chunk_header(stbi *s) { chunk c; c.length = get32(s); c.type = get32(s); return c; } static int check_png_header(stbi *s) { static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (get8(s) != png_sig[i]) return e("bad png sig","Not a PNG"); return 1; } typedef struct { stbi s; uint8 *idata, *expanded, *out; } png; enum { F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4, F_avg_first, F_paeth_first, }; static uint8 first_row_filter[5] = { F_none, F_sub, F_none, F_avg_first, F_paeth_first }; static int paeth(int a, int b, int c) { int p = a + b - c; int pa = abs(p-a); int pb = abs(p-b); int pc = abs(p-c); if (pa <= pb && pa <= pc) return a; if (pb <= pc) return b; return c; } // create the png data from post-deflated data static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n) { stbi *s = &a->s; uint32 i,j,stride = s->img_x*out_n; int k; int img_n = s->img_n; // copy it into a local for later assert(out_n == s->img_n || out_n == s->img_n+1); a->out = (uint8 *) malloc(s->img_x * s->img_y * out_n); if (!a->out) return e("outofmem", "Out of memory"); if (raw_len != (img_n * s->img_x + 1) * s->img_y) return e("not enough pixels","Corrupt PNG"); for (j=0; j < s->img_y; ++j) { uint8 *cur = a->out + stride*j; uint8 *prior = cur - stride; int filter = *raw++; if (filter > 4) return e("invalid filter","Corrupt PNG"); // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; // handle first pixel explicitly for (k=0; k < img_n; ++k) { switch(filter) { case F_none : cur[k] = raw[k]; break; case F_sub : cur[k] = raw[k]; break; case F_up : cur[k] = raw[k] + prior[k]; break; case F_avg : cur[k] = raw[k] + (prior[k]>>1); break; case F_paeth : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break; case F_avg_first : cur[k] = raw[k]; break; case F_paeth_first: cur[k] = raw[k]; break; } } if (img_n != out_n) cur[img_n] = 255; raw += img_n; cur += out_n; prior += out_n; // this is a little gross, so that we don't switch per-pixel or per-component if (img_n == out_n) { #define CASE(f) \ case f: \ for (i=s->img_x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \ for (k=0; k < img_n; ++k) switch(filter) { CASE(F_none) cur[k] = raw[k]; break; CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break; CASE(F_up) cur[k] = raw[k] + prior[k]; break; CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break; CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break; CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break; CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break; } #undef CASE } else { assert(img_n+1 == out_n); #define CASE(f) \ case f: \ for (i=s->img_x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \ for (k=0; k < img_n; ++k) switch(filter) { CASE(F_none) cur[k] = raw[k]; break; CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break; CASE(F_up) cur[k] = raw[k] + prior[k]; break; CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break; CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break; CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break; CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break; } #undef CASE } } return 1; } static int compute_transparency(png *z, uint8 tc[3], int out_n) { stbi *s = &z->s; uint32 i, pixel_count = s->img_x * s->img_y; uint8 *p = z->out; // compute color-based transparency, assuming we've // already got 255 as the alpha value in the output assert(out_n == 2 || out_n == 4); if (out_n == 2) { for (i=0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 255); p += 2; } } else { for (i=0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n) { uint32 i, pixel_count = a->s.img_x * a->s.img_y; uint8 *p, *temp_out, *orig = a->out; p = (uint8 *) malloc(pixel_count * pal_img_n); if (p == NULL) return e("outofmem", "Out of memory"); // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p += 3; } } else { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p[3] = palette[n+3]; p += 4; } } free(a->out); a->out = temp_out; return 1; } static int parse_png_file(png *z, int scan, int req_comp) { uint8 palette[1024], pal_img_n=0; uint8 has_trans=0, tc[3]; uint32 ioff=0, idata_limit=0, i, pal_len=0; int first=1,k; stbi *s = &z->s; if (!check_png_header(s)) return 0; if (scan == SCAN_type) return 1; for(;;first=0) { chunk c = get_chunk_header(s); if (first && c.type != PNG_TYPE('I','H','D','R')) return e("first not IHDR","Corrupt PNG"); switch (c.type) { case PNG_TYPE('I','H','D','R'): { int depth,color,interlace,comp,filter; if (!first) return e("multiple IHDR","Corrupt PNG"); if (c.length != 13) return e("bad IHDR len","Corrupt PNG"); s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)"); s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)"); depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only"); color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG"); comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG"); filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG"); interlace = get8(s); if (interlace) return e("interlaced","PNG not supported: interlaced mode"); if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode"); if (scan == SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG"); // if SCAN_header, have to scan to see if we have a tRNS } break; } case PNG_TYPE('P','L','T','E'): { if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG"); pal_len = c.length / 3; if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG"); for (i=0; i < pal_len; ++i) { palette[i*4+0] = get8u(s); palette[i*4+1] = get8u(s); palette[i*4+2] = get8u(s); palette[i*4+3] = 255; } break; } case PNG_TYPE('t','R','N','S'): { if (z->idata) return e("tRNS after IDAT","Corrupt PNG"); if (pal_img_n) { if (scan == SCAN_header) { s->img_n = 4; return 1; } if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG"); if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG"); pal_img_n = 4; for (i=0; i < c.length; ++i) palette[i*4+3] = get8u(s); } else { if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG"); if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG"); has_trans = 1; for (k=0; k < s->img_n; ++k) tc[k] = (uint8) get16(s); // non 8-bit images will be larger } break; } case PNG_TYPE('I','D','A','T'): { if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG"); if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; } if (ioff + c.length > idata_limit) { uint8 *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory"); z->idata = p; } #ifndef STBI_NO_STDIO if (s->img_file) { if (fread(z->idata+ioff,1,c.length,s->img_file) != c.length) return e("outofdata","Corrupt PNG"); } else #endif { memcpy(z->idata+ioff, s->img_buffer, c.length); s->img_buffer += c.length; } ioff += c.length; break; } case PNG_TYPE('I','E','N','D'): { uint32 raw_len; if (scan != SCAN_load) return 1; if (z->idata == NULL) return e("no IDAT","Corrupt PNG"); z->expanded = (uint8 *) stbi_zlib_decode_malloc((char *) z->idata, ioff, (int *) &raw_len); if (z->expanded == NULL) return 0; // zlib should set error free(z->idata); z->idata = NULL; if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; if (!create_png_image(z, z->expanded, raw_len, s->img_out_n)) return 0; if (has_trans) if (!compute_transparency(z, tc, s->img_out_n)) return 0; if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; if (!expand_palette(z, palette, pal_len, s->img_out_n)) return 0; } free(z->expanded); z->expanded = NULL; return 1; } default: // if critical, fail if ((c.type & (1 << 29)) == 0) { #ifndef STBI_NO_FAILURE_STRINGS // not threadsafe static char invalid_chunk[] = "XXXX chunk not known"; invalid_chunk[0] = (uint8) (c.type >> 24); invalid_chunk[1] = (uint8) (c.type >> 16); invalid_chunk[2] = (uint8) (c.type >> 8); invalid_chunk[3] = (uint8) (c.type >> 0); #endif return e(invalid_chunk, "PNG not supported: unknown chunk type"); } skip(s, c.length); break; } // end of chunk, read and skip CRC get32(s); } } static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp) { unsigned char *result=NULL; p->expanded = NULL; p->idata = NULL; p->out = NULL; if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error"); if (parse_png_file(p, SCAN_load, req_comp)) { result = p->out; p->out = NULL; if (req_comp && req_comp != p->s.img_out_n) { result = convert_format(result, p->s.img_out_n, req_comp, p->s.img_x, p->s.img_y); p->s.img_out_n = req_comp; if (result == NULL) return result; } *x = p->s.img_x; *y = p->s.img_y; if (n) *n = p->s.img_n; } free(p->out); p->out = NULL; free(p->expanded); p->expanded = NULL; free(p->idata); p->idata = NULL; return result; } #ifndef STBI_NO_STDIO unsigned char *stbi_png_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { png p; start_file(&p.s, f); return do_png(&p, x,y,comp,req_comp); } unsigned char *stbi_png_load(char const *filename, int *x, int *y, int *comp, int req_comp) { unsigned char *data; FILE *f = fopen(filename, "rb"); if (!f) return NULL; data = stbi_png_load_from_file(f,x,y,comp,req_comp); fclose(f); return data; } #endif unsigned char *stbi_png_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { png p; start_mem(&p.s, buffer,len); return do_png(&p, x,y,comp,req_comp); } #ifndef STBI_NO_STDIO int stbi_png_test_file(FILE *f) { png p; int n,r; n = ftell(f); start_file(&p.s, f); r = parse_png_file(&p, SCAN_type,STBI_default); fseek(f,n,SEEK_SET); return r; } #endif int stbi_png_test_memory(stbi_uc const *buffer, int len) { png p; start_mem(&p.s, buffer, len); return parse_png_file(&p, SCAN_type,STBI_default); } // TODO: load header from png #ifndef STBI_NO_STDIO extern int stbi_png_info (char const *filename, int *x, int *y, int *comp); extern int stbi_png_info_from_file (FILE *f, int *x, int *y, int *comp); #endif extern int stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp); // Microsoft/Windows BMP image static int bmp_test(stbi *s) { int sz; if (get8(s) != 'B') return 0; if (get8(s) != 'M') return 0; get32le(s); // discard filesize get16le(s); // discard reserved get16le(s); // discard reserved get32le(s); // discard data offset sz = get32le(s); if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1; return 0; } #ifndef STBI_NO_STDIO int stbi_bmp_test_file (FILE *f) { stbi s; int r,n = ftell(f); start_file(&s,f); r = bmp_test(&s); fseek(f,n,SEEK_SET); return r; } #endif int stbi_bmp_test_memory (stbi_uc const *buffer, int len) { stbi s; start_mem(&s, buffer, len); return bmp_test(&s); } // returns 0..31 for the highest set bit static int high_bit(unsigned int z) { int n=0; if (z == 0) return -1; if (z >= 0x10000) n += 16, z >>= 16; if (z >= 0x00100) n += 8, z >>= 8; if (z >= 0x00010) n += 4, z >>= 4; if (z >= 0x00004) n += 2, z >>= 2; if (z >= 0x00002) n += 1, z >>= 1; return n; } static int bitcount(unsigned int a) { a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits a = (a + (a >> 8)); // max 16 per 8 bits a = (a + (a >> 16)); // max 32 per 8 bits return a & 0xff; } static int shiftsigned(int v, int shift, int bits) { int result; int z=0; if (shift < 0) v <<= -shift; else v >>= shift; result = v; z = bits; while (z < 8) { result += v >> z; z += bits; } return result; } static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp) { uint8 *out; unsigned int mr=0,mg=0,mb=0,ma=0; stbi_uc pal[256][4]; int psize=0,i,j,compress=0,width; int bpp, flip_vertically, pad, target, offset, hsz; if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP"); get32le(s); // discard filesize get16le(s); // discard reserved get16le(s); // discard reserved offset = get32le(s); hsz = get32le(s); if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown"); failure_reason = "bad BMP"; if (hsz == 12) { s->img_x = get16le(s); s->img_y = get16le(s); } else { s->img_x = get32le(s); s->img_y = get32le(s); } if (get16le(s) != 1) return 0; bpp = get16le(s); if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit"); flip_vertically = ((int) s->img_y) > 0; s->img_y = abs((int) s->img_y); if (hsz == 12) { if (bpp < 24) psize = (offset - 14 - 24) / 3; } else { compress = get32le(s); if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE"); get32le(s); // discard sizeof get32le(s); // discard hres get32le(s); // discard vres get32le(s); // discard colorsused get32le(s); // discard max important if (hsz == 40 || hsz == 56) { if (hsz == 56) { get32le(s); get32le(s); get32le(s); get32le(s); } if (bpp == 16 || bpp == 32) { mr = mg = mb = 0; if (compress == 0) { if (bpp == 32) { mr = 0xff << 16; mg = 0xff << 8; mb = 0xff << 0; } else { mr = 31 << 10; mg = 31 << 5; mb = 31 << 0; } } else if (compress == 3) { mr = get32le(s); mg = get32le(s); mb = get32le(s); // not documented, but generated by photoshop and handled by mspaint if (mr == mg && mg == mb) { // ?!?!? return NULL; } } else return NULL; } } else { assert(hsz == 108); mr = get32le(s); mg = get32le(s); mb = get32le(s); ma = get32le(s); get32le(s); // discard color space for (i=0; i < 12; ++i) get32le(s); // discard color space parameters } if (bpp < 16) psize = (offset - 14 - hsz) >> 2; } s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert out = (stbi_uc *) malloc(target * s->img_x * s->img_y); if (!out) return epuc("outofmem", "Out of memory"); if (bpp < 16) { int z=0; if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = get8(s); pal[i][1] = get8(s); pal[i][0] = get8(s); if (hsz != 12) get8(s); pal[i][3] = 255; } skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4)); if (bpp == 4) width = (s->img_x + 1) >> 1; else if (bpp == 8) width = s->img_x; else { free(out); return epuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; for (j=0; j < (int) s->img_y; ++j) { for (i=0; i < (int) s->img_x; i += 2) { int v=get8(s),v2=0; if (bpp == 4) { v2 = v & 15; v >>= 4; } out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; v = (bpp == 8) ? get8(s) : v2; out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; } skip(s, pad); } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; skip(s, offset - 14 - hsz); if (bpp == 24) width = 3 * s->img_x; else if (bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; if (bpp == 24) { easy = 1; } else if (bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0xff000000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) return epuc("bad masks", "Corrupt BMP"); // right shift amt to put high bit in position #7 rshift = high_bit(mr)-7; rcount = bitcount(mr); gshift = high_bit(mg)-7; gcount = bitcount(mr); bshift = high_bit(mb)-7; bcount = bitcount(mr); ashift = high_bit(ma)-7; acount = bitcount(mr); } for (j=0; j < (int) s->img_y; ++j) { if (easy) { for (i=0; i < (int) s->img_x; ++i) { int a; out[z+2] = get8(s); out[z+1] = get8(s); out[z+0] = get8(s); z += 3; a = (easy == 2 ? get8(s) : 255); if (target == 4) out[z++] = a; } } else { for (i=0; i < (int) s->img_x; ++i) { uint32 v = (bpp == 16 ? get16le(s) : get32le(s)); int a; out[z++] = shiftsigned(v & mr, rshift, rcount); out[z++] = shiftsigned(v & mg, gshift, gcount); out[z++] = shiftsigned(v & mb, bshift, bcount); a = (ma ? shiftsigned(v & ma, ashift, acount) : 255); if (target == 4) out[z++] = a; } } skip(s, pad); } } if (flip_vertically) { stbi_uc t; for (j=0; j < (int) s->img_y>>1; ++j) { stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { t = p1[i], p1[i] = p2[i], p2[i] = t; } } } if (req_comp && req_comp != target) { out = convert_format(out, target, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // convert_format frees input on failure } *x = s->img_x; *y = s->img_y; if (comp) *comp = target; return out; } #ifndef STBI_NO_STDIO stbi_uc *stbi_bmp_load (char const *filename, int *x, int *y, int *comp, int req_comp) { stbi_uc *data; FILE *f = fopen(filename, "rb"); if (!f) return NULL; data = stbi_bmp_load_from_file(f, x,y,comp,req_comp); fclose(f); return data; } stbi_uc *stbi_bmp_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp) { stbi s; start_file(&s, f); return bmp_load(&s, x,y,comp,req_comp); } #endif stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi s; start_mem(&s, buffer, len); return bmp_load(&s, x,y,comp,req_comp); } // Targa Truevision - TGA // by Jonathan Dummer static int tga_test(stbi *s) { int sz; get8u(s); // discard Offset sz = get8u(s); // color type if( sz > 1 ) return 0; // only RGB or indexed allowed sz = get8u(s); // image type if( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE get16(s); // discard palette start get16(s); // discard palette length get8(s); // discard bits per palette color entry get16(s); // discard x origin get16(s); // discard y origin if( get16(s) < 1 ) return 0; // test width if( get16(s) < 1 ) return 0; // test height sz = get8(s); // bits per pixel if( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed return 1; // seems to have passed everything } #ifndef STBI_NO_STDIO int stbi_tga_test_file (FILE *f) { stbi s; int r,n = ftell(f); start_file(&s, f); r = tga_test(&s); fseek(f,n,SEEK_SET); return r; } #endif int stbi_tga_test_memory (stbi_uc const *buffer, int len) { stbi s; start_mem(&s, buffer, len); return tga_test(&s); } static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp) { // read in the TGA header stuff int tga_offset = get8u(s); int tga_indexed = get8u(s); int tga_image_type = get8u(s); int tga_is_RLE = 0; int tga_palette_start = get16le(s); int tga_palette_len = get16le(s); int tga_palette_bits = get8u(s); int tga_x_origin = get16le(s); int tga_y_origin = get16le(s); int tga_width = get16le(s); int tga_height = get16le(s); int tga_bits_per_pixel = get8u(s); int tga_inverted = get8u(s); // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; unsigned char raw_data[4]; unsigned char trans_data[] = { 0,0,0,0 }; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; // do a tiny bit of precessing if( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } /* int tga_alpha_bits = tga_inverted & 15; */ tga_inverted = 1 - ((tga_inverted >> 5) & 1); // error check if( //(tga_indexed) || (tga_width < 1) || (tga_height < 1) || (tga_image_type < 1) || (tga_image_type > 3) || ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) && (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32)) ) { return NULL; } // If I'm paletted, then I'll use the number of bits from the palette if( tga_indexed ) { tga_bits_per_pixel = tga_palette_bits; } // tga info *x = tga_width; *y = tga_height; if( (req_comp < 1) || (req_comp > 4) ) { // just use whatever the file was req_comp = tga_bits_per_pixel / 8; *comp = req_comp; } else { // force a new number of components *comp = tga_bits_per_pixel/8; } tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp ); // skip to the data's starting position (offset usually = 0) skip(s, tga_offset ); // do I need to load a palette? if( tga_indexed ) { // any data to skip? (offset usually = 0) skip(s, tga_palette_start ); // load the palette tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 ); getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 ); } // load the data for( i = 0; i < tga_width * tga_height; ++i ) { // if I'm in RLE mode, do I need to get a RLE chunk? if( tga_is_RLE ) { if( RLE_count == 0 ) { // yep, get the next byte as a RLE command int RLE_cmd = get8u(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; } else if( !RLE_repeating ) { read_next_pixel = 1; } } else { read_next_pixel = 1; } // OK, if I need to read a pixel, do it now if( read_next_pixel ) { // load however much data we did have if( tga_indexed ) { // read in 1 byte, then perform the lookup int pal_idx = get8u(s); if( pal_idx >= tga_palette_len ) { // invalid index pal_idx = 0; } pal_idx *= tga_bits_per_pixel / 8; for( j = 0; j*8 < tga_bits_per_pixel; ++j ) { raw_data[j] = tga_palette[pal_idx+j]; } } else { // read in the data raw for( j = 0; j*8 < tga_bits_per_pixel; ++j ) { raw_data[j] = get8u(s); } } // convert raw to the intermediate format switch( tga_bits_per_pixel ) { case 8: // Luminous => RGBA trans_data[0] = raw_data[0]; trans_data[1] = raw_data[0]; trans_data[2] = raw_data[0]; trans_data[3] = 255; break; case 16: // Luminous,Alpha => RGBA trans_data[0] = raw_data[0]; trans_data[1] = raw_data[0]; trans_data[2] = raw_data[0]; trans_data[3] = raw_data[1]; break; case 24: // BGR => RGBA trans_data[0] = raw_data[2]; trans_data[1] = raw_data[1]; trans_data[2] = raw_data[0]; trans_data[3] = 255; break; case 32: // BGRA => RGBA trans_data[0] = raw_data[2]; trans_data[1] = raw_data[1]; trans_data[2] = raw_data[0]; trans_data[3] = raw_data[3]; break; } // clear the reading flag for the next pixel read_next_pixel = 0; } // end of reading a pixel // convert to final format switch( req_comp ) { case 1: // RGBA => Luminance tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]); break; case 2: // RGBA => Luminance,Alpha tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]); tga_data[i*req_comp+1] = trans_data[3]; break; case 3: // RGBA => RGB tga_data[i*req_comp+0] = trans_data[0]; tga_data[i*req_comp+1] = trans_data[1]; tga_data[i*req_comp+2] = trans_data[2]; break; case 4: // RGBA => RGBA tga_data[i*req_comp+0] = trans_data[0]; tga_data[i*req_comp+1] = trans_data[1]; tga_data[i*req_comp+2] = trans_data[2]; tga_data[i*req_comp+3] = trans_data[3]; break; } // in case we're in RLE mode, keep counting down --RLE_count; } // do I need to invert the image? if( tga_inverted ) { for( j = 0; j*2 < tga_height; ++j ) { int index1 = j * tga_width * req_comp; int index2 = (tga_height - 1 - j) * tga_width * req_comp; for( i = tga_width * req_comp; i > 0; --i ) { unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; ++index2; } } } // clear my palette, if I had one if( tga_palette != NULL ) { free( tga_palette ); } // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; // OK, done return tga_data; } #ifndef STBI_NO_STDIO stbi_uc *stbi_tga_load (char const *filename, int *x, int *y, int *comp, int req_comp) { stbi_uc *data; FILE *f = fopen(filename, "rb"); if (!f) return NULL; data = stbi_tga_load_from_file(f, x,y,comp,req_comp); fclose(f); return data; } stbi_uc *stbi_tga_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp) { stbi s; start_file(&s, f); return tga_load(&s, x,y,comp,req_comp); } #endif stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi s; start_mem(&s, buffer, len); return tga_load(&s, x,y,comp,req_comp); } // ************************************************************************************************* // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicholas Schulz, tweaked by STB static int psd_test(stbi *s) { if (get32(s) != 0x38425053) return 0; // "8BPS" else return 1; } #ifndef STBI_NO_STDIO int stbi_psd_test_file(FILE *f) { stbi s; int r,n = ftell(f); start_file(&s, f); r = psd_test(&s); fseek(f,n,SEEK_SET); return r; } #endif int stbi_psd_test_memory(stbi_uc const *buffer, int len) { stbi s; start_mem(&s, buffer, len); return psd_test(&s); } static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp) { int pixelCount; int channelCount, compression; int channel, i, count, len; int w,h; uint8 *out; // Check identifier if (get32(s) != 0x38425053) // "8BPS" return epuc("not PSD", "Corrupt PSD image"); // Check file type version. if (get16(s) != 1) return epuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. skip(s, 6 ); // Read the number of channels (R, G, B, A, etc). channelCount = get16(s); if (channelCount < 0 || channelCount > 16) return epuc("wrong channel count", "Unsupported number of channels in PSD image"); // Read the rows and columns of the image. h = get32(s); w = get32(s); // Make sure the depth is 8 bits. if (get16(s) != 8) return epuc("unsupported bit depth", "PSD bit depth is not 8 bit"); // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color if (get16(s) != 3) return epuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) skip(s,get32(s) ); // Skip the image resources. (resolution, pen tool paths, etc) skip(s, get32(s) ); // Skip the reserved data. skip(s, get32(s) ); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed compression = get16(s); if (compression > 1) return epuc("bad compression", "PSD has an unknown compression format"); // Create the destination image. out = (stbi_uc *) malloc(4 * w*h); if (!out) return epuc("outofmem", "Out of memory"); pixelCount = w*h; // Initialize the data to zero. //memset( out, 0, pixelCount * 4 ); // Finally, the image data. if (compression) { // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, // which we're going to just skip. skip(s, h * channelCount * 2 ); // Read the RLE data by channel. for (channel = 0; channel < 4; channel++) { uint8 *p; p = out+channel; if (channel >= channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4; } else { // Read the RLE data. count = 0; while (count < pixelCount) { len = get8(s); if (len == 128) { // No-op. } else if (len < 128) { // Copy next len+1 bytes literally. len++; count += len; while (len) { *p = get8(s); p += 4; len--; } } else if (len > 128) { uint32 val; // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) len ^= 0x0FF; len += 2; val = get8(s); count += len; while (len) { *p = val; p += 4; len--; } } } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { uint8 *p; p = out + channel; if (channel > channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4; } else { // Read the data. count = 0; for (i = 0; i < pixelCount; i++) *p = get8(s), p += 4; } } } if (req_comp && req_comp != 4) { out = convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // convert_format frees input on failure } if (comp) *comp = channelCount; *y = h; *x = w; return out; } #ifndef STBI_NO_STDIO stbi_uc *stbi_psd_load(char const *filename, int *x, int *y, int *comp, int req_comp) { stbi_uc *data; FILE *f = fopen(filename, "rb"); if (!f) return NULL; data = stbi_psd_load_from_file(f, x,y,comp,req_comp); fclose(f); return data; } stbi_uc *stbi_psd_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi s; start_file(&s, f); return psd_load(&s, x,y,comp,req_comp); } #endif stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi s; start_mem(&s, buffer, len); return psd_load(&s, x,y,comp,req_comp); } // ************************************************************************************************* // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR static int hdr_test(stbi *s) { char *signature = "#?RADIANCE\n"; int i; for (i=0; signature[i]; ++i) if (get8(s) != signature[i]) return 0; return 1; } int stbi_hdr_test_memory(stbi_uc const *buffer, int len) { stbi s; start_mem(&s, buffer, len); return hdr_test(&s); } #ifndef STBI_NO_STDIO int stbi_hdr_test_file(FILE *f) { stbi s; int r,n = ftell(f); start_file(&s, f); r = hdr_test(&s); fseek(f,n,SEEK_SET); return r; } #endif #define HDR_BUFLEN 1024 static char *hdr_gettoken(stbi *z, char *buffer) { int len=0; //char *s = buffer, char c = '\0'; c = get8(z); while (!at_eof(z) && c != '\n') { buffer[len++] = c; if (len == HDR_BUFLEN-1) { // flush to end of line while (!at_eof(z) && get8(z) != '\n') ; break; } c = get8(z); } buffer[len] = 0; return buffer; } static void hdr_convert(float *output, stbi_uc *input, int req_comp) { if( input[3] != 0 ) { float f1; // Exponent f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; output[2] = input[2] * f1; } if (req_comp == 2) output[1] = 1; if (req_comp == 4) output[3] = 1; } else { switch (req_comp) { case 4: output[3] = 1; /* fallthrough */ case 3: output[0] = output[1] = output[2] = 0; break; case 2: output[1] = 1; /* fallthrough */ case 1: output[0] = 0; break; } } } static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp) { char buffer[HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; float *hdr_data; int len; unsigned char count, value; int i, j, k, c1,c2, z; // Check identifier if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) return epf("not HDR", "Corrupt HDR image"); // Parse header while(1) { token = hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return epf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format"); token += 3; height = strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format"); token += 3; width = strtol(token, NULL, 10); *x = width; *y = height; *comp = 3; if (req_comp == 0) req_comp = 3; // Read data hdr_data = (float *) malloc(height * width * req_comp * sizeof(float)); // Load image data // image data is stored as some number of sca if( width < 8 || width >= 32768) { // Read flat data for (j=0; j < height; ++j) { for (i=0; i < width; ++i) { stbi_uc rgbe[4]; main_decode_loop: getn(s, rgbe, 4); hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); } } } else { // Read RLE-encoded data scanline = NULL; for (j = 0; j < height; ++j) { c1 = get8(s); c2 = get8(s); len = get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) stbi_uc rgbe[4] = { c1,c2,len, get8(s) }; hdr_convert(hdr_data, rgbe, req_comp); i = 1; j = 0; free(scanline); goto main_decode_loop; // yes, this is fucking insane; blame the fucking insane format } len <<= 8; len |= get8(s); if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4); for (k = 0; k < 4; ++k) { i = 0; while (i < width) { count = get8(s); if (count > 128) { // Run value = get8(s); count -= 128; for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = get8(s); } } } for (i=0; i < width; ++i) hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } free(scanline); } return hdr_data; } static stbi_uc *hdr_load_rgbe(stbi *s, int *x, int *y, int *comp, int req_comp) { char buffer[HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; stbi_uc *rgbe_data; int len; unsigned char count, value; int i, j, k, c1,c2, z; // Check identifier if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) return epuc("not HDR", "Corrupt HDR image"); // Parse header while(1) { token = hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return epuc("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) return epuc("unsupported data layout", "Unsupported HDR format"); token += 3; height = strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return epuc("unsupported data layout", "Unsupported HDR format"); token += 3; width = strtol(token, NULL, 10); *x = width; *y = height; // RGBE _MUST_ come out as 4 components *comp = 4; req_comp = 4; // Read data rgbe_data = (stbi_uc *) malloc(height * width * req_comp * sizeof(stbi_uc)); // point to the beginning scanline = rgbe_data; // Load image data // image data is stored as some number of scan lines if( width < 8 || width >= 32768) { // Read flat data for (j=0; j < height; ++j) { for (i=0; i < width; ++i) { main_decode_loop: //getn(rgbe, 4); getn(s,scanline, 4); scanline += 4; } } } else { // Read RLE-encoded data for (j = 0; j < height; ++j) { c1 = get8(s); c2 = get8(s); len = get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) scanline[0] = c1; scanline[1] = c2; scanline[2] = len; scanline[3] = get8(s); scanline += 4; i = 1; j = 0; goto main_decode_loop; // yes, this is insane; blame the insane format } len <<= 8; len |= get8(s); if (len != width) { free(rgbe_data); return epuc("invalid decoded scanline length", "corrupt HDR"); } for (k = 0; k < 4; ++k) { i = 0; while (i < width) { count = get8(s); if (count > 128) { // Run value = get8(s); count -= 128; for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = get8(s); } } } // move the scanline on scanline += 4 * width; } } return rgbe_data; } #ifndef STBI_NO_STDIO float *stbi_hdr_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi s; start_file(&s,f); return hdr_load(&s,x,y,comp,req_comp); } stbi_uc *stbi_hdr_load_rgbe_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi s; start_file(&s,f); return hdr_load_rgbe(&s,x,y,comp,req_comp); } stbi_uc *stbi_hdr_load_rgbe (char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = fopen(filename, "rb"); unsigned char *result; if (!f) return epuc("can't fopen", "Unable to open file"); result = stbi_hdr_load_rgbe_file(f,x,y,comp,req_comp); fclose(f); return result; } #endif float *stbi_hdr_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi s; start_mem(&s,buffer, len); return hdr_load(&s,x,y,comp,req_comp); } stbi_uc *stbi_hdr_load_rgbe_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi s; start_mem(&s,buffer, len); return hdr_load_rgbe(&s,x,y,comp,req_comp); } #endif // STBI_NO_HDR /////////////////////// write image /////////////////////// #ifndef STBI_NO_WRITE static void write8(FILE *f, int x) { uint8 z = (uint8) x; fwrite(&z,1,1,f); } static void writefv(FILE *f, char *fmt, va_list v) { while (*fmt) { switch (*fmt++) { case ' ': break; case '1': { uint8 x = va_arg(v, int); write8(f,x); break; } case '2': { int16 x = va_arg(v, int); write8(f,x); write8(f,x>>8); break; } case '4': { int32 x = va_arg(v, int); write8(f,x); write8(f,x>>8); write8(f,x>>16); write8(f,x>>24); break; } default: assert(0); va_end(v); return; } } } static void writef(FILE *f, char *fmt, ...) { va_list v; va_start(v, fmt); writefv(f,fmt,v); va_end(v); } static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad) { uint8 bg[3] = { 255, 0, 255}, px[3]; uint32 zero = 0; int i,j,k, j_end; if (vdir < 0) j_end = -1, j = y-1; else j_end = y, j = 0; for (; j != j_end; j += vdir) { for (i=0; i < x; ++i) { uint8 *d = (uint8 *) data + (j*x+i)*comp; if (write_alpha < 0) fwrite(&d[comp-1], 1, 1, f); switch (comp) { case 1: case 2: writef(f, "111", d[0],d[0],d[0]); break; case 4: if (!write_alpha) { for (k=0; k < 3; ++k) px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255; writef(f, "111", px[1-rgb_dir],px[1],px[1+rgb_dir]); break; } /* FALLTHROUGH */ case 3: writef(f, "111", d[1-rgb_dir],d[1],d[1+rgb_dir]); break; } if (write_alpha > 0) fwrite(&d[comp-1], 1, 1, f); } fwrite(&zero,scanline_pad,1,f); } } static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, char *fmt, ...) { FILE *f = fopen(filename, "wb"); if (f) { va_list v; va_start(v, fmt); writefv(f, fmt, v); va_end(v); write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad); fclose(f); } return f != NULL; } int stbi_write_bmp(char const *filename, int x, int y, int comp, void *data) { int pad = (-x*3) & 3; return outfile(filename,-1,-1,x,y,comp,data,0,pad, "11 4 22 4" "4 44 22 444444", 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header } int stbi_write_tga(char const *filename, int x, int y, int comp, void *data) { int has_alpha = !(comp & 1); return outfile(filename, -1,-1, x, y, comp, data, has_alpha, 0, "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha); } // any other image formats that do interleaved rgb data? // PNG: requires adler32,crc32 -- significant amount of code // PSD: no, channels output separately // TIFF: no, stripwise-interleaved... i think #endif // STBI_NO_WRITE // add in my DDS loading support #ifndef STBI_NO_DDS #include "stbi_DDS_aug_c.h" #endif
C
3D
hku-mars/ImMesh
src/shader/tools_my_point_shader.h
.h
12,653
311
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "tools_my_shader_common.h" namespace Common_tools { class Point_cloud_shader { public: Point_cloud_shader() { } ~Point_cloud_shader() { glDeleteVertexArrays( 1, &m_VAO ); glDeleteBuffers( 1, &m_VBO ); } std::shared_ptr< Shader > m_pt_shader=nullptr, m_pt_shader_single_color=nullptr; std::vector< Point_element > m_pts_vector; unsigned int m_VBO, m_VAO; bool m_if_set_pt_buffer = false; unsigned char m_pt_stencil_id = 0xF0; int m_pts_size = 10; double m_pts_alpha = 1.0; int m_edge_size = 0; glm::vec4 m_edge_color = glm::vec4( 1.0, 1.0, 1.0, 1.0 ); int m_rviz_like_cluster_number = 100; int m_point_step = 1; int m_draw_points_number = -1; void find_min_max_of_points(int s_index, int e_index, Point_element & min_pt, Point_element & max_pt) { if ( s_index < 0 ) s_index = 0; if ( e_index > m_pts_vector.size() ) e_index = m_pts_vector.size(); min_pt = m_pts_vector[ s_index ]; max_pt = m_pts_vector[ s_index ]; for ( int i = s_index; i < e_index; i++ ) { for ( int j = 0; j < 3; j++ ) { min_pt.m_pos[ j ] = std::min( min_pt.m_pos[ j ], m_pts_vector[ i ].m_pos[ j ] ); max_pt.m_pos[ j ] = std::max( max_pt.m_pos[ j ], m_pts_vector[ i ].m_pos[ j ] ); } } } void make_rviz_like_color() { // int cluster_number = m_pts_vector.size() / m_rviz_like_cluster_number; int cluster_number = 1e3; for(int cluster_idx = 0; cluster_idx < m_pts_vector.size(); cluster_idx+=cluster_number) { Point_element pt_min, pt_max; int s_index = cluster_idx; int e_index = cluster_idx+ cluster_number; find_min_max_of_points( s_index, e_index, pt_min, pt_max ); float min_value = pt_min.m_pos[2]; float max_value = pt_max.m_pos[2]; float mix_max = (pt_max.m_pos[2] - pt_min.m_pos[2]); for(int pt_idx = s_index; pt_idx < e_index; pt_idx++ ) { float val = (m_pts_vector[pt_idx].m_pos[2] - min_value) / mix_max; tinycolormap::Color c = tinycolormap::GetColor(1.0-val, tinycolormap::ColormapType::Heat); m_pts_vector[pt_idx].pack_color(c.r(), c.g(), c.b()); } } } void init_single_color_shader(const std::string & shader_path ) { std::string vertex_shader_single = std::string( shader_path ).append( "points_shader_rgb.vs" ); std::string fragment_single_color_shader = std::string( shader_path ).append( "points_shader_single_color.fs" ); m_pt_shader_single_color = std::make_shared< Shader >( vertex_shader_single.c_str(), fragment_single_color_shader.c_str() ); m_pt_shader_single_color->use(); m_pt_shader_single_color->setFloat( "pointAlpha", 1.0 ); m_pt_shader_single_color->setFloat( "pointSize", 10.0 ); m_pt_shader_single_color->setVec4("edgeColor", m_edge_color ); } void init( const std::string & shader_path ) { std::string vertex_shader = std::string( shader_path ).append( "points_shader_rgb.vs" ); std::string fragment_shader = std::string( shader_path ).append( "points_shader_rgb.fs" ); m_pt_shader = std::make_shared< Shader >( vertex_shader.c_str(), fragment_shader.c_str() ); m_pt_shader->use(); m_pt_shader->setFloat( "pointAlpha", 1.0 ); m_pt_shader->setFloat( "pointSize", 1 ); } void set_point_attr( int pts_size = 10, int edge_size = 10, double pts_alpha = 1.0 ) { m_pts_size = pts_size; m_edge_size = edge_size; m_pts_alpha = pts_alpha; } void init_data_buffer() { // cout << "=== Init data buffer === " << endl; if(m_if_set_pt_buffer) { glDeleteVertexArrays( 1, &m_VAO ); glDeleteBuffers( 1, &m_VBO ); } m_point_step = std::max(1 , m_point_step); glGenVertexArrays( 1, &m_VAO ); glGenBuffers( 1, &m_VBO ); glBindVertexArray( m_VAO ); glBindBuffer( GL_ARRAY_BUFFER, m_VBO ); int stride = 3 * sizeof( float ) + sizeof( float ); glBufferData( GL_ARRAY_BUFFER, m_pts_vector.size() * ( stride ), m_pts_vector.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) 0 ); glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 1, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) ( 3 * sizeof( float ) ) ); m_if_set_pt_buffer = true; } template < typename T, int option = EIGEN_DATA_TYPE_DEFAULT_OPTION > void set_pointcloud( std::vector< Eigen::Matrix< T, 6, 1, option > >& _pts_color_of_maps, int if_rviz_like_color = 1 ) { m_pts_vector.resize(_pts_color_of_maps.size()); for ( int i = 0; i < _pts_color_of_maps.size(); i++ ) { for ( int j = 0; j < 3; j++ ) { m_pts_vector[ i ].m_pos[j] = _pts_color_of_maps[ i ]( j ); } m_pts_vector[ i ].pack_color( _pts_color_of_maps[ i ]( 3 ), _pts_color_of_maps[ i ]( 4 ), _pts_color_of_maps[ i ]( 5 ) ); } if ( if_rviz_like_color ) { make_rviz_like_color(); } init_data_buffer(); } template < typename T, int option = EIGEN_DATA_TYPE_DEFAULT_OPTION > void set_pointcloud( std::vector< Eigen::Matrix< T, 3, 1, option > >& _pts_color_of_maps, vec_3 pt_color = vec_3( 1.0, 1.0, 1.0 ), bool if_rviz_like_color = false ) { m_pts_vector.resize( _pts_color_of_maps.size() ); for ( int i = 0; i < _pts_color_of_maps.size(); i++ ) { for ( int j = 0; j < 3; j++ ) { m_pts_vector[ i ].m_pos[j] = _pts_color_of_maps[ i ]( j ); } m_pts_vector[ i ].pack_color( pt_color(0), pt_color(1), pt_color(2)); } if ( if_rviz_like_color ) { make_rviz_like_color(); } init_data_buffer(); } template < typename T, int option = EIGEN_DATA_TYPE_DEFAULT_OPTION > void set_pointcloud( std::vector< Eigen::Matrix< T, 4, 1, option > >& _pts_color_of_maps, vec_3 pt_color = vec_3( 1.0, 1.0, 1.0 ), bool if_rviz_like_color = false ) { m_pts_vector.resize( _pts_color_of_maps.size() ); for ( int i = 0; i < _pts_color_of_maps.size(); i++ ) { for ( int j = 0; j < 3; j++ ) { m_pts_vector[ i ].m_pos[j] = _pts_color_of_maps[ i ]( j ); } m_pts_vector[ i ].pack_color( pt_color(0), pt_color(1), pt_color(2)); } if ( if_rviz_like_color ) { make_rviz_like_color(); } init_data_buffer(); } void set_pointcloud( std::vector< eigen_vec_f<3> >& _pts_pos, std::vector< eigen_vec_uc<4> >& _pts_color, bool if_rviz_like_color = false ) { m_pts_vector.resize(_pts_pos.size()); for ( int i = 0; i < _pts_pos.size(); i++ ) { for ( int j = 0; j < 3; j++ ) { m_pts_vector[ i ].m_pos[j] = _pts_pos[ i ]( j ); } m_pts_vector[ i ].pack_color( _pts_color[ i ]( 0 ), _pts_color[ i ]( 1 ), _pts_color[ i ]( 2 ) ); } if ( if_rviz_like_color ) { make_rviz_like_color(); } init_data_buffer(); } void set_pointcloud( std::vector< eigen_vec_f<3> >& _pts_pos, bool if_rviz_like_color = false ) { m_pts_vector.resize(_pts_pos.size()); for ( int i = 0; i < _pts_pos.size(); i++ ) { for ( int j = 0; j < 3; j++ ) { m_pts_vector[ i ].m_pos[j] = _pts_pos[ i ]( j ); } m_pts_vector[ i ].pack_color( 1.0, 1.0, 1.0 ); } if ( if_rviz_like_color ) { make_rviz_like_color(); } init_data_buffer(); } void draw( glm::mat4 proj_mat, glm::mat4 pose_mat, GLenum draw_mode = GL_POINTS ) { Common_tools::Timer tim; tim.tic(); if(m_if_set_pt_buffer == false) { return; } glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_BLEND ); glm::mat4 projection_mul_view = proj_mat * pose_mat; m_pt_shader->use(); m_pt_shader->setFloat( "pointAlpha", m_pts_alpha ); m_pt_shader->setFloat( "pointSize", m_pts_size ); m_pt_shader->setMat4( "projection_mul_view", projection_mul_view ); int draw_count = m_pts_vector.size(); if ( m_draw_points_number >= 0 ) { draw_count = std::min( m_draw_points_number, ( int ) m_pts_vector.size() ); // cout << "Draw count = " << draw_count << " | " << m_pts_vector.size() << endl; } if ( draw_mode == GL_LINES || draw_mode == GL_LINE_STRIP || draw_mode == GL_LINE_LOOP ) { glEnable( GL_LINE_WIDTH ); glLineWidth( m_pts_size ); } else { if(m_pts_size >=0) { glEnable( GL_VERTEX_PROGRAM_POINT_SIZE ); glPointSize( m_pts_size ); } } glBindVertexArray( m_VAO ); glDrawArrays( draw_mode, 0, draw_count / m_point_step ); glDepthFunc( GL_LESS ); // cout << "Shader cost time_3 = " << tim.toc_string() << endl; } void draw( const Eigen::Matrix< double, 4, 4 > proj_mat, const Eigen::Matrix< double, 4, 4 > pose_mat ) { draw( eigen2glm( proj_mat ), Common_tools::eigen2glm( pose_mat ) ); } }; }
Unknown
3D
hku-mars/ImMesh
src/shader/stb_image_aug.h
.h
16,591
355
/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c when you control the images you're loading QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline (no JPEG progressive, no oddball channel decimations) PNG non-interlaced BMP non-1bpp, non-RLE TGA (not sure what subset, if a subset) PSD (composited view only, no extra channels) HDR (radiance rgbE format) writes BMP,TGA (define STBI_NO_WRITE to remove code) decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code) supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD) TODO: stbi_info_* history: 1.16 major bugfix - convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant */ #ifndef HEADER_STB_IMAGE_AUGMENTED #define HEADER_STB_IMAGE_AUGMENTED //// begin header file //////////////////////////////////////////////////// // // Limitations: // - no progressive/interlaced support (jpeg, png) // - 8-bit samples only (jpeg, png) // - not threadsafe // - channel subsampling of at most 2 in each dimension (jpeg) // - no delayed line count (jpeg) -- IJG doesn't support either // // Basic usage (see HDR discussion below): // int x,y,n; // unsigned char *data = stbi_load(filename, &x, &y, &n, 0); // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // stbi_image_free(data) // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *comp -- outputs # of image components in image file // int req_comp -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data. The pixel data consists of *y scanlines of *x pixels, // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. // If req_comp is non-zero, *comp has the number of components that _would_ // have been output otherwise. E.g. if you set req_comp to 4, you will always // get RGBA output, but you can check *comp to easily see if it's opaque. // // An output image with N components has the following components interleaved // in this order in each pixel: // // N=#comp components // 1 grey // 2 grey, alpha // 3 red, green, blue // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, // and *x, *y, *comp will be unchanged. The function stbi_failure_reason() // can be queried for an extremely brief, end-user unfriendly explanation // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG and BMP images are automatically depalettized. // // // =========================================================================== // // HDR image support (disable by defining STBI_NO_HDR) // // stb_image now supports loading HDR images in general, and currently // the Radiance .HDR file format, although the support is provided // generically. You can still load any file through the existing interface; // if you attempt to load an HDR file, it will be automatically remapped to // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); // // (note, do not use _inverse_ constants; stbi_image will invert them // appropriately). // // Additionally, there is a new, parallel interface for loading files as // (linear) floats to preserve the full dynamic range: // // float *data = stbi_loadf(filename, &x, &y, &n, 0); // // If you load LDR images through this interface, those images will // be promoted to floating point values, run through the inverse of // constants corresponding to the above: // // stbi_ldr_to_hdr_scale(1.0f); // stbi_ldr_to_hdr_gamma(2.2f); // // Finally, given a filename (or an open file or memory block--see header // file for details) containing image data, you can query for the "most // appropriate" interface to use (that is, whether the image is HDR or // not), using: // // stbi_is_hdr(char *filename); #ifndef STBI_NO_STDIO #include <stdio.h> #endif #define STBI_VERSION 1 enum { STBI_default = 0, // only used for req_comp STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4, }; typedef unsigned char stbi_uc; #ifdef __cplusplus extern "C" { #endif // WRITING API #if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO) // write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding) // (you must include the appropriate extension in the filename). // returns TRUE on success, FALSE if couldn't open file, error writing file extern int stbi_write_bmp (char const *filename, int x, int y, int comp, void *data); extern int stbi_write_tga (char const *filename, int x, int y, int comp, void *data); #endif // PRIMARY API - works on images of any type // load image by filename, open file, or memory buffer #ifndef STBI_NO_STDIO extern stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); #endif extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); // for stbi_load_from_file, file pointer is left pointing immediately after image #ifndef STBI_NO_HDR #ifndef STBI_NO_STDIO extern float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp); extern float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); #endif extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); extern void stbi_hdr_to_ldr_gamma(float gamma); extern void stbi_hdr_to_ldr_scale(float scale); extern void stbi_ldr_to_hdr_gamma(float gamma); extern void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_HDR // get a VERY brief reason for failure // NOT THREADSAFE extern char *stbi_failure_reason (void); // free the loaded image -- this is just free() extern void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); extern int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); #ifndef STBI_NO_STDIO extern int stbi_info (char const *filename, int *x, int *y, int *comp); extern int stbi_is_hdr (char const *filename); extern int stbi_is_hdr_from_file(FILE *f); #endif // ZLIB client - used by PNG, available for other purposes extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); extern int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); extern int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); // TYPE-SPECIFIC ACCESS // is it a jpeg? extern int stbi_jpeg_test_memory (stbi_uc const *buffer, int len); extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); extern int stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); #ifndef STBI_NO_STDIO extern stbi_uc *stbi_jpeg_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern int stbi_jpeg_test_file (FILE *f); extern stbi_uc *stbi_jpeg_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); extern int stbi_jpeg_info (char const *filename, int *x, int *y, int *comp); extern int stbi_jpeg_info_from_file (FILE *f, int *x, int *y, int *comp); #endif // is it a png? extern int stbi_png_test_memory (stbi_uc const *buffer, int len); extern stbi_uc *stbi_png_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); extern int stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp); #ifndef STBI_NO_STDIO extern stbi_uc *stbi_png_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern int stbi_png_info (char const *filename, int *x, int *y, int *comp); extern int stbi_png_test_file (FILE *f); extern stbi_uc *stbi_png_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); extern int stbi_png_info_from_file (FILE *f, int *x, int *y, int *comp); #endif // is it a bmp? extern int stbi_bmp_test_memory (stbi_uc const *buffer, int len); extern stbi_uc *stbi_bmp_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO extern int stbi_bmp_test_file (FILE *f); extern stbi_uc *stbi_bmp_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); #endif // is it a tga? extern int stbi_tga_test_memory (stbi_uc const *buffer, int len); extern stbi_uc *stbi_tga_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO extern int stbi_tga_test_file (FILE *f); extern stbi_uc *stbi_tga_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); #endif // is it a psd? extern int stbi_psd_test_memory (stbi_uc const *buffer, int len); extern stbi_uc *stbi_psd_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO extern int stbi_psd_test_file (FILE *f); extern stbi_uc *stbi_psd_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); #endif // is it an hdr? extern int stbi_hdr_test_memory (stbi_uc const *buffer, int len); extern float * stbi_hdr_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern float * stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); extern stbi_uc *stbi_hdr_load_rgbe (char const *filename, int *x, int *y, int *comp, int req_comp); extern float * stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO extern int stbi_hdr_test_file (FILE *f); extern float * stbi_hdr_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); extern stbi_uc *stbi_hdr_load_rgbe_file (FILE *f, int *x, int *y, int *comp, int req_comp); #endif // define new loaders typedef struct { int (*test_memory)(stbi_uc const *buffer, int len); stbi_uc * (*load_from_memory)(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO int (*test_file)(FILE *f); stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp); #endif } stbi_loader; // register a loader by filling out the above structure (you must defined ALL functions) // returns 1 if added or already added, 0 if not added (too many loaders) // NOT THREADSAFE extern int stbi_register_loader(stbi_loader *loader); // define faster low-level operations (typically SIMD support) #if STBI_SIMD typedef void (*stbi_idct_8x8)(uint8 *out, int out_stride, short data[64], unsigned short *dequantize); // compute an integer IDCT on "input" // input[x] = data[x] * dequantize[x] // write results to 'out': 64 samples, each run of 8 spaced by 'out_stride' // CLAMP results to 0..255 typedef void (*stbi_YCbCr_to_RGB_run)(uint8 *output, uint8 const *y, uint8 const *cb, uint8 const *cr, int count, int step); // compute a conversion from YCbCr to RGB // 'count' pixels // write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B // y: Y input channel // cb: Cb input channel; scale/biased to be 0..255 // cr: Cr input channel; scale/biased to be 0..255 extern void stbi_install_idct(stbi_idct_8x8 func); extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func); #endif // STBI_SIMD #ifdef __cplusplus } #endif // // //// end header file ///////////////////////////////////////////////////// #endif // STBI_INCLUDE_STB_IMAGE_H
Unknown
3D
hku-mars/ImMesh
src/shader/tools_my_dbg_utility.h
.h
9,600
244
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "tools_my_shader_common.h" namespace Common_tools { class Axis_shader { public: Axis_shader() { } ~Axis_shader() { if ( m_if_set_pt_buffer ) { glDeleteVertexArrays( 1, &m_VAO ); glDeleteBuffers( 1, &m_VBO ); } } std::shared_ptr< Shader > m_pt_shader; std::vector< Point_element > m_pts_vector; unsigned int m_VBO, m_VAO; bool m_if_set_pt_buffer = false; unsigned char m_pt_stencil_id = 0xF0; int m_pts_size = 10; int m_point_step = 1; void init_pts( float axis_scale = 10 ) { m_pts_vector.clear(); m_pts_vector.push_back( Point_element( 0, 0, 0, 1.0, 0.0, 0.0 ) ); m_pts_vector.push_back( Point_element( axis_scale, 0, 0, 1.0, 0.0, 0.0 ) ); m_pts_vector.push_back( Point_element( 0, 0, 0, 0.0, 1.0, 0.0 ) ); m_pts_vector.push_back( Point_element( 0, axis_scale, 0, 0.0, 1.0, 0.0 ) ); m_pts_vector.push_back( Point_element( 0, 0, 0, 0.0, 0.0, 1.0 ) ); m_pts_vector.push_back( Point_element( 0, 0, axis_scale, 0.0, 0.0, 1.0 ) ); init_data_buffer(); } void init( std::string shader_path, float axis_scale = 10 ) { std::string vertex_shader = std::string( shader_path ).append( "/points_shader_rgb.vs" ); std::string fragment_shader = std::string( shader_path ).append( "/points_shader_rgb.fs" ); m_pt_shader = std::make_shared< Shader >( vertex_shader.c_str(), fragment_shader.c_str() ); init_pts( axis_scale ); } void init_data_buffer() { // cout << "=== Init data buffer === " << endl; if ( m_if_set_pt_buffer ) { glDeleteVertexArrays( 1, &m_VAO ); glDeleteBuffers( 1, &m_VBO ); } m_if_set_pt_buffer = true; m_point_step = std::max( 1, m_point_step ); glGenVertexArrays( 1, &m_VAO ); glGenBuffers( 1, &m_VBO ); glBindVertexArray( m_VAO ); glBindBuffer( GL_ARRAY_BUFFER, m_VBO ); int stride = 3 * sizeof( float ) + sizeof( float ); glBufferData( GL_ARRAY_BUFFER, m_pts_vector.size() * ( stride ), m_pts_vector.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) 0 ); glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 1, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) ( 3 * sizeof( float ) ) ); } void draw( glm::mat4 proj_mat, glm::mat4 pose_mat ) { // printf_line; Common_tools::Timer tim; tim.tic(); glm::mat4 projection_mul_view = proj_mat * pose_mat; // activate shader // glDepthFunc( GL_ALWAYS ); m_pt_shader->use(); m_pt_shader->setFloat( "pointAlpha", 1.0 ); m_pt_shader->setFloat( "pointSize", 1 ); m_pt_shader->setMat4( "projection_mul_view", projection_mul_view ); glEnable( GL_LINE_WIDTH ); glLineWidth( m_pts_size ); glBindVertexArray( m_VAO ); glDrawArrays( GL_LINES, 0, m_pts_vector.size() ); // glDepthFunc( GL_LESS ); } void draw( const Eigen::Matrix< double, 4, 4 > proj_mat, const Eigen::Matrix< double, 4, 4 > pose_mat ) { draw( eigen2glm( proj_mat ), Common_tools::eigen2glm( pose_mat ) ); } }; class Ground_plane_shader { public: Ground_plane_shader() { } ~Ground_plane_shader() { if ( m_if_set_pt_buffer ) { glDeleteVertexArrays( 1, &m_VAO ); glDeleteBuffers( 1, &m_VBO ); } } std::shared_ptr< Shader > m_pt_shader; std::vector< Point_element > m_pts_vector; unsigned int m_VBO, m_VAO; bool m_if_set_pt_buffer = false; unsigned char m_pt_stencil_id = 0xF0; int m_pts_size = 1; int m_point_step = 1; void init_pts( float grid_scale = 10, int cell_count = 5 ) { m_pts_vector.clear(); vec_3 color = vec_3( 0.45, 0.45, 0.45 ); for ( int i = -cell_count; i <= cell_count; i++ ) { m_pts_vector.push_back( Point_element( i * grid_scale, -cell_count * grid_scale, 0, color( 0 ), color( 1 ), color( 2 ) ) ); m_pts_vector.push_back( Point_element( i * grid_scale, cell_count * grid_scale, 0, color( 0 ), color( 1 ), color( 2 ) ) ); m_pts_vector.push_back( Point_element( -cell_count * grid_scale, i * grid_scale, 0, color( 0 ), color( 1 ), color( 2 ) ) ); m_pts_vector.push_back( Point_element( cell_count * grid_scale, i * grid_scale, 0, color( 0 ), color( 1 ), color( 2 ) ) ); } init_data_buffer(); } void init( std::string shader_path, float axis_scale = 1 , float grid_count = 5 ) { std::string vertex_shader = std::string( shader_path ).append( "/points_shader_rgb.vs" ); std::string fragment_shader = std::string( shader_path ).append( "/points_shader_rgb.fs" ); m_pt_shader = std::make_shared< Shader >( vertex_shader.c_str(), fragment_shader.c_str() ); init_pts( axis_scale, grid_count); } void init_data_buffer() { // cout << "=== Init data buffer === " << endl; if ( m_if_set_pt_buffer ) { glDeleteVertexArrays( 1, &m_VAO ); glDeleteBuffers( 1, &m_VBO ); } m_if_set_pt_buffer = true; m_point_step = std::max( 1, m_point_step ); glGenVertexArrays( 1, &m_VAO ); glGenBuffers( 1, &m_VBO ); glBindVertexArray( m_VAO ); glBindBuffer( GL_ARRAY_BUFFER, m_VBO ); int stride = 3 * sizeof( float ) + sizeof( float ); glBufferData( GL_ARRAY_BUFFER, m_pts_vector.size() * ( stride ), m_pts_vector.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) 0 ); glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 1, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) ( 3 * sizeof( float ) ) ); } void draw( glm::mat4 proj_mat, glm::mat4 pose_mat ) { Common_tools::Timer tim; tim.tic(); glm::mat4 projection_mul_view = proj_mat * pose_mat; m_pt_shader->use(); m_pt_shader->setFloat( "pointAlpha", 1.0 ); m_pt_shader->setFloat( "pointSize", 1 ); m_pt_shader->setMat4( "projection_mul_view", projection_mul_view ); glEnable( GL_LINE_WIDTH ); glLineWidth( m_pts_size ); glBindVertexArray( m_VAO ); glDrawArrays( GL_LINES, 0, m_pts_vector.size() ); // glDepthFunc( GL_LESS ); } void draw( const Eigen::Matrix< double, 4, 4 > proj_mat, const Eigen::Matrix< double, 4, 4 > pose_mat ) { draw( eigen2glm( proj_mat ), Common_tools::eigen2glm( pose_mat ) ); } }; } // namespace Common_tools
Unknown
3D
hku-mars/ImMesh
src/shader/tools_my_camera_pose_shader.h
.h
12,108
264
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "tools_my_shader_common.h" namespace Common_tools { class Camera_pose_shader { public: Camera_pose_shader() { } ~Camera_pose_shader() { glDeleteVertexArrays( 1, &m_frame_vao ); glDeleteBuffers( 1, &m_frame_vbo ); glDeleteVertexArrays( 1, &m_image_vao ); glDeleteBuffers( 2, m_image_vbo ); } std::shared_ptr< Shader > m_pt_shader, m_image_shader; std::vector< Point_element > m_pts_vector; unsigned int m_frame_vbo, m_frame_vao; unsigned int m_image_vbo[2], m_image_vao; bool m_if_set_pt_buffer = false; unsigned char pt_stencil_id = 0xF0; int m_pts_size = 20; double m_draw_alpha = 1.0; int m_edge_size = 50; int if_draw_edge = true; glm::vec4 m_edge_color = glm::vec4( 1.0, 1.0, 1.0, 1.0 ); int m_rviz_like_cluster_number = 100; int m_point_step = 1; glm::vec3 m_draw_color = glm::vec3( 1.0, 1.0, 1.0 ); std::vector< vec_3f > init_camera_frustum_vertex( Eigen::Matrix3f cam_K, int w, int h, float scale ) { std::vector< vec_3f > vertex_vec; Eigen::Matrix3f Kinv = cam_K.inverse(); float u0 = Kinv( 0, 2 ); float v0 = Kinv( 1, 2 ); float fu = Kinv( 0, 0 ); float fv = Kinv( 1, 1 ); const float xl = scale * u0; const float xh = scale * ( w * fu + u0 ); const float yl = scale * v0; const float yh = scale * ( h * fv + v0 ); vertex_vec.push_back( vec_3f( xl, yl, scale ) ); vertex_vec.push_back( vec_3f( xh, yl, scale ) ); vertex_vec.push_back( vec_3f( xh, yh, scale ) ); vertex_vec.push_back( vec_3f( xl, yh, scale ) ); vertex_vec.push_back( vec_3f( xl, yl, scale ) ); vertex_vec.push_back( vec_3f( 0, 0, 0 ) ); vertex_vec.push_back( vec_3f( xh, yl, scale ) ); vertex_vec.push_back( vec_3f( 0, 0, 0 ) ); vertex_vec.push_back( vec_3f( xl, yh, scale ) ); vertex_vec.push_back( vec_3f( 0, 0, 0 ) ); vertex_vec.push_back( vec_3f( xh, yh, scale ) ); return vertex_vec; } std::vector< vec_3f > cam_frustum_vertex_vec; std::vector< vec_2f > tex_cor_vec; std::vector< vec_3f > texture_pts_vec; float draw_camera_size = 1.0; void init_vertices() { Eigen::Matrix3f cam_K; Eigen::Matrix3d lidar_frame_to_camera_frame; // For R3LIVE camera // cam_K << 863.4241, 0.0, 640.6808, 0.0, 863.4171, 518.3392, 0.0, 0.0, 1.0; // Eigen::Matrix3f K = cam_K.cast< float >(); // cam_frustum_vertex_vec = init_camera_frustum_vertex( cam_K, 1280, 1024, 1.5 * draw_camera_size ); // For oxford data cam_K << 704.504153913163, 0.0, 708.8501128392297, 0.0, 703.6790228113778, 562.7041625276061, 0.0, 0.0, 1.0 ; Eigen::Matrix3f K = cam_K.cast< float >(); cam_frustum_vertex_vec = init_camera_frustum_vertex( cam_K, 1440, 1080, 1.5 * draw_camera_size ); // =========== texture_pts_vec.push_back( cam_frustum_vertex_vec[ 0 ] ); texture_pts_vec.push_back( cam_frustum_vertex_vec[ 1 ] ); texture_pts_vec.push_back( cam_frustum_vertex_vec[ 2 ] ); texture_pts_vec.push_back( cam_frustum_vertex_vec[ 3 ] ); tex_cor_vec.push_back( vec_2f( 0, 0 ) ); tex_cor_vec.push_back( vec_2f( 1, 0 ) ); tex_cor_vec.push_back( vec_2f( 1, 1 ) ); tex_cor_vec.push_back( vec_2f( 0, 1 ) ); // cout << ANSI_COLOR_GREEN << "init_vertices finish!!!" << cam_K << ANSI_COLOR_RESET << endl; } void init( std::string shader_path ) { std::string vertex_shader = std::string( shader_path ).append( "/points_shader.vs" ); std::string fragment_shader = std::string( shader_path ).append( "/points_shader.fs" ); m_pt_shader = std::make_shared< Shader >( vertex_shader.c_str(), fragment_shader.c_str() ); m_pt_shader->use(); m_pt_shader->setFloat( "pointAlpha", 1.0 ); m_pt_shader->setFloat( "pointSize", 10 ); m_pt_shader->setVec3( "pointColor", glm::vec3( 1.0, 1.0, 1.0 ) ); m_image_shader = std::make_shared< Shader >( std::string( shader_path ).append( "/image_shader.vs" ).c_str(), std::string( shader_path ).append( "/image_shader.fs" ).c_str() ); init_vertices(); init_data_buffer(); } void set_point_attr( int wireframe_size = 10, int edge_size = 10, double pts_alpha = 1.0 ) { m_pts_size = wireframe_size; m_edge_size = edge_size; m_draw_alpha = pts_alpha; } void init_data_buffer() { // cout << "=== Init data buffer === " << endl; if(m_if_set_pt_buffer) { glDeleteVertexArrays( 1, &m_frame_vao ); glDeleteBuffers( 1, &m_frame_vbo ); } m_point_step = std::max(1 , m_point_step); // Init frame vao and vbo glGenVertexArrays( 1, &m_frame_vao ); glGenBuffers( 1, &m_frame_vbo ); glBindVertexArray( m_frame_vao ); glBindBuffer( GL_ARRAY_BUFFER, m_frame_vbo ); int stride = 3 * sizeof( float ); glBufferData( GL_ARRAY_BUFFER, cam_frustum_vertex_vec.size() * ( stride ), cam_frustum_vertex_vec.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) 0 ); // Init image vao and vbo glGenVertexArrays( 1, &m_image_vao ); glGenBuffers( 2, m_image_vbo ); glBindVertexArray( m_image_vao ); glBindBuffer( GL_ARRAY_BUFFER, m_image_vbo[0] ); stride = 3 * sizeof( float ); glBufferData( GL_ARRAY_BUFFER, texture_pts_vec.size() * ( stride ), texture_pts_vec.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) 0 ); glBindBuffer( GL_ARRAY_BUFFER, m_image_vbo[1] ); stride = 2 * sizeof( float ); glBufferData( GL_ARRAY_BUFFER, tex_cor_vec.size() * ( stride ), tex_cor_vec.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, stride * m_point_step, ( void* ) 0 ); m_if_set_pt_buffer = true; } Eigen::Quaterniond m_pose_q; vec_3 m_pose_t; double m_scale; Eigen::Matrix4d pose_inv_d = Eigen::Matrix4d::Identity(); void set_camera_pose_and_scale( Eigen::Quaterniond pose_q, vec_3 pose_t, double scale ) { m_pose_q = pose_q; m_pose_t = pose_t; m_scale = scale; Eigen::Matrix4f pose = Eigen::Matrix4f::Identity(); pose.block( 0, 0, 3, 3 ) = ( pose_q.toRotationMatrix() ).cast< float >(); pose.block( 0, 3, 3, 1 ) = pose_t.cast< float >(); pose_inv_d = pose.inverse().cast<double>(); pose_inv_d.block( 0, 0, 3, 3 ) *= scale; } void draw( glm::mat4 proj_mat, glm::mat4 pose_mat, int texture_id = -1 ) { // printf_line; GLenum draw_mode = GL_LINE_STRIP; Common_tools::Timer tim; tim.tic(); // pts_vector[0].debug(); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_BLEND ); // 1st. render pass, draw objects as normal, writing to the stencil buffer // -------------------------------------------------------------------- glStencilFunc( GL_ALWAYS, pt_stencil_id, 0xFF ); glStencilMask( pt_stencil_id ); glm::mat4 projection_mul_view = proj_mat * pose_mat * eigen2glm<double>(pose_inv_d); glActiveTexture( GL_TEXTURE0 ); if ( texture_id >= 0 ) { glBindTexture( GL_TEXTURE_2D, texture_id ); glBindVertexArray( m_image_vao ); m_image_shader->use(); m_image_shader->setMat4( "projection_mul_view", projection_mul_view ); m_image_shader->setInt( "TexID", 0 ); // glLineWidth( m_pts_size + 3 ); // cout << "Number of pts = " << cam_frustum_vertex_vec.size() << "" << endl; glDrawArrays( GL_QUADS, 0, 4 ); // printf("Draw[%d], ", texture_id); // fflush(stdout); } // activate shader // glDepthFunc( GL_LESS ); m_pt_shader->use(); m_pt_shader->setVec3( "pointColor", m_draw_color ); m_pt_shader->setFloat( "pointAlpha", m_draw_alpha ); m_pt_shader->setFloat( "pointSize", m_pts_size ); m_pt_shader->setMat4( "projection_mul_view", projection_mul_view ); if ( draw_mode == GL_LINES || draw_mode == GL_LINE_STRIP || draw_mode == GL_LINE_LOOP) { glEnable(GL_LINE_WIDTH); glLineWidth( m_pts_size ); } glBindVertexArray( m_frame_vao ); // cout << "Number of pts = " << cam_frustum_vertex_vec.size() << "" << endl; glDrawArrays( draw_mode, 0, cam_frustum_vertex_vec.size() / m_point_step ); } void draw( const Eigen::Matrix< double, 4, 4 > proj_mat, const Eigen::Matrix< double, 4, 4 > pose_mat ) { draw( eigen2glm( proj_mat ), Common_tools::eigen2glm( pose_mat ) ); } }; };
Unknown
3D
hku-mars/ImMesh
src/shader/tools_my_texture_triangle_shader.h
.h
9,093
218
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #define HAVE_OPENCV 1 #include "tools_my_shader_common.h" #include <glm/glm.hpp> namespace Common_tools { class Triangle_facet_shader // class Point_cloud_shader { public: Triangle_facet_shader() { } ~Triangle_facet_shader() { glDeleteVertexArrays( 1, &m_vao ); glDeleteBuffers( 3, m_vbo ); } std::shared_ptr< Shader > m_shader_facet; std::vector< vec_3f > m_pts_pos_vector; std::vector< vec_3f > m_pts_normal_vector; std::vector< float > m_pts_color_vector; bool m_if_draw_face = true; unsigned int m_vbo[ 3 ], m_vao; unsigned char m_pt_stencil_id = 0xF0; int m_line_width = 1; double m_pts_alpha = 1; int m_edge_size = 0; int m_if_draw_edge = true; int m_rviz_like_cluster_number = 100; void init( std::string shader_path ) { std::string vertex_shader = std::string( shader_path ).append( "triangle_facets.vs" ); std::string fragment_shader = std::string( shader_path ).append( "triangle_facets.fs" ); m_shader_facet = std::make_shared< Shader >( vertex_shader.c_str(), fragment_shader.c_str() ); } void set_point_attr( int pts_size = 10, int edge_size = 10, double pts_alpha = 1.0 ) { m_edge_size = edge_size; m_line_width = pts_size; m_pts_alpha = pts_alpha; } // template < typename T > // void set_pointcloud( std::vector< Eigen::Matrix< float, 6, 1 > >& _pts_color_of_maps ) int if_have_init_data_buffer = false; void init_data_buffer() { if ( if_have_init_data_buffer ) { } else { glGenVertexArrays( 1, &m_vao ); // glGenBuffers( 2, m_vbo ); glGenBuffers( 3, m_vbo ); } glBindVertexArray( m_vao ); int stride = 3 * sizeof( float ); glBindBuffer( GL_ARRAY_BUFFER, m_vbo[ 0 ] ); glBufferData( GL_ARRAY_BUFFER, m_pts_pos_vector.size() * ( stride ), m_pts_pos_vector.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, stride, ( void* ) 0 ); glBindBuffer( GL_ARRAY_BUFFER, m_vbo[ 1 ] ); glBufferData( GL_ARRAY_BUFFER, m_pts_normal_vector.size() * ( stride ), m_pts_normal_vector.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, stride, ( void* ) 0 ); stride = sizeof( float ); glBindBuffer( GL_ARRAY_BUFFER, m_vbo[ 2 ] ); glBufferData( GL_ARRAY_BUFFER, m_pts_color_vector.size() * ( stride ), m_pts_color_vector.data(), GL_STATIC_DRAW ); glEnableVertexAttribArray( 2 ); glVertexAttribPointer( 2, 1, GL_FLOAT, GL_FALSE, stride, ( void* ) 0 ); if_have_init_data_buffer = true; } void set_color_by_axis(vec_3f * axis_min_max = nullptr, int select_axis = 2) { if ( axis_min_max != nullptr ) { m_pts_color_vector.resize( m_pts_pos_vector.size() ); for ( int i = 0; i < m_pts_pos_vector.size(); i++ ) { float val_min = axis_min_max[ 0 ][ select_axis ]; float val_max = axis_min_max[ 1 ][ select_axis ]; float val = (m_pts_pos_vector[ i ][ select_axis ] - val_min) / (val_max - val_min); tinycolormap::Color color = tinycolormap::GetColor( 1.0 - val, tinycolormap::ColormapType::Heat ); unsigned char r = ( unsigned char ) ( color.r() * 255 ); unsigned char g = ( unsigned char ) ( color.g() * 255 ); unsigned char b = ( unsigned char ) ( color.b() * 255 ); m_pts_color_vector[i] = ( r << 16 ) | ( g << 8 ) | b; } } } void set_pointcloud( std::vector< eigen_vec_f<3> >& _pts_pos, vec_3f * axis_min_max = nullptr, int select_axis = 2) { m_pts_pos_vector.resize(_pts_pos.size()); m_pts_normal_vector.resize(_pts_pos.size()); m_pts_color_vector.resize( _pts_pos.size() ); for ( int i = 0; i < _pts_pos.size(); i+=3 ) { vec_3f normal = ( _pts_pos[ i + 1 ] - _pts_pos[ i ] ).cross( _pts_pos[ i + 2 ] - _pts_pos[ i ] ); for ( int j = 0; j < 3; j++ ) { m_pts_pos_vector[ i + j ] = _pts_pos[ i + j ]; m_pts_normal_vector[ i + j ] = normal; if(axis_min_max == nullptr) m_pts_color_vector[ i + j ] = ( 255 << 16 ) | ( 255 << 8 ) | 255; } } set_color_by_axis(axis_min_max, select_axis); init_data_buffer(); } void draw( glm::mat4 proj_mat, glm::mat4 pose_mat ) { Common_tools::Timer tim; tim.tic(); // pts_vector[0].debug(); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_BLEND ); glm::mat4 projection_mul_view = proj_mat * pose_mat; glDepthFunc( GL_LESS ); glLineWidth(m_line_width); glm::mat4 pose_mat_inv = glm::inverse(pose_mat); glm::vec3 lightPos(pose_mat_inv[3][0], pose_mat_inv[3][1], pose_mat_inv[3][2]); m_shader_facet->use(); m_shader_facet->setVec3("lightColor", 1.0f, 1.0f, 1.0f); m_shader_facet->setVec3("lightPos", lightPos); m_shader_facet->setMat4( "projection", proj_mat ); m_shader_facet->setMat4( "view", pose_mat ); // m_shader->setFloat( "pointAlpha", m_pts_alpha ); // m_shader->setFloat( "pointSize", m_line_width ); // m_shader->setMat4( "projection_mul_view", projection_mul_view ); // cout << "================================" << endl; // render boxes glBindVertexArray( m_vao ); if(m_if_draw_face) { m_shader_facet->setBool("if_light", true); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } else { m_shader_facet->setBool("if_light", false); glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); } glDrawArrays( GL_TRIANGLES, 0, m_pts_pos_vector.size() ); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glDepthFunc( GL_LESS ); } void draw( const Eigen::Matrix< double, 4, 4 > proj_mat, const Eigen::Matrix< double, 4, 4 > pose_mat ) { draw( eigen2glm( proj_mat ), Common_tools::eigen2glm( pose_mat ) ); } }; } // namespace Common_tools
Unknown
3D
hku-mars/ImMesh
src/shader/tools_my_shader_common.h
.h
9,106
252
/* This code is the implementation of our paper "ImMesh: An Immediate LiDAR Localization and Meshing Framework". The source code of this package is released under GPLv2 license. We only allow it free for personal and academic usage. If you use any code of this repo in your academic research, please cite at least one of our papers: [1] Lin, Jiarong, et al. "Immesh: An immediate lidar localization and meshing framework." IEEE Transactions on Robotics (T-RO 2023) [2] Yuan, Chongjian, et al. "Efficient and probabilistic adaptive voxel mapping for accurate online lidar odometry." IEEE Robotics and Automation Letters (RA-L 2022) [3] Lin, Jiarong, and Fu Zhang. "R3LIVE: A Robust, Real-time, RGB-colored, LiDAR-Inertial-Visual tightly-coupled state Estimation and mapping package." IEEE International Conference on Robotics and Automation (ICRA 2022) For commercial use, please contact me <ziv.lin.ljr@gmail.com> and Dr. Fu Zhang <fuzhang@hku.hk> to negotiate a different license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __TOOOLS_MY_SHADER_COMMON_H__ #define __TOOOLS_MY_SHADER_COMMON_H__ #include "shader_m.h" #include <glad/glad.h> #include <GLFW/glfw3.h> #include "stb_image.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "learnopengl/filesystem.h" #include "learnopengl/shader_m.h" #include "learnopengl/camera.h" #include "learnopengl/model.h" #include "shader_m.h" #include "tools/tools_eigen.hpp" #include "tools/tools_timer.hpp" #include "tools/tools_logger.hpp" #include "tools/tools_color_printf.hpp" #include "tools/tinycolormap.hpp" #define HAVE_OPENCV 1 #if HAVE_OPENCV #include "opencv2/opencv.hpp" #endif namespace Common_tools { #if HAVE_OPENCV inline cv::Mat get_stencil_buffer( float scaled = 0.5, std::string window_name = std::string( "" ) ) { // Visualize stencil buffer const GLFWvidmode* vidmode = glfwGetVideoMode( glfwGetPrimaryMonitor() ); int win_w = vidmode->width; int win_h = vidmode->height; cout << "Window size = " << win_w << " x " << win_h << endl; cv::Mat stencilImage = cv::Mat::zeros( win_h, win_w, CV_8UC1 ); glReadPixels( 0, 0, win_w, win_h, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilImage.data ); // glReadPixels( 0, 0, win_w, win_h, GL_STENCIL_VALUE_MASK, GL_UNSIGNED_BYTE, stencilImage.data ); stencilImage = stencilImage; cv::Mat stencilImage_resize; if ( scaled != 1.0 ) { cv::resize( stencilImage, stencilImage_resize, cv::Size( 0, 0 ), scaled, scaled ); } else { stencilImage_resize = stencilImage; } if ( window_name.length() > 1 ) { cv::imshow( window_name, stencilImage_resize ); cv::waitKey( 1 ); } return stencilImage_resize; } #endif template < typename T > inline glm::mat4 eigen2glm( const Eigen::Matrix< T, 4, 4 >& eigen_mat ) { glm::mat4 temp_mat; for ( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 4; j++ ) { temp_mat[ i ][ j ] = eigen_mat( j, i ); } } return temp_mat; } inline unsigned int loadTexture( char const* path ) { unsigned int textureID; glGenTextures( 1, &textureID ); int width, height, nrComponents; unsigned char* data = stbi_load( path, &width, &height, &nrComponents, 0 ); if ( data ) { GLenum format; if ( nrComponents == 1 ) format = GL_RED; else if ( nrComponents == 3 ) format = GL_RGB; else if ( nrComponents == 4 ) format = GL_RGBA; glBindTexture( GL_TEXTURE_2D, textureID ); glTexImage2D( GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data ); glGenerateMipmap( GL_TEXTURE_2D ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); stbi_image_free( data ); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free( data ); } return textureID; } // loads a cubemap texture from 6 individual texture faces // order: // +X (right) // -X (left) // +Y (top) // -Y (bottom) // +Z (front) // -Z (back) // ------------------------------------------------------- inline unsigned int loadCubemap( vector< std::string > faces ) { unsigned int textureID; glGenTextures( 1, &textureID ); glBindTexture( GL_TEXTURE_CUBE_MAP, textureID ); int width, height, nrChannels; for ( unsigned int i = 0; i < faces.size(); i++ ) { unsigned char* data = stbi_load( faces[ i ].c_str(), &width, &height, &nrChannels, 0 ); if ( data ) { glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); stbi_image_free( data ); } else { std::cout << "Cubemap texture failed to load at path: " << faces[ i ] << std::endl; stbi_image_free( data ); } } glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE ); return textureID; } struct Point_element { float m_pos[ 3 ]; float m_color = 0x000000FF; Point_element() = default; void pack_color(const unsigned char r, const unsigned char g, const unsigned char b) { m_color = (r << 16) | (g << 8) | b; } void pack_color(const float rf, const float gf, const float bf) { unsigned char r = (unsigned char)(rf * 255); unsigned char g = (unsigned char)(gf * 255); unsigned char b = (unsigned char)(bf * 255); m_color = (r << 16) | (g << 8) | b; } void pack_color(const double rf, const double gf, const double bf) { unsigned char r = (unsigned char)(rf * 255); unsigned char g = (unsigned char)(gf * 255); unsigned char b = (unsigned char)(bf * 255); m_color = (r << 16) | (g << 8) | b; } Point_element( const float& x, const float& y, const float& z, const float& rf, const float& gf, const float& bf ) { m_pos[ 0 ] = x; m_pos[ 1 ] = y; m_pos[ 2 ] = z; pack_color( ( float ) rf, ( float ) gf, ( float ) bf ); } Point_element( const float& x, const float& y, const float& z, const double& rf, const double& gf, const double& bf ) { m_pos[ 0 ] = x; m_pos[ 1 ] = y; m_pos[ 2 ] = z; pack_color( ( float ) rf, ( float ) gf, ( float ) bf ); } Point_element( const float& x, const float& y, const float& z, const unsigned char& r, const unsigned char& g, const unsigned char& b ) { m_pos[ 0 ] = x; m_pos[ 1 ] = y; m_pos[ 2 ] = z; pack_color( r, g, b ); } void debug() { int m_color_cast_int = int(m_color); vec_3 fragColor = vec_3( (m_color_cast_int >> 16) & 0xFF, (m_color_cast_int >> 8) & 0xFF, m_color_cast_int & 0xFF) / 255.0; printf("Bit = %x, ", m_color_cast_int); cout <<"Frag_color = " << fragColor.transpose() << endl; } }; } // namespace Common_tools #endif
Unknown
3D
hku-mars/ImMesh
src/shader/shader_m.h
.h
7,770
199
#ifndef SHADER_H #define SHADER_H #include "glad.h" #include <glm/glm.hpp> #include <Eigen/Eigen> #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: unsigned int ID; // constructor generates the shader on the fly // ------------------------------------------------------------------------ Shader(const char* vertexPath, const char* fragmentPath, int if_silence = true) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (std::ifstream::failure& e) { std::cout << ANSI_COLOR_RED_BOLD << "Load: " << std::string(vertexPath) << " Fail!!!"; std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ: " << e.what() << ANSI_COLOR_RESET << std::endl; while(1); } const char* vShaderCode = vertexCode.c_str(); const char * fShaderCode = fragmentCode.c_str(); // 2. compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessery glDeleteShader(vertex); glDeleteShader(fragment); if ( !if_silence ) { std::cout << "== Loading shader from " << vertexPath << " and " << fragmentPath << " done." << std::endl; } } // Bug here, I don't know why // Shader(const std::string vertexPath, const std::string fragmentPath) // { // Shader( vertexPath.c_str(), fragmentPath.c_str() ); // } // activate the shader // ------------------------------------------------------------------------ void use() const { glUseProgram(ID); } // utility uniform functions // ------------------------------------------------------------------------ void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } // ------------------------------------------------------------------------ void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } // ------------------------------------------------------------------------ void setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } // ------------------------------------------------------------------------ void setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec4(const std::string &name, float x, float y, float z, float w) const { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } // ------------------------------------------------------------------------ void setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } template < typename T > static inline glm::mat4 eigen2glm( const Eigen::Matrix< T, 4, 4 >& eigen_mat ) { glm::mat4 temp_mat; for ( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 4; j++ ) { temp_mat[ i ][ j ] = eigen_mat( j, i ); } } return temp_mat; } void setMat4(const std::string &name, const Eigen::Matrix< double, 4, 4 > & eigen_mat) const { glm::mat4 temp_mat = eigen2glm<double>(eigen_mat); glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &temp_mat[0][0]); } private: // utility function for checking shader compilation/linking errors. // ------------------------------------------------------------------------ void checkCompileErrors(GLuint shader, std::string type) { GLint success; GLchar infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); scope_color(ANSI_COLOR_RED_BOLD); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; while(1); } } } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/shader_s.h
.h
4,566
123
#ifndef SHADER_H #define SHADER_H // #include <glad/glad.h> #include "../r4live_dev/openGL/glad.h" #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: unsigned int ID; // constructor generates the shader on the fly // ------------------------------------------------------------------------ Shader(const char* vertexPath, const char* fragmentPath) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (std::ifstream::failure& e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ: " << e.what() << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char * fShaderCode = fragmentCode.c_str(); // 2. compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessary glDeleteShader(vertex); glDeleteShader(fragment); } // activate the shader // ------------------------------------------------------------------------ void use() { glUseProgram(ID); } // utility uniform functions // ------------------------------------------------------------------------ void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } // ------------------------------------------------------------------------ void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } private: // utility function for checking shader compilation/linking errors. // ------------------------------------------------------------------------ void checkCompileErrors(unsigned int shader, std::string type) { int success; char infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/mesh.h
.h
5,038
147
#ifndef MESH_H #define MESH_H #include <glad/glad.h> // holds all OpenGL type declarations #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "./shader.h" #include <string> #include <vector> using namespace std; #define MAX_BONE_INFLUENCE 4 struct Vertex { // position glm::vec3 Position; // normal glm::vec3 Normal; // texCoords glm::vec2 TexCoords; // tangent glm::vec3 Tangent; // bitangent glm::vec3 Bitangent; //bone indexes which will influence this vertex int m_BoneIDs[MAX_BONE_INFLUENCE]; //weights from each bone float m_Weights[MAX_BONE_INFLUENCE]; }; struct Texture { unsigned int id; string type; string path; }; class Mesh { public: // mesh Data vector<Vertex> vertices; vector<unsigned int> indices; vector<Texture> textures; unsigned int VAO; // constructor Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<Texture> textures) { this->vertices = vertices; this->indices = indices; this->textures = textures; // now that we have all the required data, set the vertex buffers and its attribute pointers. setupMesh(); } // render the mesh void Draw(Shader &shader) { // bind appropriate textures unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; for(unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding // retrieve texture number (the N in diffuse_textureN) string number; string name = textures[i].type; if(name == "texture_diffuse") number = std::to_string(diffuseNr++); else if(name == "texture_specular") number = std::to_string(specularNr++); // transfer unsigned int to string else if(name == "texture_normal") number = std::to_string(normalNr++); // transfer unsigned int to string else if(name == "texture_height") number = std::to_string(heightNr++); // transfer unsigned int to string // now set the sampler to the correct texture unit glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i); // and finally bind the texture glBindTexture(GL_TEXTURE_2D, textures[i].id); } // draw mesh glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, static_cast<unsigned int>(indices.size()), GL_UNSIGNED_INT, 0); glBindVertexArray(0); // always good practice to set everything back to defaults once configured. glActiveTexture(GL_TEXTURE0); } private: // render data unsigned int VBO, EBO; // initializes all the buffer objects/arrays void setupMesh() { // create buffers/arrays glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); // load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, VBO); // A great thing about structs is that their memory layout is sequential for all its items. // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which // again translates to 3/2 floats which translates to a byte array. glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); // set the vertex attribute pointers // vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); // vertex normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal)); // vertex texture coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords)); // vertex tangent glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent)); // vertex bitangent glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent)); // ids glEnableVertexAttribArray(5); glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)offsetof(Vertex, m_BoneIDs)); // weights glEnableVertexAttribArray(6); glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_Weights)); glBindVertexArray(0); } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/model_animation.h
.h
9,140
283
#ifndef MODEL_H #define MODEL_H #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <stb_image.h> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <learnopengl/mesh.h> #include <learnopengl/shader.h> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <vector> #include <learnopengl/assimp_glm_helpers.h> #include <learnopengl/animdata.h> using namespace std; class Model { public: // model data vector<Texture> textures_loaded; // stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once. vector<Mesh> meshes; string directory; bool gammaCorrection; // constructor, expects a filepath to a 3D model. Model(string const &path, bool gamma = false) : gammaCorrection(gamma) { loadModel(path); } // draws the model, and thus all its meshes void Draw(Shader &shader) { for(unsigned int i = 0; i < meshes.size(); i++) meshes[i].Draw(shader); } auto& GetBoneInfoMap() { return m_BoneInfoMap; } int& GetBoneCount() { return m_BoneCounter; } private: std::map<string, BoneInfo> m_BoneInfoMap; int m_BoneCounter = 0; // loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector. void loadModel(string const &path) { // read file via ASSIMP Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_CalcTangentSpace); // check for errors if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl; return; } // retrieve the directory path of the filepath directory = path.substr(0, path.find_last_of('/')); // process ASSIMP's root node recursively processNode(scene->mRootNode, scene); } // processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any). void processNode(aiNode *node, const aiScene *scene) { // process each mesh located at the current node for(unsigned int i = 0; i < node->mNumMeshes; i++) { // the node object only contains indices to index the actual objects in the scene. // the scene contains all the data, node is just to keep stuff organized (like relations between nodes). aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; meshes.push_back(processMesh(mesh, scene)); } // after we've processed all of the meshes (if any) we then recursively process each of the children nodes for(unsigned int i = 0; i < node->mNumChildren; i++) { processNode(node->mChildren[i], scene); } } void SetVertexBoneDataToDefault(Vertex& vertex) { for (int i = 0; i < MAX_BONE_INFLUENCE; i++) { vertex.m_BoneIDs[i] = -1; vertex.m_Weights[i] = 0.0f; } } Mesh processMesh(aiMesh* mesh, const aiScene* scene) { vector<Vertex> vertices; vector<unsigned int> indices; vector<Texture> textures; for (unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; SetVertexBoneDataToDefault(vertex); vertex.Position = AssimpGLMHelpers::GetGLMVec(mesh->mVertices[i]); vertex.Normal = AssimpGLMHelpers::GetGLMVec(mesh->mNormals[i]); if (mesh->mTextureCoords[0]) { glm::vec2 vec; vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.TexCoords = vec; } else vertex.TexCoords = glm::vec2(0.0f, 0.0f); vertices.push_back(vertex); } for (unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (unsigned int j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal"); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height"); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); ExtractBoneWeightForVertices(vertices,mesh,scene); return Mesh(vertices, indices, textures); } void SetVertexBoneData(Vertex& vertex, int boneID, float weight) { for (int i = 0; i < MAX_BONE_INFLUENCE; ++i) { if (vertex.m_BoneIDs[i] < 0) { vertex.m_Weights[i] = weight; vertex.m_BoneIDs[i] = boneID; break; } } } void ExtractBoneWeightForVertices(std::vector<Vertex>& vertices, aiMesh* mesh, const aiScene* scene) { auto& boneInfoMap = m_BoneInfoMap; int& boneCount = m_BoneCounter; for (int boneIndex = 0; boneIndex < mesh->mNumBones; ++boneIndex) { int boneID = -1; std::string boneName = mesh->mBones[boneIndex]->mName.C_Str(); if (boneInfoMap.find(boneName) == boneInfoMap.end()) { BoneInfo newBoneInfo; newBoneInfo.id = boneCount; newBoneInfo.offset = AssimpGLMHelpers::ConvertMatrixToGLMFormat(mesh->mBones[boneIndex]->mOffsetMatrix); boneInfoMap[boneName] = newBoneInfo; boneID = boneCount; boneCount++; } else { boneID = boneInfoMap[boneName].id; } assert(boneID != -1); auto weights = mesh->mBones[boneIndex]->mWeights; int numWeights = mesh->mBones[boneIndex]->mNumWeights; for (int weightIndex = 0; weightIndex < numWeights; ++weightIndex) { int vertexId = weights[weightIndex].mVertexId; float weight = weights[weightIndex].mWeight; assert(vertexId <= vertices.size()); SetVertexBoneData(vertices[vertexId], boneID, weight); } } } unsigned int TextureFromFile(const char* path, const string& directory, bool gamma = false) { string filename = string(path); filename = directory + '/' + filename; unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char* data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0); if (data) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; } // checks all material textures of a given type and loads the textures if they're not loaded yet. // the required info is returned as a Texture struct. vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName) { vector<Texture> textures; for(unsigned int i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture bool skip = false; for(unsigned int j = 0; j < textures_loaded.size(); j++) { if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0) { textures.push_back(textures_loaded[j]); skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization) break; } } if(!skip) { // if texture hasn't been loaded already, load it Texture texture; texture.id = TextureFromFile(str.C_Str(), this->directory); texture.type = typeName; texture.path = str.C_Str(); textures.push_back(texture); textures_loaded.push_back(texture); // store it as texture loaded for entire model, to ensure we won't unnecessary load duplicate textures. } } return textures; } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/camera.h
.h
4,341
131
#ifndef CAMERA_H #define CAMERA_H #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <vector> // Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods enum Camera_Movement { FORWARD, BACKWARD, LEFT, RIGHT }; // Default camera values const float YAW = -90.0f; const float PITCH = 0.0f; const float SPEED = 2.5f; const float SENSITIVITY = 0.1f; const float ZOOM = 45.0f; // An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL class Camera { public: // camera Attributes glm::vec3 Position; glm::vec3 Front; glm::vec3 Up; glm::vec3 Right; glm::vec3 WorldUp; // euler Angles float Yaw; float Pitch; // camera options float MovementSpeed; float MouseSensitivity; float Zoom; // constructor with vectors Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM) { Position = position; WorldUp = up; Yaw = yaw; Pitch = pitch; updateCameraVectors(); } // constructor with scalar values Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM) { Position = glm::vec3(posX, posY, posZ); WorldUp = glm::vec3(upX, upY, upZ); Yaw = yaw; Pitch = pitch; updateCameraVectors(); } // returns the view matrix calculated using Euler Angles and the LookAt Matrix glm::mat4 GetViewMatrix() { return glm::lookAt(Position, Position + Front, Up); } // processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems) void ProcessKeyboard(Camera_Movement direction, float deltaTime) { float velocity = MovementSpeed * deltaTime; if (direction == FORWARD) Position += Front * velocity; if (direction == BACKWARD) Position -= Front * velocity; if (direction == LEFT) Position -= Right * velocity; if (direction == RIGHT) Position += Right * velocity; } // processes input received from a mouse input system. Expects the offset value in both the x and y direction. void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true) { xoffset *= MouseSensitivity; yoffset *= MouseSensitivity; Yaw += xoffset; Pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (Pitch > 89.0f) Pitch = 89.0f; if (Pitch < -89.0f) Pitch = -89.0f; } // update Front, Right and Up Vectors using the updated Euler angles updateCameraVectors(); } // processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis void ProcessMouseScroll(float yoffset) { Zoom -= (float)yoffset; if (Zoom < 1.0f) Zoom = 1.0f; if (Zoom > 45.0f) Zoom = 45.0f; } private: // calculates the front vector from the Camera's (updated) Euler Angles void updateCameraVectors() { // calculate the new Front vector glm::vec3 front; front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch)); front.y = sin(glm::radians(Pitch)); front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch)); Front = glm::normalize(front); // also re-calculate the Right and Up vector Right = glm::normalize(glm::cross(Front, WorldUp)); // normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. Up = glm::normalize(glm::cross(Right, Front)); } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/filesystem.h
.h
1,281
54
#ifndef FILESYSTEM_H #define FILESYSTEM_H #include <string> #include <cstdlib> static const char * logl_root = "/home/ziv/opt/LearnOpenGL"; // #include "root_directory.h" // This is a configuration file generated by CMake. class FileSystem { private: typedef std::string (*Builder) (const std::string& path); public: static std::string getPath(const std::string& path) { static std::string(*pathBuilder)(std::string const &) = getPathBuilder(); return (*pathBuilder)(path); } private: static std::string const & getRoot() { static char const * envRoot = getenv("LOGL_ROOT_PATH"); static char const * givenRoot = (envRoot != nullptr ? envRoot : logl_root); static std::string root = (givenRoot != nullptr ? givenRoot : ""); return root; } //static std::string(*foo (std::string const &)) getPathBuilder() static Builder getPathBuilder() { if (getRoot() != "") return &FileSystem::getPathRelativeRoot; else return &FileSystem::getPathRelativeBinary; } static std::string getPathRelativeRoot(const std::string& path) { return getRoot() + std::string("/") + path; } static std::string getPathRelativeBinary(const std::string& path) { return "../../../" + path; } }; // FILESYSTEM_H #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/shader_c.h
.h
5,827
151
#ifndef COMPUTE_SHADER_H #define COMPUTE_SHADER_H #include <glad/glad.h> #include <glm/glm.hpp> #include <string> #include <fstream> #include <sstream> #include <iostream> class ComputeShader { public: unsigned int ID; // constructor generates the shader on the fly // ------------------------------------------------------------------------ ComputeShader(const char* computePath) { // 1. retrieve the vertex/fragment source code from filePath std::string computeCode; std::ifstream cShaderFile; // ensure ifstream objects can throw exceptions: cShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { // open files cShaderFile.open(computePath); std::stringstream cShaderStream; // read file's buffer contents into streams cShaderStream << cShaderFile.rdbuf(); // close file handlers cShaderFile.close(); // convert stream into string computeCode = cShaderStream.str(); } catch (std::ifstream::failure& e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ: " << e.what() << std::endl; } const char* cShaderCode = computeCode.c_str(); // 2. compile shaders unsigned int compute; // compute shader compute = glCreateShader(GL_COMPUTE_SHADER); glShaderSource(compute, 1, &cShaderCode, NULL); glCompileShader(compute); checkCompileErrors(compute, "COMPUTE"); // shader Program ID = glCreateProgram(); glAttachShader(ID, compute); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessary glDeleteShader(compute); } // activate the shader // ------------------------------------------------------------------------ void use() { glUseProgram(ID); } // utility uniform functions // ------------------------------------------------------------------------ void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } // ------------------------------------------------------------------------ void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } // ------------------------------------------------------------------------ void setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } // ------------------------------------------------------------------------ void setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec4(const std::string &name, float x, float y, float z, float w) { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } // ------------------------------------------------------------------------ void setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } private: // utility function for checking shader compilation/linking errors. // ------------------------------------------------------------------------ void checkCompileErrors(GLuint shader, std::string type) { GLint success; GLchar infoLog[1024]; if(type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/entity.h
.h
14,955
486
#ifndef ENTITY_H #define ENTITY_H #include <glm/glm.hpp> //glm::mat4 #include <list> //std::list #include <array> //std::array #include <memory> //std::unique_ptr class Transform { protected: //Local space information glm::vec3 m_pos = { 0.0f, 0.0f, 0.0f }; glm::vec3 m_eulerRot = { 0.0f, 0.0f, 0.0f }; //In degrees glm::vec3 m_scale = { 1.0f, 1.0f, 1.0f }; //Global space information concatenate in matrix glm::mat4 m_modelMatrix = glm::mat4(1.0f); //Dirty flag bool m_isDirty = true; protected: glm::mat4 getLocalModelMatrix() { const glm::mat4 transformX = glm::rotate(glm::mat4(1.0f), glm::radians(m_eulerRot.x), glm::vec3(1.0f, 0.0f, 0.0f)); const glm::mat4 transformY = glm::rotate(glm::mat4(1.0f), glm::radians(m_eulerRot.y), glm::vec3(0.0f, 1.0f, 0.0f)); const glm::mat4 transformZ = glm::rotate(glm::mat4(1.0f), glm::radians(m_eulerRot.z), glm::vec3(0.0f, 0.0f, 1.0f)); // Y * X * Z const glm::mat4 rotationMatrix = transformY * transformX * transformZ; // translation * rotation * scale (also know as TRS matrix) return glm::translate(glm::mat4(1.0f), m_pos) * rotationMatrix * glm::scale(glm::mat4(1.0f), m_scale); } public: void computeModelMatrix() { m_modelMatrix = getLocalModelMatrix(); m_isDirty = false; } void computeModelMatrix(const glm::mat4& parentGlobalModelMatrix) { m_modelMatrix = parentGlobalModelMatrix * getLocalModelMatrix(); m_isDirty = false; } void setLocalPosition(const glm::vec3& newPosition) { m_pos = newPosition; m_isDirty = true; } void setLocalRotation(const glm::vec3& newRotation) { m_eulerRot = newRotation; m_isDirty = true; } void setLocalScale(const glm::vec3& newScale) { m_scale = newScale; m_isDirty = true; } const glm::vec3& getGlobalPosition() const { return m_modelMatrix[3]; } const glm::vec3& getLocalPosition() const { return m_pos; } const glm::vec3& getLocalRotation() const { return m_eulerRot; } const glm::vec3& getLocalScale() const { return m_scale; } const glm::mat4& getModelMatrix() const { return m_modelMatrix; } glm::vec3 getRight() const { return m_modelMatrix[0]; } glm::vec3 getUp() const { return m_modelMatrix[1]; } glm::vec3 getBackward() const { return m_modelMatrix[2]; } glm::vec3 getForward() const { return -m_modelMatrix[2]; } glm::vec3 getGlobalScale() const { return { glm::length(getRight()), glm::length(getUp()), glm::length(getBackward()) }; } bool isDirty() const { return m_isDirty; } }; struct Plane { glm::vec3 normal = { 0.f, 1.f, 0.f }; // unit vector float distance = 0.f; // Distance with origin Plane() = default; Plane(const glm::vec3& p1, const glm::vec3& norm) : normal(glm::normalize(norm)), distance(glm::dot(normal, p1)) {} float getSignedDistanceToPlane(const glm::vec3& point) const { return glm::dot(normal, point) - distance; } }; struct Frustum { Plane topFace; Plane bottomFace; Plane rightFace; Plane leftFace; Plane farFace; Plane nearFace; }; struct BoundingVolume { virtual bool isOnFrustum(const Frustum& camFrustum, const Transform& transform) const = 0; virtual bool isOnOrForwardPlane(const Plane& plane) const = 0; bool isOnFrustum(const Frustum& camFrustum) const { return (isOnOrForwardPlane(camFrustum.leftFace) && isOnOrForwardPlane(camFrustum.rightFace) && isOnOrForwardPlane(camFrustum.topFace) && isOnOrForwardPlane(camFrustum.bottomFace) && isOnOrForwardPlane(camFrustum.nearFace) && isOnOrForwardPlane(camFrustum.farFace)); }; }; struct Sphere : public BoundingVolume { glm::vec3 center{ 0.f, 0.f, 0.f }; float radius{ 0.f }; Sphere(const glm::vec3& inCenter, float inRadius) : BoundingVolume{}, center{ inCenter }, radius{ inRadius } {} bool isOnOrForwardPlane(const Plane& plane) const final { return plane.getSignedDistanceToPlane(center) > -radius; } bool isOnFrustum(const Frustum& camFrustum, const Transform& transform) const final { //Get global scale thanks to our transform const glm::vec3 globalScale = transform.getGlobalScale(); //Get our global center with process it with the global model matrix of our transform const glm::vec3 globalCenter{ transform.getModelMatrix() * glm::vec4(center, 1.f) }; //To wrap correctly our shape, we need the maximum scale scalar. const float maxScale = std::max(std::max(globalScale.x, globalScale.y), globalScale.z); //Max scale is assuming for the diameter. So, we need the half to apply it to our radius Sphere globalSphere(globalCenter, radius * (maxScale * 0.5f)); //Check Firstly the result that have the most chance to failure to avoid to call all functions. return (globalSphere.isOnOrForwardPlane(camFrustum.leftFace) && globalSphere.isOnOrForwardPlane(camFrustum.rightFace) && globalSphere.isOnOrForwardPlane(camFrustum.farFace) && globalSphere.isOnOrForwardPlane(camFrustum.nearFace) && globalSphere.isOnOrForwardPlane(camFrustum.topFace) && globalSphere.isOnOrForwardPlane(camFrustum.bottomFace)); }; }; struct SquareAABB : public BoundingVolume { glm::vec3 center{ 0.f, 0.f, 0.f }; float extent{ 0.f }; SquareAABB(const glm::vec3& inCenter, float inExtent) : BoundingVolume{}, center{ inCenter }, extent{ inExtent } {} bool isOnOrForwardPlane(const Plane& plane) const final { // Compute the projection interval radius of b onto L(t) = b.c + t * p.n const float r = extent * (std::abs(plane.normal.x) + std::abs(plane.normal.y) + std::abs(plane.normal.z)); return -r <= plane.getSignedDistanceToPlane(center); } bool isOnFrustum(const Frustum& camFrustum, const Transform& transform) const final { //Get global scale thanks to our transform const glm::vec3 globalCenter{ transform.getModelMatrix() * glm::vec4(center, 1.f) }; // Scaled orientation const glm::vec3 right = transform.getRight() * extent; const glm::vec3 up = transform.getUp() * extent; const glm::vec3 forward = transform.getForward() * extent; const float newIi = std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, right)) + std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, up)) + std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, forward)); const float newIj = std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, right)) + std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, up)) + std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, forward)); const float newIk = std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, right)) + std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, up)) + std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, forward)); const SquareAABB globalAABB(globalCenter, std::max(std::max(newIi, newIj), newIk)); return (globalAABB.isOnOrForwardPlane(camFrustum.leftFace) && globalAABB.isOnOrForwardPlane(camFrustum.rightFace) && globalAABB.isOnOrForwardPlane(camFrustum.topFace) && globalAABB.isOnOrForwardPlane(camFrustum.bottomFace) && globalAABB.isOnOrForwardPlane(camFrustum.nearFace) && globalAABB.isOnOrForwardPlane(camFrustum.farFace)); }; }; struct AABB : public BoundingVolume { glm::vec3 center{ 0.f, 0.f, 0.f }; glm::vec3 extents{ 0.f, 0.f, 0.f }; AABB(const glm::vec3& min, const glm::vec3& max) : BoundingVolume{}, center{ (max + min) * 0.5f }, extents{ max.x - center.x, max.y - center.y, max.z - center.z } {} AABB(const glm::vec3& inCenter, float iI, float iJ, float iK) : BoundingVolume{}, center{ inCenter }, extents{ iI, iJ, iK } {} std::array<glm::vec3, 8> getVertice() const { std::array<glm::vec3, 8> vertice; vertice[0] = { center.x - extents.x, center.y - extents.y, center.z - extents.z }; vertice[1] = { center.x + extents.x, center.y - extents.y, center.z - extents.z }; vertice[2] = { center.x - extents.x, center.y + extents.y, center.z - extents.z }; vertice[3] = { center.x + extents.x, center.y + extents.y, center.z - extents.z }; vertice[4] = { center.x - extents.x, center.y - extents.y, center.z + extents.z }; vertice[5] = { center.x + extents.x, center.y - extents.y, center.z + extents.z }; vertice[6] = { center.x - extents.x, center.y + extents.y, center.z + extents.z }; vertice[7] = { center.x + extents.x, center.y + extents.y, center.z + extents.z }; return vertice; } //see https://gdbooks.gitbooks.io/3dcollisions/content/Chapter2/static_aabb_plane.html bool isOnOrForwardPlane(const Plane& plane) const final { // Compute the projection interval radius of b onto L(t) = b.c + t * p.n const float r = extents.x * std::abs(plane.normal.x) + extents.y * std::abs(plane.normal.y) + extents.z * std::abs(plane.normal.z); return -r <= plane.getSignedDistanceToPlane(center); } bool isOnFrustum(const Frustum& camFrustum, const Transform& transform) const final { //Get global scale thanks to our transform const glm::vec3 globalCenter{ transform.getModelMatrix() * glm::vec4(center, 1.f) }; // Scaled orientation const glm::vec3 right = transform.getRight() * extents.x; const glm::vec3 up = transform.getUp() * extents.y; const glm::vec3 forward = transform.getForward() * extents.z; const float newIi = std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, right)) + std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, up)) + std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, forward)); const float newIj = std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, right)) + std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, up)) + std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, forward)); const float newIk = std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, right)) + std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, up)) + std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, forward)); const AABB globalAABB(globalCenter, newIi, newIj, newIk); return (globalAABB.isOnOrForwardPlane(camFrustum.leftFace) && globalAABB.isOnOrForwardPlane(camFrustum.rightFace) && globalAABB.isOnOrForwardPlane(camFrustum.topFace) && globalAABB.isOnOrForwardPlane(camFrustum.bottomFace) && globalAABB.isOnOrForwardPlane(camFrustum.nearFace) && globalAABB.isOnOrForwardPlane(camFrustum.farFace)); }; }; Frustum createFrustumFromCamera(const Camera& cam, float aspect, float fovY, float zNear, float zFar) { Frustum frustum; const float halfVSide = zFar * tanf(fovY * .5f); const float halfHSide = halfVSide * aspect; const glm::vec3 frontMultFar = zFar * cam.Front; frustum.nearFace = { cam.Position + zNear * cam.Front, cam.Front }; frustum.farFace = { cam.Position + frontMultFar, -cam.Front }; frustum.rightFace = { cam.Position, glm::cross(frontMultFar - cam.Right * halfHSide, cam.Up) }; frustum.leftFace = { cam.Position, glm::cross(cam.Up, frontMultFar + cam.Right * halfHSide) }; frustum.topFace = { cam.Position, glm::cross(cam.Right, frontMultFar - cam.Up * halfVSide) }; frustum.bottomFace = { cam.Position, glm::cross(frontMultFar + cam.Up * halfVSide, cam.Right) }; return frustum; } AABB generateAABB(const Model& model) { glm::vec3 minAABB = glm::vec3(std::numeric_limits<float>::max()); glm::vec3 maxAABB = glm::vec3(std::numeric_limits<float>::min()); for (auto&& mesh : model.meshes) { for (auto&& vertex : mesh.vertices) { minAABB.x = std::min(minAABB.x, vertex.Position.x); minAABB.y = std::min(minAABB.y, vertex.Position.y); minAABB.z = std::min(minAABB.z, vertex.Position.z); maxAABB.x = std::max(maxAABB.x, vertex.Position.x); maxAABB.y = std::max(maxAABB.y, vertex.Position.y); maxAABB.z = std::max(maxAABB.z, vertex.Position.z); } } return AABB(minAABB, maxAABB); } Sphere generateSphereBV(const Model& model) { glm::vec3 minAABB = glm::vec3(std::numeric_limits<float>::max()); glm::vec3 maxAABB = glm::vec3(std::numeric_limits<float>::min()); for (auto&& mesh : model.meshes) { for (auto&& vertex : mesh.vertices) { minAABB.x = std::min(minAABB.x, vertex.Position.x); minAABB.y = std::min(minAABB.y, vertex.Position.y); minAABB.z = std::min(minAABB.z, vertex.Position.z); maxAABB.x = std::max(maxAABB.x, vertex.Position.x); maxAABB.y = std::max(maxAABB.y, vertex.Position.y); maxAABB.z = std::max(maxAABB.z, vertex.Position.z); } } return Sphere((maxAABB + minAABB) * 0.5f, glm::length(minAABB - maxAABB)); } class Entity { public: //Scene graph std::list<std::unique_ptr<Entity>> children; Entity* parent = nullptr; //Space information Transform transform; Model* pModel = nullptr; std::unique_ptr<AABB> boundingVolume; // constructor, expects a filepath to a 3D model. Entity(Model& model) : pModel{ &model } { boundingVolume = std::make_unique<AABB>(generateAABB(model)); //boundingVolume = std::make_unique<Sphere>(generateSphereBV(model)); } AABB getGlobalAABB() { //Get global scale thanks to our transform const glm::vec3 globalCenter{ transform.getModelMatrix() * glm::vec4(boundingVolume->center, 1.f) }; // Scaled orientation const glm::vec3 right = transform.getRight() * boundingVolume->extents.x; const glm::vec3 up = transform.getUp() * boundingVolume->extents.y; const glm::vec3 forward = transform.getForward() * boundingVolume->extents.z; const float newIi = std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, right)) + std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, up)) + std::abs(glm::dot(glm::vec3{ 1.f, 0.f, 0.f }, forward)); const float newIj = std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, right)) + std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, up)) + std::abs(glm::dot(glm::vec3{ 0.f, 1.f, 0.f }, forward)); const float newIk = std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, right)) + std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, up)) + std::abs(glm::dot(glm::vec3{ 0.f, 0.f, 1.f }, forward)); return AABB(globalCenter, newIi, newIj, newIk); } //Add child. Argument input is argument of any constructor that you create. By default you can use the default constructor and don't put argument input. template<typename... TArgs> void addChild(TArgs&... args) { children.emplace_back(std::make_unique<Entity>(args...)); children.back()->parent = this; } //Update transform if it was changed void updateSelfAndChild() { if (transform.isDirty()) { forceUpdateSelfAndChild(); return; } for (auto&& child : children) { child->updateSelfAndChild(); } } //Force update of transform even if local space don't change void forceUpdateSelfAndChild() { if (parent) transform.computeModelMatrix(parent->transform.getModelMatrix()); else transform.computeModelMatrix(); for (auto&& child : children) { child->forceUpdateSelfAndChild(); } } void drawSelfAndChild(const Frustum& frustum, Shader& ourShader, unsigned int& display, unsigned int& total) { if (boundingVolume->isOnFrustum(frustum, transform)) { ourShader.setMat4("model", transform.getModelMatrix()); pModel->Draw(ourShader); display++; } total++; for (auto&& child : children) { child->drawSelfAndChild(frustum, ourShader, display, total); } } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/shader.h
.h
7,660
192
#ifndef SHADER_H #define SHADER_H #include <glad/glad.h> #include <glm/glm.hpp> #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: unsigned int ID; // constructor generates the shader on the fly // ------------------------------------------------------------------------ Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::string geometryCode; std::ifstream vShaderFile; std::ifstream fShaderFile; std::ifstream gShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); gShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); // if geometry shader path is present, also load a geometry shader if(geometryPath != nullptr) { gShaderFile.open(geometryPath); std::stringstream gShaderStream; gShaderStream << gShaderFile.rdbuf(); gShaderFile.close(); geometryCode = gShaderStream.str(); } } catch (std::ifstream::failure& e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ: " << e.what() << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char * fShaderCode = fragmentCode.c_str(); // 2. compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // if geometry shader is given, compile geometry shader unsigned int geometry; if(geometryPath != nullptr) { const char * gShaderCode = geometryCode.c_str(); geometry = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(geometry, 1, &gShaderCode, NULL); glCompileShader(geometry); checkCompileErrors(geometry, "GEOMETRY"); } // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); if(geometryPath != nullptr) glAttachShader(ID, geometry); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessary glDeleteShader(vertex); glDeleteShader(fragment); if(geometryPath != nullptr) glDeleteShader(geometry); } // activate the shader // ------------------------------------------------------------------------ void use() { glUseProgram(ID); } // utility uniform functions // ------------------------------------------------------------------------ void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } // ------------------------------------------------------------------------ void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } // ------------------------------------------------------------------------ void setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } // ------------------------------------------------------------------------ void setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec4(const std::string &name, float x, float y, float z, float w) { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } // ------------------------------------------------------------------------ void setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } private: // utility function for checking shader compilation/linking errors. // ------------------------------------------------------------------------ void checkCompileErrors(GLuint shader, std::string type) { GLint success; GLchar infoLog[1024]; if(type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/animdata.h
.h
207
15
#pragma once #include<glm/glm.hpp> struct BoneInfo { /*id is index in finalBoneMatrices*/ int id; /*offset matrix transforms vertex from model space to bone space*/ glm::mat4 offset; }; #pragma once
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/animation.h
.h
2,857
112
#pragma once #include <vector> #include <map> #include <glm/glm.hpp> #include <assimp/scene.h> #include <learnopengl/bone.h> #include <functional> #include <learnopengl/animdata.h> #include <learnopengl/model_animation.h> struct AssimpNodeData { glm::mat4 transformation; std::string name; int childrenCount; std::vector<AssimpNodeData> children; }; class Animation { public: Animation() = default; Animation(const std::string& animationPath, Model* model) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(animationPath, aiProcess_Triangulate); assert(scene && scene->mRootNode); auto animation = scene->mAnimations[0]; m_Duration = animation->mDuration; m_TicksPerSecond = animation->mTicksPerSecond; aiMatrix4x4 globalTransformation = scene->mRootNode->mTransformation; globalTransformation = globalTransformation.Inverse(); ReadHierarchyData(m_RootNode, scene->mRootNode); ReadMissingBones(animation, *model); } ~Animation() { } Bone* FindBone(const std::string& name) { auto iter = std::find_if(m_Bones.begin(), m_Bones.end(), [&](const Bone& Bone) { return Bone.GetBoneName() == name; } ); if (iter == m_Bones.end()) return nullptr; else return &(*iter); } inline float GetTicksPerSecond() { return m_TicksPerSecond; } inline float GetDuration() { return m_Duration;} inline const AssimpNodeData& GetRootNode() { return m_RootNode; } inline const std::map<std::string,BoneInfo>& GetBoneIDMap() { return m_BoneInfoMap; } private: void ReadMissingBones(const aiAnimation* animation, Model& model) { int size = animation->mNumChannels; auto& boneInfoMap = model.GetBoneInfoMap();//getting m_BoneInfoMap from Model class int& boneCount = model.GetBoneCount(); //getting the m_BoneCounter from Model class //reading channels(bones engaged in an animation and their keyframes) for (int i = 0; i < size; i++) { auto channel = animation->mChannels[i]; std::string boneName = channel->mNodeName.data; if (boneInfoMap.find(boneName) == boneInfoMap.end()) { boneInfoMap[boneName].id = boneCount; boneCount++; } m_Bones.push_back(Bone(channel->mNodeName.data, boneInfoMap[channel->mNodeName.data].id, channel)); } m_BoneInfoMap = boneInfoMap; } void ReadHierarchyData(AssimpNodeData& dest, const aiNode* src) { assert(src); dest.name = src->mName.data; dest.transformation = AssimpGLMHelpers::ConvertMatrixToGLMFormat(src->mTransformation); dest.childrenCount = src->mNumChildren; for (int i = 0; i < src->mNumChildren; i++) { AssimpNodeData newData; ReadHierarchyData(newData, src->mChildren[i]); dest.children.push_back(newData); } } float m_Duration; int m_TicksPerSecond; std::vector<Bone> m_Bones; AssimpNodeData m_RootNode; std::map<std::string, BoneInfo> m_BoneInfoMap; };
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/shader_m.h
.h
6,523
166
#ifndef SHADER_H #define SHADER_H #include <glad/glad.h> #include <glm/glm.hpp> #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: unsigned int ID; // constructor generates the shader on the fly // ------------------------------------------------------------------------ Shader(const char* vertexPath, const char* fragmentPath) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (std::ifstream::failure& e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ: " << e.what() << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char * fShaderCode = fragmentCode.c_str(); // 2. compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessary glDeleteShader(vertex); glDeleteShader(fragment); } // activate the shader // ------------------------------------------------------------------------ void use() const { glUseProgram(ID); } // utility uniform functions // ------------------------------------------------------------------------ void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } // ------------------------------------------------------------------------ void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } // ------------------------------------------------------------------------ void setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } // ------------------------------------------------------------------------ void setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec4(const std::string &name, float x, float y, float z, float w) const { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } // ------------------------------------------------------------------------ void setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } private: // utility function for checking shader compilation/linking errors. // ------------------------------------------------------------------------ void checkCompileErrors(GLuint shader, std::string type) { GLint success; GLchar infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/shader_t.h
.h
9,618
235
#ifndef SHADER_H #define SHADER_H #include <glad/glad.h> #include <glm/glm.hpp> #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: unsigned int ID; // constructor generates the shader on the fly // ------------------------------------------------------------------------ Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr, const char* tessControlPath = nullptr, const char* tessEvalPath = nullptr) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::string geometryCode; std::string tessControlCode; std::string tessEvalCode; std::ifstream vShaderFile; std::ifstream fShaderFile; std::ifstream gShaderFile; std::ifstream tcShaderFile; std::ifstream teShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); gShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); tcShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); teShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); // if geometry shader path is present, also load a geometry shader if(geometryPath != nullptr) { gShaderFile.open(geometryPath); std::stringstream gShaderStream; gShaderStream << gShaderFile.rdbuf(); gShaderFile.close(); geometryCode = gShaderStream.str(); } if(tessControlPath != nullptr) { tcShaderFile.open(tessControlPath); std::stringstream tcShaderStream; tcShaderStream << tcShaderFile.rdbuf(); tcShaderFile.close(); tessControlCode = tcShaderStream.str(); } if(tessEvalPath != nullptr) { teShaderFile.open(tessEvalPath); std::stringstream teShaderStream; teShaderStream << teShaderFile.rdbuf(); teShaderFile.close(); tessEvalCode = teShaderStream.str(); } } catch (std::ifstream::failure& e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ" << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char * fShaderCode = fragmentCode.c_str(); // 2. compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // if geometry shader is given, compile geometry shader unsigned int geometry; if(geometryPath != nullptr) { const char * gShaderCode = geometryCode.c_str(); geometry = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(geometry, 1, &gShaderCode, NULL); glCompileShader(geometry); checkCompileErrors(geometry, "GEOMETRY"); } // if tessellation shader is given, compile tessellation shader unsigned int tessControl; if(tessControlPath != nullptr) { const char * tcShaderCode = tessControlCode.c_str(); tessControl = glCreateShader(GL_TESS_CONTROL_SHADER); glShaderSource(tessControl, 1, &tcShaderCode, NULL); glCompileShader(tessControl); checkCompileErrors(tessControl, "TESS_CONTROL"); } unsigned int tessEval; if(tessEvalPath != nullptr) { const char * teShaderCode = tessEvalCode.c_str(); tessEval = glCreateShader(GL_TESS_EVALUATION_SHADER); glShaderSource(tessEval, 1, &teShaderCode, NULL); glCompileShader(tessEval); checkCompileErrors(tessEval, "TESS_EVALUATION"); } // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); if(geometryPath != nullptr) glAttachShader(ID, geometry); if(tessControlPath != nullptr) glAttachShader(ID, tessControl); if(tessEvalPath != nullptr) glAttachShader(ID, tessEval); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessary glDeleteShader(vertex); glDeleteShader(fragment); if(geometryPath != nullptr) glDeleteShader(geometry); } // activate the shader // ------------------------------------------------------------------------ void use() { glUseProgram(ID); } // utility uniform functions // ------------------------------------------------------------------------ void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } // ------------------------------------------------------------------------ void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } // ------------------------------------------------------------------------ void setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } // ------------------------------------------------------------------------ void setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } // ------------------------------------------------------------------------ void setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec4(const std::string &name, float x, float y, float z, float w) { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } // ------------------------------------------------------------------------ void setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ void setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } private: // utility function for checking shader compilation/linking errors. // ------------------------------------------------------------------------ void checkCompileErrors(GLuint shader, std::string type) { GLint success; GLchar infoLog[1024]; if(type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } }; #endif
Unknown
3D
hku-mars/ImMesh
src/shader/learnopengl/model.h
.h
9,928
246
#ifndef MODEL_H #define MODEL_H #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "../stb_image.h" #include "./mesh.h" #include "./shader.h" #include <string> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <vector> using namespace std; unsigned int TextureFromFile(const char *path, const string &directory, bool gamma = false); class Model { public: // model data vector<Texture> textures_loaded; // stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once. vector<Mesh> meshes; string directory; bool gammaCorrection; // constructor, expects a filepath to a 3D model. Model(string const &path, bool gamma = false) : gammaCorrection(gamma) { loadModel(path); } // draws the model, and thus all its meshes void Draw(Shader &shader) { for(unsigned int i = 0; i < meshes.size(); i++) meshes[i].Draw(shader); } private: // loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector. void loadModel(string const &path) { // read file via ASSIMP Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); // check for errors if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl; return; } // retrieve the directory path of the filepath directory = path.substr(0, path.find_last_of('/')); // process ASSIMP's root node recursively processNode(scene->mRootNode, scene); } // processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any). void processNode(aiNode *node, const aiScene *scene) { // process each mesh located at the current node for(unsigned int i = 0; i < node->mNumMeshes; i++) { // the node object only contains indices to index the actual objects in the scene. // the scene contains all the data, node is just to keep stuff organized (like relations between nodes). aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; meshes.push_back(processMesh(mesh, scene)); } // after we've processed all of the meshes (if any) we then recursively process each of the children nodes for(unsigned int i = 0; i < node->mNumChildren; i++) { processNode(node->mChildren[i], scene); } } Mesh processMesh(aiMesh *mesh, const aiScene *scene) { // data to fill vector<Vertex> vertices; vector<unsigned int> indices; vector<Texture> textures; // walk through each of the mesh's vertices for(unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first. // positions vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; vertex.Position = vector; // normals if (mesh->HasNormals()) { vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; vertex.Normal = vector; } // texture coordinates if(mesh->mTextureCoords[0]) // does the mesh contain texture coordinates? { glm::vec2 vec; // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't // use models where a vertex can have multiple texture coordinates so we always take the first set (0). vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.TexCoords = vec; // tangent vector.x = mesh->mTangents[i].x; vector.y = mesh->mTangents[i].y; vector.z = mesh->mTangents[i].z; vertex.Tangent = vector; // bitangent vector.x = mesh->mBitangents[i].x; vector.y = mesh->mBitangents[i].y; vector.z = mesh->mBitangents[i].z; vertex.Bitangent = vector; } else vertex.TexCoords = glm::vec2(0.0f, 0.0f); vertices.push_back(vertex); } // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices. for(unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; // retrieve all indices of the face and store them in the indices vector for(unsigned int j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } // process materials aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; // we assume a convention for sampler names in the shaders. Each diffuse texture should be named // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER. // Same applies to other texture as the following list summarizes: // diffuse: texture_diffuseN // specular: texture_specularN // normal: texture_normalN // 1. diffuse maps vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); // 2. specular maps vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); // 3. normal maps std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal"); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); // 4. height maps std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height"); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); // return a mesh object created from the extracted mesh data return Mesh(vertices, indices, textures); } // checks all material textures of a given type and loads the textures if they're not loaded yet. // the required info is returned as a Texture struct. vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName) { vector<Texture> textures; for(unsigned int i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture bool skip = false; for(unsigned int j = 0; j < textures_loaded.size(); j++) { if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0) { textures.push_back(textures_loaded[j]); skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization) break; } } if(!skip) { // if texture hasn't been loaded already, load it Texture texture; texture.id = TextureFromFile(str.C_Str(), this->directory); texture.type = typeName; texture.path = str.C_Str(); textures.push_back(texture); textures_loaded.push_back(texture); // store it as texture loaded for entire model, to ensure we won't unnecessary load duplicate textures. } } return textures; } }; inline unsigned int TextureFromFile(const char *path, const string &directory, bool gamma) { string filename = string(path); filename = directory + '/' + filename; unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0); if (data) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; } #endif
Unknown