text:
'''
  _   _   _   _   _   _   _   _   _   _   _
 / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \
( P | O | L | Y | G | O | N | S | O | U | P )
 \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/

Plotter-friendly graphics utilities
© Daniel Berio (@colormotor) 2021 - ...

plut - visualization utils (matplotlib-based)
'''

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.patches import Path, PathPatch
from matplotlib.colors import ListedColormap
import matplotlib
import numpy as np
import matplotlib as mpl
import polygonsoup.geom as geom

cfg = lambda: None
cfg.dpi = 100
# Make it a bit prettier
cfg.default_style = 'seaborn-darkgrid'
cfg.plotter = None

class NoPlotter:
    '''Default dummy plotter
      Use plotters.AxiDrawClient or plotters.AxiPlotter to plot something
    '''

    def __init__(self):
        pass

    def _set_bounds(self, w, h):
        pass

    def _stroke(self, P):
        pass

    def _plot(self, title='', padding=0, box=None):
        pass

paper_sizes = {
    'A4': (11.7, 8.3),
    'A3': (16.5, 11.7),
    'A5': (8.3, 5.8)
}

def set_theme(style=cfg.default_style, fontsize=6):
    if style:
        # https://towardsdatascience.com/a-new-plot-theme-for-matplotlib-gadfly-2cffc745ff84
        # Place `gadfly.mplstyle` in `~/.matplotlib/stylelib`
        try:
            plt.rcParams.update(plt.rcParamsDefault)
            plt.style.use(style)
            #print('Setting style ' + style)
        except OSError:
            print('Style ' + style + ' not found')
    #plt.style.use('seaborn') #fivethirtyeight') #seaborn-poster') #seaborn-poster')
    #return

    params = {
    # Illustrator compatible fonts
    # http://jonathansoma.com/lede/data-studio/matplotlib/exporting-from-matplotlib-to-open-in-adobe-illustrator/
    'pdf.fonttype': 42,
    'ps.fonttype': 42,
    'axes.titlesize': fontsize+1,
    'font.family': 'Times New Roman',
    'text.color': 'k',
    'lines.markersize': 2,
    'lines.linewidth': 0.75,
    'lines.markeredgewidth':0.25,
    'axes.labelsize': fontsize,
    'axes.facecolor': (1.,1.,1.,1),
    'xtick.major.pad':0.0,
    'ytick.major.pad':0.0,
    'figure.facecolor': (1.,1.,1.,1),
    'savefig.facecolor': (1.,1.,1.,1),
    'legend.fontsize': 4,
    'xtick.labelsize': fontsize*0.9,
    'ytick.labelsize': fontsize*0.9,
    'xtick.color': '333333',
    'ytick.color': '333333',
    'axes.edgecolor' : '666666',
    'axes.grid': True,
    'grid.color': 'cccccc',
    'grid.alpha': 1.,#'dfdfdf',
    'grid.linestyle': ':',
    'grid.linewidth' : 0.25,
    'figure.figsize': [3, 3],
    }

    mpl.rcParams.update(params)

set_theme()

def stroke(S, clr='k', closed=False, **kwargs):
    if type(S)==list and not S:
        # print('Empty shape')
        return
    if geom.is_compound(S):
        for P in S:
            stroke(P, clr=clr, closed=closed, **kwargs)
        return

    # Send out
    P = [p for p in S]
    if closed:
        P = P + [P[0]]

    P = np.array(S).T
    if closed:
        P = np.vstack([P, P[0]])

    plt.plot(P[0], P[1], color=mpl.colors.to_rgb(clr), **kwargs)

def fill(S, clr, **kwargs):
    if type(S)==list and not S:
        # print('Empty shape')
        return

    if not geom.is_compound(S):
        S = [S]

    if not S:
        # print('Empty shape')
        return

    path = []
    cmds = []
    for P in S:
        path += [p for p in P] + [P[0]]
        cmds += [Path.MOVETO] + [Path.LINETO for p in P[:-1]] + [Path.CLOSEPOLY]
    plt.gca().add_patch(PathPatch(Path(path, cmds), color=clr, fill=True, linewidth=0, **kwargs))

def fill_stroke(S, clr, strokeclr, **kwargs):
    if not S:
        # print('Empty shape')
        return
    if not geom.is_compound(S):
        S = [S]

    path = []
    cmds = []
    for P in S:
        # Send out
        cfg.plotter.stroke(P)

        path += [p for p in P] + [P[0]]
        cmds += [Path.MOVETO] + [Path.LINETO for p in P[:-1]] + [Path.CLOSEPOLY]
    plt.gca().add_patch(PathPatch(Path(path, cmds), facecolor=clr, edgecolor=strokeclr, fill=True,  **kwargs))

def stroke_rect(rect, clr='k', plot=True, **kwargs):
    x, y = rect[0]
    w, h = rect[1] - rect[0]

    # Send out
    if plot:
        cfg.plotter._stroke(geom.rect_corners(rect, close=True))

    plt.gca().add_patch(
        patches.Rectangle((x, y), w, h, fill=False, edgecolor=clr, **kwargs))

def fill_rect(rect, clr, **kwargs):
    x, y = rect[0]
    w, h = rect[1] - rect[0]
    plt.gca().add_patch(
        patches.Rectangle((x, y), w, h, fill=True, facecolor=clr, **kwargs))

def fill_circle(pos, radius, clr, **kwargs):
    plt.gca().add_patch(
        patches.Circle(pos, radius, fill=True, facecolor=clr, **kwargs)) #alpha=alpha, zorder=zorder))

def stroke_circle(pos, radius, clr, **kwargs):
    plt.gca().add_patch(
        patches.Circle(pos, radius, fill=False, edgecolor=clr, **kwargs)) #alpha=alpha, zorder=zorder))

def draw_markers(P, color, marker='o', **kwargs):
    if type(color) == str:
        plt.plot(P[:,0], P[:,1], color, linestyle='None', marker=marker, **kwargs)
    else:
        plt.plot(P[:,0], P[:,1], color=color, linestyle='None', marker=marker, **kwargs)

def draw_line(a, b, clr, **kwargs):
    p = np.vstack([a,b])
    plt.plot(p[:,0], p[:,1], color=clr, solid_capstyle='round', dash_capstyle='round', **kwargs)

def det22(mat):
    return mat[0,0] * mat[1,1] - mat[0,1]*mat[1,0]

def draw_arrow(a, b, clr, alpha=1., head_width=0.5, head_length=None, overhang=0.3, zorder=None, **kwargs):
    if head_length is None:
        head_length = head_width

    linewidth = 1.0
    if 'lw' in kwargs:
        linewidth = kwargs['lw']
    if 'linewidth' in kwargs:
        linewidth = kwargs['linewidth']

    # Uglyness, still does not work
    axis = plt.gca()
    trans = axis.transData.inverted()
    scale = np.sqrt(det22(trans.get_matrix()))*axis.figure.dpi*100
    head_width = (linewidth*head_width)*scale
    head_length = (linewidth*head_length)*scale
    a, b  = np.array(a), np.array(b)
    d = b - a

    draw_line(a, b - geom.normalize(d)*head_length*0.5, clr, linewidth=linewidth)
    plt.arrow(a[0], a[1], d[0], d[1], lw=0.5, overhang=overhang,
              head_width=head_width, head_length=head_length, length_includes_head=True,
              fc=clr, ec='none', zorder=zorder)

