Skip to content

Instantly share code, notes, and snippets.

@burrussmp
burrussmp / Triangulate.cs
Created April 26, 2020 21:35
Triangulate function to extract the triangles from a list of vertices to construct a mesh in Unity
public class Triangulator
{
private List<Vector2> m_points = new List<Vector2>();
public Triangulator (Vector2[] points) {
m_points = new List<Vector2>(points);
}
public int[] Triangulate() {
List<int> indices = new List<int>();
@burrussmp
burrussmp / createMesh.cs
Created April 26, 2020 21:39
Create a mesh in Unity
IEnumerator CreateMesh(){
while(inFirst)
yield return new WaitForSeconds(0.1f);
int meshID = 97;
int cur = 0;
var resources = Resources.FindObjectsOfTypeAll(typeof(Material));
foreach(var face in mList){
int num_of_vertices = Convert.ToInt32(face[face.Count-1]);
// should we make it hollow?
if (mMap["special"] == 'H' && cur < 4){
@burrussmp
burrussmp / PaperBackground.py
Created May 3, 2020 18:22
Create a realistic paper-like background
BG_COLOR = 209
BG_SIGMA = 5
MONOCHROME = 1
def blank_image(width=1024, height=1024, background=BG_COLOR):
"""
It creates a blank image of the given background color
"""
img = np.full((height, width, MONOCHROME), background, np.uint8)
return img
@burrussmp
burrussmp / SegmentationOneHotEncoder.py
Last active May 5, 2020 18:44
Takes in a matrix HxWx1 where each pixel is a label in the set {0,..,k} and returns a matrix of size HxWx(k+1)
"""
One-hot-encodes segmentation map
@params
y: np.ndarray
HxWx1 seegmentation map where each element is in set {0,...,num_labels}
num_labels: int
Defines the set {0,...,num_labels} which is used to one-hot-encode the segmentation map
Ex. For annotation segmentation, we have 26 letters, so we say 26. It is assumed that a 0 means no class of interest.
@return
target: np.ndarray
@burrussmp
burrussmp / PytorchDataLoader.py
Last active May 5, 2020 19:08
An example of a PyTorch Data Loader that uses ListDataset and a load_data function.
"""
Helper function for the Pytorch data loader
@params
type: string
Specifies if training (train), validation (valid), or testing (test) list
should be generated
@return
mlist: A nested Python list
A list of number of input-output pairs where each element is a list of size 2
The first element is the path to the .npy input file and the second element is
@burrussmp
burrussmp / train.py
Created May 5, 2020 19:55
Training and validation for annotation segmentation network
# used to penalize the model less when it predicts a 0 to account for
# slight frequency issues in the training space i.e. imbalances of label 0 and other labels
weights = np.ones(27)
weights[0] = 0.25
class_weights = torch.FloatTensor(weights).cuda()
"""
Function to train model for a single epoch
@params
model: PyTorch.nn.Module
@burrussmp
burrussmp / TrainMode.py
Created May 5, 2020 20:16
Train a model in Pytorch.
# hyper-parameters
batch_size = 32
learning_rate = 0.001
scheduler_step = 30
epochs = 190
gamma = 0.5
lr_scheduler_step_size = 12
adam_betas = (0.9,0.999)
use_cuda = torch.cuda.is_available()
torch.manual_seed(123456)
@burrussmp
burrussmp / UNet.py
Created May 5, 2020 20:24
Define and load UNet into the GPU
class DoubleConv2D(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.double_conv = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
@burrussmp
burrussmp / testUNetSegmentation.py
Created May 5, 2020 20:49
Test segmentation model (U-Net) using the dice coefficient and return the average, median, and standard deviation dice scores. The close to 1 the average dice score, the better the model.
def dice_loss(input, target):
smooth = 1.
iflat = input.view(-1)
tflat = target.view(-1)
intersection = (iflat * tflat).sum()
return 1 - ((2. * intersection + smooth) /
(iflat.sum() + tflat.sum() + smooth))
@burrussmp
burrussmp / GaussianMixtureModel.py
Created June 13, 2020 20:00
Example of EM Maximization using Gaussian Mixture Model for Unsupervised Segmentation of Image
import cv2
import numpy as np
from sklearn.mixture import GaussianMixture
def preprocess(x):
return (x - x.mean(axis=(0,1,2), keepdims=True)) / x.std(axis=(0,1,2), keepdims=True)
# EM hyper parameters
epsilon = 1e-4 # stopping criterion
R = 10 # number of re-runs