def set_axis_limits(box, pad=0, invert=True, ax=None, y_limits_only=False):
    # UNUSED
    if ax is None:
        ax = plt.gca()

    xlim = [box[0][0]-pad, box[1][0]+pad]
    ylim = [box[0][1]-pad, box[1][1]+pad]

    ax.set_ylim(ylim)
    ax.set_ybound(ylim)
    if not y_limits_only:
        ax.set_xlim(xlim)
        ax.set_xbound(xlim)

    # Hack to get matplotlib to actually respect limits?
    stroke_rect([geom.vec(xlim[0], ylim[0]), geom.vec(xlim[1], ylim[1])], 'r', plot=False, alpha=0)
    # ax.set_clip_on(True)
    if invert:
        ax.invert_yaxis()

def set_axis_limits(P, pad=0, invert=True, ax=None, y_limits_only=False):
    if ax is None:
        ax = plt.gca()

    if type(P) == tuple or (type(P)==list and len(P)==2):
        box = P
        xlim = [box[0][0]-pad, box[1][0]+pad]
        ylim = [box[0][1]-pad, box[1][1]+pad]
    else:
        if type(P) == list:
            P = np.hstack(P)
        xlim = [np.min(P[0,:])-pad, np.max(P[0,:])+pad]
        ylim = [np.min(P[1,:])-pad, np.max(P[1,:])+pad]
    ax.set_ylim(ylim)
    ax.set_ybound(ylim)
    if not y_limits_only:
        ax.set_xlim(xlim)
        ax.set_xbound(xlim)

    # Hack to get matplotlib to actually respect limits?
    stroke_rect([geom.vec(xlim[0],ylim[0]), geom.vec(xlim[1], ylim[1])], 'r', alpha=0)
    # ax.set_clip_on(True)
    if invert:
        ax.invert_yaxis()

def show_drawing(drawing, size='A4', title='', padding=0, plotter=NoPlotter()):
    ''' Plots/draws a axi.Drawing object'''
    figure(size, plotter)
    for path in drawing.paths:
        P = [np.array(p) for p in path]
        stroke(P, 'k')
    show(title, padding)

def figure(size="A5", plotter=NoPlotter()):
    if type(size)==str:
        w, h = paper_sizes[size]
    else:
        w, h = size
    fig = plt.figure(dpi=cfg.dpi)
    fig.set_size_inches(w, h)
    if plotter is None:
        plotter = NoPlotter()
    cfg.plotter = plotter
    plotter._set_bounds(w, h)
    return fig

def show(title='', padding=0, box=None, axis=False, ydown=True, file='', debug_box=False):
    if title:
        plt.title(title)

    setup(ydown, axis, box, debug_box)

    if file:
        plt.savefig(file, transparent=True)

    cfg.plotter._plot(title, padding, box=box)
    plt.show()

def setup(ydown=True, axis=False, box=None, debug_box=False):
    ax = plt.gca()
    ax.axis('scaled')
    if not axis:
        ax.axis('off')
    else:
        ax.axis('on')
    if ydown:
        ax.invert_yaxis()
    if debug_box and box is not None:
        stroke_rect(box, 'r')
    if box is not None:
        set_axis_limits(box, invert=ydown, ax=ax, y_limits_only=False)

categorical_palettes = {
    'Tabular':[
(0.12156862745098039, 0.4666666666666667, 0.7058823529411765),
(0.6823529411764706, 0.7803921568627451, 0.9098039215686274),
(1.0, 0.4980392156862745, 0.054901960784313725),
(1.0, 0.7333333333333333, 0.47058823529411764),
(0.17254901960784313, 0.6274509803921569, 0.17254901960784313),
(0.596078431372549, 0.8745098039215686, 0.5411764705882353),
(0.8392156862745098, 0.15294117647058825, 0.1568627450980392),
(1.0, 0.596078431372549, 0.5882352941176471),
(0.5803921568627451, 0.403921568627451, 0.7411764705882353),
(0.7725490196078432, 0.6901960784313725, 0.8352941176470589),
(0.5490196078431373, 0.33725490196078434, 0.29411764705882354),
(0.7686274509803922, 0.611764705882353, 0.5803921568627451),
(0.8901960784313725, 0.4666666666666667, 0.7607843137254902),
(0.9686274509803922, 0.7137254901960784, 0.8235294117647058),
(0.4980392156862745, 0.4980392156862745, 0.4980392156862745),
(0.7803921568627451, 0.7803921568627451, 0.7803921568627451),
(0.7372549019607844, 0.7411764705882353, 0.13333333333333333),
(0.8588235294117647, 0.8588235294117647, 0.5529411764705883),
(0.09019607843137255, 0.7450980392156863, 0.8117647058823529),
(0.6196078431372549, 0.8549019607843137, 0.8980392156862745)
    ],
'Dark2_8':[
(0.10588235294117647, 0.6196078431372549, 0.4666666666666667),
(0.8509803921568627, 0.37254901960784315, 0.00784313725490196),
(0.4588235294117647, 0.4392156862745098, 0.7019607843137254),
(0.9058823529411765, 0.1607843137254902, 0.5411764705882353),
(0.4, 0.6509803921568628, 0.11764705882352941),
(0.9019607843137255, 0.6705882352941176, 0.00784313725490196),
(0.6509803921568628, 0.4627450980392157, 0.11372549019607843),
(0.4, 0.4, 0.4)
],
'Custom':[
[104.0/255, 175.0/255, 252.0/255],
[66.0/255, 47.0/255, 174.0/255],
[71.0/255, 240.0/255, 163.0/255],
[29.0/255, 104.0/255, 110.0/255],
[52.0/255, 218.0/255, 234.0/255],
[45.0/255, 93.0/255, 168.0/255],
[219.0/255, 119.0/255, 230.0/255],
[165.0/255, 46.0/255, 120.0/255],
[171.0/255, 213.0/255, 51.0/255],
[29.0/255, 109.0/255, 31.0/255],
[143.0/255, 199.0/255, 137.0/255],
[226.0/255, 50.0/255, 9.0/255],
[93.0/255, 242.0/255, 62.0/255],
[94.0/255, 64.0/255, 40.0/255],
[247.0/255, 147.0/255, 2.0/255],
[255.0/255, 0.0/255, 135.0/255],
[226.0/255, 150.0/255, 163.0/255],
[216.0/255, 197.0/255, 152.0/255],
[97.0/255, 8.0/255, 232.0/255],
[243.0/255, 212.0/255, 38.0/255]
],
'Paired_12':[ # Okeish
(0.6509803921568628, 0.807843137254902, 0.8901960784313725),
(0.12156862745098039, 0.47058823529411764, 0.7058823529411765),
(0.6980392156862745, 0.8745098039215686, 0.5411764705882353),
(0.2, 0.6274509803921569, 0.17254901960784313),
(0.984313725490196, 0.6039215686274509, 0.6),
(0.8901960784313725, 0.10196078431372549, 0.10980392156862745),
(0.9921568627450981, 0.7490196078431373, 0.43529411764705883),
(1.0, 0.4980392156862745, 0.0),
(0.792156862745098, 0.6980392156862745, 0.8392156862745098),
(0.41568627450980394, 0.23921568627450981, 0.6039215686274509),
(1.0, 1.0, 0.6),
(0.6941176470588235, 0.34901960784313724, 0.1568627450980392)
],
'Tableau_20':[
(0.12156862745098039, 0.4666666666666667, 0.7058823529411765),
(0.6823529411764706, 0.7803921568627451, 0.9098039215686274),
(1.0, 0.4980392156862745, 0.054901960784313725),
(1.0, 0.7333333333333333, 0.47058823529411764),
(0.17254901960784313, 0.6274509803921569, 0.17254901960784313),
(0.596078431372549, 0.8745098039215686, 0.5411764705882353),
(0.8392156862745098, 0.15294117647058825, 0.1568627450980392),
(1.0, 0.596078431372549, 0.5882352941176471),
(0.5803921568627451, 0.403921568627451, 0.7411764705882353),
(0.7725490196078432, 0.6901960784313725, 0.8352941176470589),
(0.5490196078431373, 0.33725490196078434, 0.29411764705882354),
(0.7686274509803922, 0.611764705882353, 0.5803921568627451),
(0.8901960784313725, 0.4666666666666667, 0.7607843137254902),
(0.9686274509803922, 0.7137254901960784, 0.8235294117647058),
(0.4980392156862745, 0.4980392156862745, 0.4980392156862745),
(0.7803921568627451, 0.7803921568627451, 0.7803921568627451),
(0.7372549019607844, 0.7411764705882353, 0.13333333333333333),
(0.8588235294117647, 0.8588235294117647, 0.5529411764705883),
(0.09019607843137255, 0.7450980392156863, 0.8117647058823529),
(0.6196078431372549, 0.8549019607843137, 0.8980392156862745)
],
'Bold_10':[
(0.4980392156862745, 0.23529411764705882, 0.5529411764705883),
(0.06666666666666667, 0.6470588235294118, 0.4745098039215686),
(0.2235294117647059, 0.4117647058823529, 0.6745098039215687),
(0.9490196078431372, 0.7176470588235294, 0.00392156862745098),
(0.9058823529411765, 0.24705882352941178, 0.4549019607843137),
(0.5019607843137255, 0.7294117647058823, 0.35294117647058826),
(0.9019607843137255, 0.5137254901960784, 0.06274509803921569),
(0.0, 0.5254901960784314, 0.5843137254901961),
(0.8117647058823529, 0.10980392156862745, 0.5647058823529412),
(0.9764705882352941, 0.4823529411764706, 0.4470588235294118)
],
    'Prism_10':[
(0.37254901960784315, 0.27450980392156865, 0.5647058823529412),
(0.11372549019607843, 0.4117647058823529, 0.5882352941176471),
(0.2196078431372549, 0.6509803921568628, 0.6470588235294118),
(0.058823529411764705, 0.5215686274509804, 0.32941176470588235),
(0.45098039215686275, 0.6862745098039216, 0.2823529411764706),
(0.9294117647058824, 0.6784313725490196, 0.03137254901960784),
(0.8823529411764706, 0.48627450980392156, 0.0196078431372549),
(0.8, 0.3137254901960784, 0.24313725490196078),
(0.5803921568627451, 0.20392156862745098, 0.43137254901960786),
(0.43529411764705883, 0.25098039215686274, 0.4392156862745098)
    ],
'ColorBlind_10':[
(0.0, 0.4196078431372549, 0.6431372549019608),
(1.0, 0.5019607843137255, 0.054901960784313725),
(0.6705882352941176, 0.6705882352941176, 0.6705882352941176),
(0.34901960784313724, 0.34901960784313724, 0.34901960784313724),
(0.37254901960784315, 0.6196078431372549, 0.8196078431372549),
(0.7843137254901961, 0.3215686274509804, 0.0),
(0.5372549019607843, 0.5372549019607843, 0.5372549019607843),
(0.6352941176470588, 0.7843137254901961, 0.9254901960784314),
(1.0, 0.7372549019607844, 0.4745098039215686),
(0.8117647058823529, 0.8117647058823529, 0.8117647058823529)
],
    'BlueRed_12':[
(0.17254901960784313, 0.4117647058823529, 0.6901960784313725),
(0.7098039215686275, 0.7843137254901961, 0.8862745098039215),
(0.9411764705882353, 0.15294117647058825, 0.12549019607843137),
(1.0, 0.7137254901960784, 0.6901960784313725),
(0.6745098039215687, 0.3803921568627451, 0.23529411764705882),
(0.9137254901960784, 0.7647058823529411, 0.6078431372549019),
(0.4196078431372549, 0.6392156862745098, 0.8392156862745098),
(0.7098039215686275, 0.8745098039215686, 0.9921568627450981),
(0.6745098039215687, 0.5294117647058824, 0.38823529411764707),
(0.8666666666666667, 0.788235294117647, 0.7058823529411765),
(0.7411764705882353, 0.0392156862745098, 0.21176470588235294),
(0.9568627450980393, 0.45098039215686275, 0.47843137254901963)
    ],
    'plut_categorical_12':[
(1.0, 0.42745098039215684, 0.6823529411764706),
(0.8313725490196079, 0.792156862745098, 0.22745098039215686),
(0.0, 0.7450980392156863, 1.0),
(0.9215686274509803, 0.6745098039215687, 0.9803921568627451),
(0.6196078431372549, 0.6196078431372549, 0.6196078431372549),
(0.403921568627451, 0.8823529411764706, 0.7098039215686275),
(0.8392156862745098, 0.15294117647058825, 0.1568627450980392),
(0.6039215686274509, 0.8156862745098039, 1.0),
(0.8862745098039215, 0.5215686274509804, 0.26666666666666666),
(0.12156862745098039, 0.4666666666666667, 0.7058823529411765),
(1.0, 0.4980392156862745, 0.054901960784313725),
(0.36470588235294116, 0.6941176470588235, 0.35294117647058826)
]

}

default_palette_name = 'plut_categorical_12' #Tableau_20' #'Tabular' #'BlueRed_12' #'Tabular' #'BlueRed_12' #'Tabular' #'BlueRed_12'# 'Paired_12' #OK #'ColorBlind_10' #OK # 'Dark2_8'# OKeish 'Bold_10' #OK #
def get_default_colors():
    return categorical_palettes[default_palette_name]
    #return plt.get_cmap('tab20').colors + plt.get_cmap('tab20b').colors + plt.get_cmap('tab20c').colors
    #return plt.rcParams['axes.prop_cycle'].by_key()['color'] + list(plt.get_cmap('tab20').colors) + list(plt.get_cmap('tab20b').colors) + list(plt.get_cmap('tab20c').colors)

def categorical(name=None):
    if name is None:
        name = palette_name
    return categorical_palettes[name]

def categorical_cmap(name=None):
    return ListedColormap(categorical(name))

def default_color(i):
    clrs = get_default_colors() #plt.rcParams['axes.prop_cycle'].by_key()['color']
    return mpl.colors.to_rgb(clrs[i%len(clrs)])

def default_color_alpha(i, alpha):
    rgb = default_color(i) #default_colors[i%len(default_colors)]
    return list(rgb) + [alpha]

def cmap(v, colormap='turbo'): #'PuRd'):
    c = matplotlib.cm.get_cmap(colormap)
    return c(v)

max_stars_repo_name: colormotor/polygonsoup

max_issues_repo_name: colormotor/polygonsoup

max_forks_repo_name: colormotor/polygonsoup


text:
import os

import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import Point, LineString
from shapely.geometry.polygon import Polygon

class Plotter:

	def process_poly(self, poly):

		lat, lon = [], []

		for p in poly:
			lat.append(float(p[0]))
			lon.append(float(p[1]))

		return lat, lon

	def separate_coord_pairs(self, coords):

		lat, lon = [], []

		for coord in coords:

			if type(coord) != list:
				coord = coord.split(',')
			lat.append(float(coord[0]))
			lon.append(float(coord[1]))

		return lat, lon

	def plot_map(self, data, file_name='test', consider=[]):

		#poly = [(41.875668055546626, -87.63382964300646), (41.87564854462585, -87.63382751090967), (41.87562933663752, -87.63382347667482), (41.875610616565076, -87.63381757915384), (41.87559256469304, -87.63380987514307), (41.8755753548708, -87.63380043883633), (41.875559152838356, -87.63378936111044), (41.875544114630145, -87.63377674864994), (41.875530385072324, -87.63376272291971), (41.87551809638805, -87.63374741899521), (41.87550736692406, -87.6337309842616), (41.87549830001097, -87.63371357699435), (41.875490982968095, -87.63369536483495), (41.87548548626257, -87.63367652317648), (41.87548186283066, -87.63365723347437), (41.87548014756801, -87.63363768149901), (41.87548035699353, -87.63361805554662), (41.87548248909034, -87.63359854462584), (41.87548652332517, -87.63357933663752), (41.87549242084616, -87.63356061656506), (41.875500124856934, -87.63354256469303), (41.87550956116366, -87.63352535487078), (41.87552063888956, -87.63350915283834), (41.87553325135006, -87.63349411463014), (41.875547277080294, -87.63348038507232), (41.875562581004786, -87.63346809638804), (41.875579015738396, -87.63345736692406), (41.875596423005646, -87.63344830001097), (41.87561463516504, -87.6334409829681), (41.87563347682353, -87.63343548626256), (41.87565276652564, -87.63343186283066), (41.875672318500996, -87.633430147568), (41.87569194445338, -87.63343035699353), (41.876861944453374, -87.63350035699354), (41.87688145537415, -87.63350248909033), (41.87690066336248, -87.63350652332518), (41.876919383434924, -87.63351242084616), (41.876937435306964, -87.63352012485693), (41.8769546451292, -87.63352956116367), (41.876970847161644, -87.63354063888956), (41.876985885369855, -87.63355325135007), (41.876999614927676, -87.63356727708029), (41.87701190361195, -87.63358258100479), (41.87702263307594, -87.6335990157384), (41.87703169998903, -87.63361642300565), (41.877039017031905, -87.63363463516505), (41.87704451373743, -87.63365347682353), (41.87704813716934, -87.63367276652563), (41.87704985243199, -87.63369231850099), (41.87704964300647, -87.63371194445338), (41.87704751090966, -87.63373145537416), (41.87704347667483, -87.63375066336248), (41.87703757915384, -87.63376938343494), (41.877029875143066, -87.63378743530697), (41.87702043883634, -87.63380464512922), (41.87700936111044, -87.63382084716166), (41.87699674864994, -87.63383588536986), (41.876982722919706, -87.63384961492768), (41.876967418995214, -87.63386190361196), (41.876950984261605, -87.63387263307594), (41.876933576994354, -87.63388169998903), (41.87691536483496, -87.6338890170319), (41.87689652317647, -87.63389451373745), (41.87687723347436, -87.63389813716934), (41.876857681499004, -87.633899852432), (41.87683805554662, -87.63389964300647), (41.875668055546626, -87.63382964300646)]
		#latpoly, lonpoly = self.process_poly(poly)

		plt.clf()
		ax = plt.subplot(111)

		top, left, right, bot = 41.8872, -87.6517, -87.6246, 41.8663

		# plt.plot([top, top], [left, right], 'k--')
		# plt.plot([top, bot], [left, left], 'k--')
		# plt.plot([bot, bot], [left, right], 'k--')
		# plt.plot([top, bot], [right, right], 'k--')

		scenario_bounds = Polygon([[top, left], [top, right], [bot, right], [bot, left]])

		for key in data:

			if len(consider) > 0 and str(key) not in consider:
				continue

			coords_list = data[key]

			filtered_coords = []

			for coords in coords_list:

				if type(coords) != list:
					coords = coords.split(',')
				coords = list(map(float, coords))

				if Point(coords).within(scenario_bounds):
					filtered_coords.append(coords)

			for i in range(1, len(filtered_coords)):

				lat, lon = self.separate_coord_pairs([filtered_coords[i-1], filtered_coords[i]])
				plt.plot(lon, lat, '--', color='#152D54')

		#plt.plot(latpoly, lonpoly, 'r-', linewidth=1)

		plt.xlabel('Longitude')
		plt.ylabel('Latitude')

		plt.savefig('./routing/mapping/{0}.pdf'.format(file_name), bbox_inches="tight", format='pdf')

	def plot_overlap_map(self, data1, data2, file_name='test'):

		plt.clf()
		ax = plt.subplot(111)

		top, left, right, bot = 41.8872, -87.6517, -87.6246, 41.8663

		plt.plot([top, top], [left, right], 'k--')
		plt.plot([top, bot], [left, left], 'k--')
		plt.plot([bot, bot], [left, right], 'k--')
		plt.plot([top, bot], [right, right], 'k--')

		for key in data1:

			coords_list = data1[key]

			for i in range(1, len(coords_list)):

				lat, lon = self.separate_coord_pairs([coords_list[i-1], coords_list[i]])
				plt.plot(lon, lat, 'r--', alpha=0.5)

		for key in data2:

			coords_list = data2[key]

			for i in range(1, len(coords_list)):

				lat, lon = self.separate_coord_pairs([coords_list[i-1], coords_list[i]])
				plt.plot(lon, lat, 'g--', alpha=0.5)

		plt.savefig('./routing/mapping/{0}.pdf'.format(file_name), bbox_inches="tight", format='pdf')

	def plot_info_traffic(self, road_network, info_flow, mapped, city, folder, file_name='mapped_flow'):

		plt.clf()
		ax = plt.subplot(111)

		top, left, right, bot = 41.8872, -87.6517, -87.6246, 41.8663

		# plt.plot([top, top], [left, right], 'k--')
		# plt.plot([top, bot], [left, left], 'k--')
		# plt.plot([bot, bot], [left, right], 'k--')
		# plt.plot([top, bot], [right, right], 'k--')

		plt.xlabel('Longitude')
		plt.ylabel('Latitude')

		scenario_bounds = Polygon([[top, left], [top, right], [bot, right], [bot, left]])

		colors = ['#A2142E', '#C01D2F', '#E85045', '#F6B574', '#FFF4B9',
				'#D1E890', '#95CF69', '#83CA6E', '#48AD5F', '#238B56',
				'#147346']

		# Plot net outlier
		for key in road_network:

			coords_list = road_network[key]
			filtered_coords = []

			for coords in coords_list:

				if type(coords) != list:
					coords = coords.split(',')
				coords = list(map(float, coords))

				if Point(coords).within(scenario_bounds):
					filtered_coords.append(coords)

			color = None
			if key in mapped:
				if int(float(info_flow[mapped[key]]['JF'])) + 2 > 10:
					color = colors[-1]
				else:
					color = colors[int(float(info_flow[mapped[key]]['JF'])) + 2]

			else:
				color = '#147346'

			for i in range(1, len(filtered_coords)):

				lat, lon = self.separate_coord_pairs([filtered_coords[i-1], filtered_coords[i]])
				plt.plot(lon, lat, 'k-', linewidth=1.8)
				plt.plot(lon, lat, '-', color=color, linewidth=1.6, alpha=0.8)

		if not os.path.exists('./routing/mapping/plots'):
			os.makedirs('./routing/mapping/plots')

		if not os.path.exists('./routing/mapping/plots/{0}'.format(city)):
			os.makedirs('./routing/mapping/plots/{0}'.format(city))

		if not os.path.exists('./routing/mapping/plots/{0}/{1}'.format(city, folder)):
			os.makedirs('./routing/mapping/plots/{0}/{1}'.format(city, folder))

		plt.savefig('./routing/mapping/plots/{0}/{1}/{2}.pdf'.format(city, folder, file_name), bbox_inches="tight", format='pdf')

ext: py

max_stars_repo_name: lucaslzl/gin

max_issues_repo_name: lucaslzl/gin

max_forks_repo_name: lucaslzl/gin

reason: import numpy


text:
"""
Retrain the YOLO model for your own dataset.
"""
import cv2
import numpy as np
import keras.backend as K
import tensorflow as tf
from PIL import Image
from keras.layers import Input, Lambda
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping

from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_data
from utils import pil_image_resize

WEIGHT_path='model_data/yolo.h5'
OUTPUT_file='model_data/raccoon_trained_weights.h5'
#ANNOTATION_path = 'dataset/raccoon/data/raccoon_labels.txt'
RECOEDS = ['dataset/raccoon/a.record']
OUTPUT_log_dir = 'logs/666/'
NUM_classes=1
ANCHORS_path = 'model_data/raccoon_anchors.txt'
INPUT_shape = (64,64) # multiple of 32, (height,width)
BATCH_size = 4
VALID_ratio = 0.2
CLASSES_offset=1 #first label is from 0 or 1
# Train with frozen layers first, to get a stable loss.
# Adjust num epochs to your dataset. This step is enough to obtain a not bad model.
PRE_epochs=50
PRE_initial_epoch=0
PRE_optimizer=Adam(lr=1e-3)
# Unfreeze and continue training, to fine-tune.
# Train longer if the result is not good.
EPOCHS=200
INITIAL_epoch=50
OPTIMIZER=Adam(lr=1e-4)
REDUCE_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)
EARLY_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=20, verbose=1)

def _main():
    """
    #annotation_path = ANNOTATION_path
    log_dir = OUTPUT_log_dir
    num_classes = NUM_classes
    anchors = get_anchors(ANCHORS_path)
    input_shape = INPUT_shape
    is_tiny_version = len(anchors)==6 # default setting

    if is_tiny_version:
        model = create_tiny_model(input_shape, anchors, num_classes,
            freeze_body=2)
    else:
        model = create_model(input_shape, anchors, num_classes,
            freeze_body=2) # make sure you know what you freeze

    logging = TensorBoard(log_dir=log_dir)
    checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',
        monitor='val_loss', save_weights_only=True, save_best_only=True, period=3)
        """
    batch_size = BATCH_size
    valid_ratio = VALID_ratio

    dataset = tf.data.TFRecordDataset(RECOEDS, 'rb').map(lambda x: split_train_valid(x, train_rate=1-valid_ratio))
    dataset_train = dataset.filter(lambda x: filter_per_split(x, train=True)).batch(batch_size)
    dataset_train=dataset_train.map_fn(lambda x: parse_exmp(x['dataset'] ))
    #dataset=dataset.map(parse_exmp).map(lambda x: split_train_valid(x, train_rate=1-valid_ratio))
    #dataset_train = dataset.filter(lambda x: filter_per_split(x, train=True))#.repeat(5).shuffle(2000).batch(1)
    #dataset_valid = dataset.filter(lambda x: filter_per_split(x, train=False)).batch(1).batch(batch_size)#.repeat(5).shuffle(2000).batch(1)
    #dataset_train = dataset.filter(lambda r: tf.string_to_hash_bucket_fast(r, 10) == 0).map(parse_exmp)
    #dataset_valid = dataset.filter(lambda r: tf.string_to_hash_bucket_fast(r, 10) != 0).map(parse_exmp)
    iter_train   = dataset_train.make_one_shot_iterator().get_next()
    #iter_valid   = dataset_valid.make_one_shot_iterator().get_next()
    #iter_dataset=dataset.make_one_shot_iterator().get_next()
    #with open(ANNOTATION_path) as f:
    #    lines = f.readlines()
    #    data_generator2(lines, 1, INPUT_shape , anchors = get_anchors(ANCHORS_path), #num_classes=80)

    with tf.Session() as sess:
        for x in range(1):
            a=sess.run(iter_train)
            print(a)
            #get_random_data2(np.array(a[0]), INPUT_shape , random=True)

    """with tf.Session() as sess:

        i=0
        try:
            while True:
                print(sess.run(iter_train))
                i+=1
        except tf.errors.OutOfRangeError:
            print("end!")

    with tf.Session() as sess:

        j=0
        try:
            while True:
                print(sess.run(iter_valid))
                j+=1
        except tf.errors.OutOfRangeError:
            print("end!")
    print(i,j)"""

    """with open(annotation_path) as f:
        lines = f.readlines()
    np.random.seed(10101)
    np.random.shuffle(lines)
    np.random.seed(None)
    num_valid = int(len(lines)*valid_ratio)
    num_train = len(lines) - num_val"""

    # Train with frozen layers first, to get a stable loss.
    # Adjust num epochs to your dataset. This step is enough to obtain a not bad model.
    if False:
        model.compile(optimizer=Adam(lr=1e-3), loss={
            # use custom yolo_loss Lambda layer.
            'yolo_loss': lambda y_true, y_pred: y_pred})

        #print('Train on {} samples, valid on {} samples, with batch size {}.'.format(num_train, num_valid, batch_size))

        model.fit_generator(
                #data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),
                data_prepared(iter_train, batch_size, input_shape, anchors, num_classes),
                steps_per_epoch=20,
                #validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),
                validation_data=data_prepared(iter_valid, batch_size, input_shape, anchors, num_classes),
                validation_steps=20,
                epochs=PRE_epochs,
                initial_epoch=PRE_initial_epoch,
                callbacks=[logging, checkpoint])
        model.save_weights(log_dir + 'trained_weights_stage_1.h5')

    # Unfreeze and continue training, to fine-tune.
    # Train longer if the result is not good.
    """if True:
        for i in range(len(model.layers)):
            model.layers[i].trainable = True
        model.compile(optimizer=OPTIMIZER, loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change
        print('Unfreeze all of the layers.')

        print('Train on {} samples, valid on {} samples, with batch size {}.'.format(num_train, num_valid, batch_size))

        model.fit_generator(
            data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),
            steps_per_epoch=max(1, num_train//batch_size),
            validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),
            validation_steps=max(1, num_valid//batch_size),
            epochs=EPOCHS,
            initial_epoch=INITIAL_epoch,
            callbacks=[logging, checkpoint, REDUCE_lr, EARLY_stopping])
        model.save_weights(log_dir + output_file)"""

    # Further training if needed.
def parse_exmp(serial_exmp):
    feats = tf.parse_single_example(serial_exmp, features={
            #'image/filename':tf.FixedLenFeature([], tf.string),
            'image/encoded':tf.FixedLenFeature([1], tf.string),
            'image/height':tf.FixedLenFeature([1], tf.int64),
            'image/width':tf.FixedLenFeature([1], tf.int64),
            'image/object/class/label':tf.VarLenFeature( tf.int64),
            'image/object/bbox/xmin':tf.VarLenFeature( tf.float32),
            'image/object/bbox/xmax':tf.VarLenFeature( tf.float32),
            'image/object/bbox/ymin':tf.VarLenFeature( tf.float32),
            'image/object/bbox/ymax':tf.VarLenFeature( tf.float32)
            })

    return feats
def split_train_valid(dataset, train_rate=0.8, seed=10101):
        """ Randomly classify samples into training or testing split """
        is_train_dict={}
        is_train_dict['is_train'] = tf.gather(tf.random_uniform([1], seed=seed) < train_rate, 0)
        is_train_dict['dataset']=dataset
        return is_train_dict
def filter_per_split(dataset, train=True):
        """ Filter samples depending on their split """

        return dataset['is_train'] if train else ~dataset['is_train']

def data_prepared(iter, input_shape, anchors, num_classes):
    '''data generator for fit_generator'''
    while True:
        parsed_features=K.get_session().run(iter)
        parsed_features['image/width']
        parsed_features['image/height']
        xmins=parsed_features["image/object/bbox/xmin"].values
        ymins=parsed_features["image/object/bbox/ymin"].values
        xmaxs=parsed_features["image/object/bbox/xmax"].values
        ymaxs=parsed_features["image/object/bbox/ymax"].values
        image_data = []
        box_data = []
        for b in range(batch_size):
            #if i==0:
            #    np.random.shuffle(annotation_lines)
            image, box = get_random_data2([parsed_features[b]], input_shape, random=True)
            image_data.append(image)
            box_data.append(box)
            #i = (i+1) % n

        image_data = np.array(image_data)
        box_data = np.array(box_data)
        y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)

        yield [image_data, *y_true], np.zeros(batch_size)
def rand(a=0, b=1):
    return np.random.rand()*(b-a) + a
def get_random_data2(parsed_features,input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True):
    from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
    '''random preprocessing for real-time data augmentation'''
    #line = annotation_line.split()
    #image = Image.open(line[0])
    image=Image.fromarray(parsed_features["image/encoded"],'RGB')
    iw=int(parsed_features['image/width'][0])
    ih=int(parsed_features['image/height'][0])
    h, w = input_shape
    #box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])

    box=np.vstack(
    (np.around(parsed_features["image/object/bbox/xmin"].values*parsed_features['image/width']),
    np.around(parsed_features["image/object/bbox/ymin"].values*parsed_features['image/height']),
    np.around(parsed_features["image/object/bbox/xmax"].values*parsed_features['image/width']),
    np.around(parsed_features["image/object/bbox/ymax"].values*parsed_features['image/height']),
    parsed_features["image/object/class/label"].values-CLASSES_offset)).astype(np.int32)
    box=box.T
    print(box)
    if not random:
        # resize image padding
        scale = min(w/iw, h/ih)
        nw = int(iw*scale)
        nh = int(ih*scale)
        dx = (w-nw)//2
        dy = (h-nh)//2
        image_data=0
        if proc_img:
            image = image.resize((nw,nh), Image.BICUBIC)
            new_image = Image.new('RGB', (w,h), (128,128,128))
            new_image.paste(image, (dx, dy))
            image_data = np.array(new_image)/255.

        # correct boxes
        box_data = np.zeros((max_boxes,5))
        if len(box)>0:
            np.random.shuffle(box)
            if len(box)>max_boxes: box = box[:max_boxes]
            box[:, [0,2]] = box[:, [0,2]]*scale + dx
            box[:, [1,3]] = box[:, [1,3]]*scale + dy
            box_data[:len(box)] = box

        return image_data, box_data

    # resize image
    new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter)
    scale = rand(.25, 2)
    scale=0.5
    if new_ar < 1:
        nh = int(scale*h)
        nw = int(nh*new_ar)
    else:
        nw = int(scale*w)
        nh = int(nw/new_ar)
    image = image.resize((nw,nh), Image.BICUBIC)

    # place image
    dx = int(rand(0, w-nw))
    dy = int(rand(0, h-nh))
    new_image = Image.new('RGB', (w,h), (128,128,128))
    new_image.paste(image, (dx, dy))
    image = new_image
    # flip image or not
    flip = rand()<.5
    if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)

    # distort image
    hue = rand(-hue, hue)
    sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)
    val = rand(1, val) if rand()<.5 else 1/rand(1, val)
    x = rgb_to_hsv(np.array(image)/255.)
    x[..., 0] += hue
    x[..., 0][x[..., 0]>1] -= 1
    x[..., 0][x[..., 0]<0] += 1
    x[..., 1] *= sat
    x[..., 2] *= val
    x[x>1] = 1
    x[x<0] = 0
    image_data = hsv_to_rgb(x) # numpy array, 0 to 1

    # correct boxes
    box_data = np.zeros((max_boxes,5))

    if len(box)>0:
        #np.random.shuffle(box)

        box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx
        box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy
        if flip: box[:, [0,2]] = w - box[:, [2,0]]
        box[:, 0:2][box[:, 0:2]<0] = 0
        box[:, 2][box[:, 2]>w] = w
        box[:, 3][box[:, 3]>h] = h
        box_w = box[:, 2] - box[:, 0]
        box_h = box[:, 3] - box[:, 1]
        box = box[np.logical_and(box_w>1., box_h>1.)] # discard invalid box
        if len(box)>max_boxes: box = box[:max_boxes]
        box_data[:len(box)] = box
    #print(box_data)
    return image_data, box_data

def get_anchors(anchors_path):
    '''loads the anchors from a file'''
    with open(anchors_path) as f:
        anchors = f.readline()
    anchors = [float(x) for x in anchors.split(',')]
    return np.array(anchors).reshape(-1, 2)

def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2):
    '''create the training model'''
    K.clear_session() # get a new session
    image_input = Input(shape=(None, None, 3))
    h, w = input_shape
    num_anchors = len(anchors)

    y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \
        num_anchors//3, num_classes+5)) for l in range(3)]

    model_body = yolo_body(image_input, num_anchors//3, num_classes)
    print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))

    if load_pretrained:
        model_body.load_weights(WEIGHT_path, by_name=True, skip_mismatch=True)
        print('Load weights {}.'.format(WEIGHT_path))
        if freeze_body in [1, 2]:
            # Freeze darknet53 body or freeze all but 3 output layers.
            num = (185, len(model_body.layers)-3)[freeze_body-1]
            for i in range(num): model_body.layers[i].trainable = False
            print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))

    model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
        arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(
        [*model_body.output, *y_true])
    model = Model([model_body.input, *y_true], model_loss)

    return model

def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2):
    '''create the training model, for Tiny YOLOv3'''
    K.clear_session() # get a new session
    image_input = Input(shape=(None, None, 3))
    h, w = input_shape
    num_anchors = len(anchors)

    y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \
        num_anchors//2, num_classes+5)) for l in range(2)]

    model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes)
    print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))

    if load_pretrained:
        model_body.load_weights(WEIGHT_path, by_name=True, skip_mismatch=True)
        print('Load weights {}.'.format(WEIGHT_path))
        if freeze_body in [1, 2]:
            # Freeze the darknet body or freeze all but 2 output layers.
            num = (20, len(model_body.layers)-2)[freeze_body-1]
            for i in range(num): model_body.layers[i].trainable = False
            print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))

    model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
        arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})(
        [*model_body.output, *y_true])
    model = Model([model_body.input, *y_true], model_loss)

    return model

def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
    '''data generator for fit_generator'''
    n = len(annotation_lines)
    i = 0
    while True:
        image_data = []
        box_data = []
        for b in range(batch_size):
            if i==0:
                np.random.shuffle(annotation_lines)
            image, box = get_random_data(annotation_lines[i], input_shape, random=True)
            image_data.append(image)
            box_data.append(box)
            i = (i+1) % n

        image_data = np.array(image_data)
        box_data = np.array(box_data)
        y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
        yield [image_data, *y_true], np.zeros(batch_size)
def data_generator2(annotation_lines, batch_size, input_shape, anchors, num_classes):
    '''data generator for fit_generator'''
    n = len(annotation_lines)
    i = 136

    image_data = []
    box_data = []
    for b in range(batch_size):
            #if i==0:
                #np.random.shuffle(annotation_lines)
            image, box = get_random_data(annotation_lines[i], input_shape, random=True)
            image_data.append(image)
            box_data.append(box)
            i = (i+1) % n

    image_data = np.array(image_data)
    box_data = np.array(box_data)
    y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
    return [image_data, *y_true], np.zeros(batch_size)
def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):
    n = len(annotation_lines)
    if n==0 or batch_size<=0: return None
    return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)

if __name__ == '__main__':
    K.clear_session()
    _main()
import gc; gc.collect()

max_stars_repo_name: plasticanne/unity-object-detection-zoo

max_issues_repo_name: plasticanne/unity-object-detection-zoo

max_forks_repo_name: plasticanne/unity-object-detection-zoo


text:
import os
import cv2
import numpy as np
from PIL import Image as pil_image
from skimage.transform import resize
import matplotlib.pyplot as plt
cancer_type = ['gbm', 'hnsc', 'lgg', 'lung']
def processimg(imgpath):
    im_cv2 = cv2.imread(imgpath)
    im_cv2 = np.flip(im_cv2, 2)
    return im_cv2
for det in cancer_type:
    for i in range(1, 9):
        program_name = 'python'
        test_script_path = ' test.py'
        model_args = ' --model_path'
        model_path = ' unet_cellcancer_1_49.pkl'
        data_args = ' --dataset'
        data_type = ' cellcancer'
        img_path_args = ' --img_path '
        img_path = '/home/neuron/Desktop/Donghao/cellsegmentation/segmentation-test-images/test_original/' + det + '/test-images/image0' + str(i) + '.png'
        output_args = ' --out_path '
        result_path = '/home/neuron/Desktop/Donghao/cellsegmentation/tmp_testing/result_' + det + '_' + str(i) + '.png'
        pycmd = program_name + test_script_path + model_args + model_path + data_args + data_type + img_path_args + img_path + output_args + result_path
        cur_test_img = processimg(img_path)
        if cur_test_img.shape[0] == 500:
            cur_test_img_resize = resize(cur_test_img, (512, 512, 3), mode='reflect')
            cur_test_img_resize = cur_test_img_resize * 255
            cur_test_img_resize = cur_test_img_resize.astype('uint8')
            cur_test_img_resize_save = pil_image.fromarray(cur_test_img_resize)
            cur_test_img_resize_save.save(result_path)

        elif cur_test_img.shape[0] == 600:
            cur_test_img_resize = resize(cur_test_img, (640, 640, 3), mode='reflect')
            cur_test_img_resize = cur_test_img_resize * 255
            cur_test_img_resize = cur_test_img_resize.astype('uint8')
            cur_test_img_resize_save = pil_image.fromarray(cur_test_img_resize)
            cur_test_img_resize_save.save(result_path)


text:
'''Player class to record stats for individual players
'''
import numpy as np

class Player:
    '''Dosctring TODO
    THIS IS NOT A VERY GENERALIZABLE MODEL IF YOU KNOW THINGS ABOUT FOOTBALL
    and that's okay
    '''
    def __init__(self, name=None, yards=120, touchdowns=5, safety=1,
                 interceptions=0, field_goals=3):
        self.name = name
        self.yards = yards
        self.touchdowns = touchdowns
        self.safety = safety
        self.interceptions = interceptions
        self.field_goals = field_goals

    def get_points(self):
        '''Gets points scored by the player from stats
        '''
        td_points = 6 * self.touchdowns
        safety_points = 2 * self.safety
        field_goal_points = 3 * self.field_goals

        total_points = td_points + safety_points + field_goal_points
        return total_points

class Quarterback(Player):
    '''Override certain parameters of the default Player class and add some
    functionality unique to quarterbacks
    '''
    def __init__(self, name=None, yards=130, touchdowns=5, completed_passes=20,
                 interceptions=4, safety=None, field_goals=None):
        super().__init__(name=name, yards=yards, touchdowns=touchdowns,
                         safety=safety, interceptions=interceptions)
        self.completed_passes = completed_passes

    def passing_score(self):
        '''This is a random formula... FYI
        '''
        score = self.completed_passes - (2 * self.interceptions)
        return score

# TODO - refine the default player stats and/or make a defensive player default
# with number of tackles, sacks, interceptions etc.

class DefensivePlayer(Player):
    '''Override certain parameters of default Player class and add
    unique parameters to a defensive player
    '''
    def __init__(self, name=None, touchdowns=0, interceptions=0, safety=0, sacks=0,
                 tackles=0, fumble_recovery=0):
        super().__init__(name=name, touchdowns=touchdowns, interceptions=interceptions,
                         safety=safety)
        self.sacks = sacks
        self.tackles = tackles
        self.fumble_recovery = fumble_recovery

    def defensive_score(self):
        '''This is a random formula for a defensive players performance
        '''

        score = (self.sacks
                + (self.touchdowns * 6)
                + (self.fumble_recovery * 1.5)
                + (self.tackles )
                + (self.safety * 2)
        )
        return score

if __name__ == "__main__":

    offensive_player = Player(name='Trent', yards=100, touchdowns=2, safety=0,
                              interceptions=0, field_goals=0)
    print(offensive_player.name)
    print(offensive_player.get_points())

    quarterback = Quarterback(name='Trent', yards=300, touchdowns=3, completed_passes=22,
                interceptions=1, safety=0, field_goals=0)
    print(quarterback.name)
    print(quarterback.passing_score())

    defensive_player = DefensivePlayer(name='Trent', touchdowns=1, interceptions=2, safety=1,
                                       fumble_recovery=1, sacks=10)
    print(defensive_player.name)
    print(defensive_player.defensive_score())

max_stars_repo_name: tmbern/DS-OOP-Review

max_issues_repo_name: tmbern/DS-OOP-Review

max_forks_repo_name: tmbern/DS-OOP-Review


text:
"""
demo_segmentation.py

    (1) Global thresholding

    (2) Spatially adaptive binary thresholding

    (3) Moving average binary thresholding

    (4) Region growing segmentation

    (5) color segmentation

    (6) kmeans segmentation

"""

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.colors as colors
import matplotlib.image as mpimg
from segmentation_utils import cmap_discretize, GlobalThresholding, \
    SpatiallyAdaptiveBinaryThresholding, MovigAverageBinaryThresholding, \
    EstimateIlluminationProfile, RegionGrowingSegmentation, ColorSegmentation, KmeansSegmentation

fontsize = 32;

# load sample data
bpp = 8; # bits per pixel
N_levels = 2 ** bpp; # number of intensity levels

# cells
image = np.array(mpimg.imread('sample_data/cells.tif'));
image_cells = image.astype(np.uint8);

# coins
image = np.array(mpimg.imread('sample_data/coins.tif'));
image_coins = image.astype(np.uint8);

# text
image = np.array(mpimg.imread('sample_data/text.tif'));
image_text = image.astype(np.uint8);
intensity_grad = np.linspace(1,250, image_text.shape[1]);
intensity_grad = intensity_grad / intensity_grad.max();
image_text_grad = image_text * intensity_grad; # adding intensity gradient to image
image_text_grad[image_text_grad < 0] = 0;
image_text_grad[image_text_grad > N_levels - 1] = N_levels - 1;

# nebula
image = np.array(mpimg.imread('sample_data/nebula.jpeg'));
image_nebula = image.astype(np.uint8);

# brain
image = np.array(mpimg.imread('sample_data/brain.tif'));
image_brain = image.astype(np.uint8);

# Global thresholding
image = image_cells;
kernel_sigma = 0;
N_classes = 2;
step = 1;
mask_class2 = GlobalThresholding(image, kernel_sigma, N_levels, N_classes, step);

image = image_cells;
N_classes = 3;
step = 1;
mask_class3 = GlobalThresholding(image, kernel_sigma, N_levels, N_classes, step);

fig_width, fig_height = 40, 20;
fig, ((ax1, ax2, ax3)) = plt.subplots(nrows=1, ncols=3, figsize=(fig_width, fig_height));
ax1.imshow(image, cmap='gray')
ax1.set_title("image", fontsize = fontsize)
ax1.set_axis_off()
discretized_jet = cmap_discretize(2);
img = ax2.imshow(mask_class2, cmap=discretized_jet);
plt.colorbar(img, ax=ax2)
ax2.set_title("segmentation", fontsize = fontsize)
ax2.set_axis_off()
discretized_jet = cmap_discretize(3);
img = ax3.imshow(mask_class3, cmap=discretized_jet);
plt.colorbar(img, ax=ax3)
ax3.set_title("segmentation", fontsize = fontsize)
ax3.set_axis_off()
plt.tight_layout()

# Spatially adaptive binary thresholding
image = image_cells;
kernel_sigma = 0;
a = 4;
b = 0.5;
mask = SpatiallyAdaptiveBinaryThresholding(image, kernel_sigma, a, b);

fig_width, fig_height = 30, 20;
fig, ((ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(fig_width, fig_height));
ax1.imshow(image, cmap='gray')
ax1.set_title("image", fontsize = fontsize)
ax1.set_axis_off()
cmap = colors.ListedColormap(['black', 'white']);
img = ax2.imshow(mask, cmap=cmap);
ax2.set_title("segmentation", fontsize = fontsize)
ax2.set_axis_off()
plt.tight_layout()

# Moving average binary thresholding
image = image_text_grad;
kernel_sigma = 31;
illumination_profile = EstimateIlluminationProfile(image, kernel_sigma);

fig_width, fig_height = 30, 20;
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(fig_width, fig_height));
ax1.imshow(image, cmap='gray')
ax1.set_title("image", fontsize = fontsize)
ax1.set_axis_off()
ax2.imshow(illumination_profile, cmap='gray')
ax2.set_title("illumination image", fontsize = fontsize)
ax2.set_axis_off()
ax3.imshow(image / illumination_profile, cmap='gray')
ax3.set_title("image illumination correction", fontsize = fontsize)
ax3.set_axis_off()

image = image_text_grad;
kernel_sigma = 0;
n = 40;
b = 0.8;
mask =  MovigAverageBinaryThresholding(image / illumination_profile, kernel_sigma, n, b);

cmap = colors.ListedColormap(['black', 'white']);
img = ax4.imshow(mask, cmap=cmap);
ax4.set_title("segmentation", fontsize = fontsize)
ax4.set_axis_off()
plt.tight_layout()

# Region growing segmentation
image = image_coins;
kernel_sigma = 0;
seed_row = 120;
seed_col = 150;
Niter = 100;
sim_threshold = 0.92;
mask = RegionGrowingSegmentation(image, kernel_sigma, seed_row, seed_col, Niter, sim_threshold);

fig_width, fig_height = 30, 20;
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(fig_width, fig_height));
ax1.imshow(image, cmap='gray')
ax1.set_title("image", fontsize = fontsize)
ax1.set_axis_off()
cmap = colors.ListedColormap(['black', 'white']);
img = ax2.imshow(mask, cmap=cmap);
ax2.set_title("segmentation", fontsize = fontsize)
ax2.set_axis_off()
ax3.imshow(image * mask, cmap='gray')
ax3.set_title("image masked", fontsize = fontsize)
ax3.set_axis_off()
plt.tight_layout()

# color segmentation
image = image_nebula;
kernel_sigma = 0;
# color_seg = (243, 92, 231); # pink
color_seg = (8, 45, 134); # blue
sim_threshold = 0.9;
mask = ColorSegmentation(image, kernel_sigma, color_seg, sim_threshold);

fig_width, fig_height = 30, 20;
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(fig_width, fig_height));
ax1.imshow(image)
ax1.set_title("image", fontsize = fontsize)
ax1.set_axis_off()
cmap = colors.ListedColormap(['black', 'white']);
img = ax2.imshow(mask, cmap=cmap);
ax2.set_title("segmentation", fontsize = fontsize)
ax2.set_axis_off()
ax3.imshow(image * mask[:, :, None])
ax3.set_title("image masked", fontsize = fontsize)
ax3.set_axis_off()
plt.tight_layout()

# kmeans segmentation
image = image_brain;
kernel_sigma = 1;
N_classes = 3;
N_iter = 10;
tol = 10e-6;
mask = KmeansSegmentation(image, kernel_sigma, N_classes, N_iter, tol);

fig_width, fig_height = 30, 20;
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(fig_width, fig_height));
ax1.imshow(image)
ax1.set_title("image", fontsize = fontsize)
ax1.set_axis_off()
discretized_jet = cmap_discretize(N_classes);
img = ax2.imshow(mask, cmap=discretized_jet);
plt.colorbar(img, ax=ax2)
ax2.set_title("segmentation", fontsize = fontsize)
ax2.set_axis_off()
plt.tight_layout()

max_stars_repo_name: almostdutch/image-segmentation

max_issues_repo_name: almostdutch/image-segmentation

max_forks_repo_name: almostdutch/image-segmentation


text:
import sys
import typing
import numpy as np

from ConfigSpace.configuration_space import Configuration

from smac.initial_design.initial_design import InitialDesign
from smac.initial_design.single_config_initial_design import SingleConfigInitialDesign
from smac.intensification.intensification import Intensifier

from smac.tae.execute_ta_run import ExecuteTARun
from smac.stats.stats import Stats
from smac.utils.io.traj_logging import TrajLogger
from smac.scenario.scenario import Scenario
from smac.tae.execute_ta_run import StatusType
from smac.runhistory.runhistory import RunHistory
from smac.utils import constants

__author__ = "Marius Lindauer"
__copyright__ = "Copyright 2016, ML4AAD"
__license__ = "3-clause BSD"

class MultiConfigInitialDesign(InitialDesign):

    def __init__(self,
                 tae_runner: ExecuteTARun,
                 scenario: Scenario,
                 stats: Stats,
                 traj_logger: TrajLogger,
                 runhistory: RunHistory,
                 rng: np.random.RandomState,
                 configs: typing.List[Configuration],
                 intensifier: Intensifier,
                 aggregate_func: typing.Callable
                 ):
        '''
        Constructor

        Arguments
        ---------
        tae_runner: ExecuteTARun
            target algorithm execution object
        scenario: Scenario
            scenario with all meta information (including configuration space)
        stats: Stats
            statistics of experiments; needed in case initial design already exhaust the budget
        traj_logger: TrajLogger
            trajectory logging to add new incumbents found by the initial design
        runhistory: RunHistory
            runhistory with all target algorithm runs
        rng: np.random.RandomState
            random state
        configs: typing.List[Configuration]
            list of initial configurations
        intensifier: Intensifier
            intensification object to issue a racing to decide the current
            incumbent
        aggregate_func: typing:Callable
            function to aggregate performance of a configuration across instances

        '''
        super().__init__(tae_runner=tae_runner,
                         scenario=scenario,
                         stats=stats,
                         traj_logger=traj_logger,
                         rng=rng)

        self.configs = configs
        self.intensifier = intensifier
        self.runhistory = runhistory
        self.aggregate_func = aggregate_func

    def run(self) -> Configuration:
        '''
            runs the initial design given the configurations from self.get_configs

            Returns
            -------
            incumbent: Configuration()
                initial incumbent configuration
        '''
        configs = self.configs

        self.traj_logger.add_entry(train_perf=2**31,
                                   incumbent_id=1,
                                   incumbent=configs[0])

        if len(set(configs)) > 1:
            # intensify will skip all challenger that are identical with the incumbent;
            # if <configs> has only identical configurations,
            # intensifiy will not do any configuration runs
            # (also not on the incumbent)
            # therefore, at least two different configurations have to be in <configs>
            inc, inc_perf = self.intensifier.intensify(challengers=set(configs[1:]),
                                                       incumbent=configs[0],
                                                       run_history=self.runhistory,
                                                       aggregate_func=self.aggregate_func)

        else:
            self.logger.debug("All initial challengers are identical")
            scid = SingleConfigInitialDesign(tae_runner=self.tae_runner,
                                             scenario=self.scenario,
                                             stats=self.stats,
                                             traj_logger=self.traj_logger,
                                             rng=self.rng)
            def get_config():
                return configs[0]
            scid._select_configuration = get_config
            scid.run()
            inc = configs[0]

        return inc