Ejemplo n.º 1
0
Archivo: plot.py Proyecto: sshi27/plot
    def work(data):
      if isinstance(data, str):
        try:
          data = rapidjson.loads(data)
        except Exception as e1:
          try:
            data = ast.literal_eval(data)
          except Exception as e2:
            print(e1)
            print(e2)
            raise Exception("Please input a valid json or python object string")

      if not isinstance(data, dict):
        raise Exception("Please input a valid json or python object string, or an object")

      plt.rc('text', usetex=data.get('usetex', False))

      type = data.get('type', None)
      if type == 'bar':
        ParallelBars().draw(data, fig, ax)
      elif type == 'line':
        MultipleLines().draw(data, fig, ax)
      elif type == 'cdf':
        Cdf().draw(data, fig, ax)
      elif type == 'annotated_bar':
        AnnotatedBars().draw(data, fig, ax)
      elif type == 'violin':
        Violin().draw(data, fig, ax)
      elif type == 'heatmap':
        HeatMap().draw(data, fig, ax)
      else:
        raise Exception("Please specify type in json. Supported: bar, line, cdf")
Ejemplo n.º 2
0
 def process_batter(self, batterId, px, pz, pitchType, pitchResult,
                    paResult, hand):
     try:
         batterId = int(batterId)
         px, pz = float(px), float(pz)
     except:
         return
     if batterId in self.season:
         self.season[batterId].process_pitch(px, pz, pitchType, pitchResult,
                                             paResult, hand)
     else:
         self.season[batterId] = HeatMap()
         self.season[batterId].process_pitch(px, pz, pitchType, pitchResult,
                                             paResult, hand)
Ejemplo n.º 3
0
def process_frame(img):
    car_boxes = find_cars(img, clf, scaler, parameter)

    from heatmap import HeatMap
    heatmap = HeatMap(threshold=3)
    heatmap.add_heat(car_boxes)
    heatmap.apply_threshold()

    from scipy.ndimage.measurements import label
    labels = label(heatmap.get_headmap())

    label_box_img = draw_labeled_bboxes(np.copy(img), labels)

    return label_box_img
Ejemplo n.º 4
0
def execute():
    mongo = Mongo('ztis', 'ztis-test')
    # mongo.cloneCollection('ztis-test')
    # mongo.removeNonEnglishArticles()
    # mongo.removeDuplicates()

    # heatMap = HeatMap(mongo.mapReduceLocations())
    # heatMap.setMap("map.png")

    mongo.collection = mongo.findCustom(
        {"locations": {
            "$in": ["Poland", "PL"]
        }})

    heatMap = HeatMap(mongo.mapReduceLocations())
    heatMap.setMap("map2.png")
Ejemplo n.º 5
0
def video_stream():

    # construct the argument parse and parse the arguments
    # ap = argparse.ArgumentParser()
    # ap.add_argument("-p", "--shape-predictor", required=True,
    #	help="path to facial landmark predictor")
    # ap.add_argument("-r", "--picamera", type=int, default=-1,
    #	help="whether or not the Raspberry Pi camera should be used")
    # args = vars(ap.parse_args())

    # initialize the video stream and allow the cammera sensor to warmup
    global sup_esq, sup_dir, inf_esq, inf_dir, vitrine_larg_altu, divisao_colum_row, comecar_leitura_unica

    sup_esq = (330, 10)
    sup_dir = (-330, 10)
    inf_esq = (330, -170)
    inf_dir = (-330, -170)
    vitrine_larg_altu = None
    comecar_leitura_unica = False

    print("[INFO] Preparando a câmera...")
    cap = cv2.VideoCapture(1)

    set_resolution_480(cap)

    time.sleep(1.0)

    land_mark = LandMark()
    head_pose = HeadPose(cv2)
    heatmap_global = HeatMap("Global")
    heatmap_usuario = HeatMap("Instantaneo")

    # Loop de frames do video
    while True:
        # Captura o frame
        ret, frame = cap.read()

        key = cv2.waitKey(100) & 0xFF
        # if the `q` key was pressed, break from the loop
        if key == ord("q"):
            break
        if key == ord("s"):
            heatmap_global.salve_map()
            heatmap_usuario.salve_map()
            print("[INFO] HeatMap salvo!!")

        if key == ord("r"):
            heatmap_usuario.reset_map()
            # heatmap_global.reset_map()
            print("[INFO] HeatMap resetaqdo!!")

        if key == ord("b"):
            comecar_leitura_unica = True
            print("[INFO] Leitura de usuário começado!!")
        if key == ord("e"):
            comecar_leitura_unica = False
            print("[INFO] Leitura de usuário parado!!")

        if (head_pose.vitrine_points != None):
            if key == ord("7"):
                sup_esq = head_pose.vitrine_points
                print("[INFO] Ponto superior esquerdo capturado!!")
            if key == ord("9"):
                sup_dir = head_pose.vitrine_points
                print("[INFO] Ponto superior direito capturado!!")
            if key == ord("1"):
                inf_esq = head_pose.vitrine_points
                print("[INFO] Ponto inferor esquerdo capturado!!")
            if key == ord("3"):
                inf_dir = head_pose.vitrine_points
                print("[INFO] Ponto inferior direito capturado!!")

        if key == ord("5"):
            sup_esq = None
            sup_dir = None
            inf_esq = None
            inf_dir = None
            vitrine_larg_altu = None
            print("[INFO] Calibração resetada!!")

        if key == ord("p"):
            print("[INFO] Sup Esquerda:")
            print(sup_esq)
            print("[INFO] Sup Direita:")
            print(sup_dir)
            print("[INFO] Inf Esquerda:")
            print(inf_esq)
            print("[INFO] Inf Direita:")
            print(inf_dir)
            print("[INFO] Largura ; Altura:")
            print(vitrine_larg_altu)

        if key == ord("c"):
            if (sup_esq != None and sup_dir != None and inf_esq != None
                    and inf_dir != None):
                vitrine_larg_altu = calibrar_vitrine(sup_esq, sup_dir, inf_esq,
                                                     inf_dir)
                divisao_colum_row = [0, 0]
                divisao_colum_row[0] = int(vitrine_larg_altu[0] /
                                           heatmap_global.width)
                divisao_colum_row[1] = int(vitrine_larg_altu[1] /
                                           heatmap_global.higth)
                print("[INFO] Calibração feita!!")

        if (None is frame):
            print("[ERROR] FALHA NA CAPTURA DO VIDEO!!")
            print("[ERROR] TENTANDO NOVAMENTE")
            continue

        frame = cv2.flip(frame, 1)

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        land_mark.set_frame(gray)
        head_pose.set_frame(gray)

        mapa = land_mark.get_land_mark()

        primeiro_elemento = True

        if (mapa.__len__() != 0):  # Encontrou alguns rostos

            # for face in land_mark.shape:  # Loop pelos rostos encontrados
            for face in mapa:  # Loop pelos rostos encontrados
                for (x, y) in face:
                    cv2.circle(frame, (int(x), int(y)), 2, (0, 0, 255), -1)

                points = head_pose.get_line_points(face)

                if (points == None):
                    continue

                cv2.arrowedLine(frame, points[0], points[1], (255, 0, 0), 2)

                # Adicionar regra de tempo para saber a partir de quanto tempo começa a contar
                if (head_pose.vitrine_points != None):

                    if (sup_esq != None and vitrine_larg_altu != None):
                        coordenada_heat = global2heat(sup_esq,
                                                      head_pose.vitrine_points)
                        heatmap_global.incrementa(coordenada_heat)

                        if (primeiro_elemento and comecar_leitura_unica):
                            primeiro_elemento = False
                            heatmap_usuario.incrementa(coordenada_heat)
        else:
            heatmap_usuario.reset_map()

        # show the frame
        cv2.imshow("Frame", frame)

    heatmap_global.salve_map()
    heatmap_usuario.salve_map()

    cv2.destroyAllWindows()
    cap.release()

    return
Ejemplo n.º 6
0
        loss_value = loss_fn(label, logits)

        lastc = model.last_conv_value

    guide = loss_tape.gradient(loss_value, image)
    grads = logits_tape.gradient(logits, lastc)

    GAP_pool = tf.keras.layers.AveragePooling2D(
        (lastc.shape[1], lastc.shape[2]), padding='valid',
        strides=(1, 1))(grads)

    grad_c = tf.zeros(lastc.shape[1:3], tf.float32)
    for idx in range(0, GAP_pool.shape[3]):
        grad_c = tf.nn.relu(grad_c +
                            lastc[0, :, :, idx] * GAP_pool[0, :, :, idx])

grad_cam, heatmap = HeatMap(grad_c, guide, dims=2)

#show with heatmap
image = image.numpy() * 255  #rescale to original
image = np.squeeze(np.uint8(image))

RGB_img = cv.cvtColor(image, cv.COLOR_GRAY2BGR)  #convert to "RGB" (size)

heatmap_img = cv.applyColorMap(np.uint8(heatmap), cv.COLORMAP_JET)

fin = cv.addWeighted(heatmap_img, 0.7, RGB_img, 0.3, 0)

plt.imshow(fin)
#cv.imshow('image_w_heatmap', fin)
test_images = list(
    map(lambda img: read_image(img), glob.glob('./test_images/*.jpg')))

model_file = './data/model.p'
print('Loading classifier model from file', model_file)
clf, scaler = load_model(model_file)
parameter = FeatureParameter()

box_imgs = []
for img in test_images:
    car_boxes = find_cars(img, clf, scaler, parameter)

    car_boxes_img = draw_cars(img, car_boxes)
    box_imgs.append(car_boxes_img)

    from heatmap import HeatMap

    heatmap = HeatMap(threshold=2)
    heatmap.add_heat(car_boxes)
    heatmap.apply_threshold()
    heatmap_img = heatmap.get_headmap()

    from scipy.ndimage.measurements import label
    labels = label(heatmap_img)

    box_imgs.append(heatmap_img)
    label_box_img = draw_labeled_bboxes(np.copy(img), labels)
    box_imgs.append(label_box_img)

plot_images(box_imgs)
Ejemplo n.º 8
0
# The extractor gets the data
toilet_extr = ToiletExtractor(
    './data/oeffentlichetoilettenmuenchen2016-06-28.csv', 'latitude',
    'longitude')

# The renderer deals with visual aspects of the map
renderer = DefaultRenderer(center=marienplatz,
                           zoom=12,
                           opacity=0.35,
                           color_scale=custom_color_scale,
                           tiles='cartodbdark_matter')

# Create a new heatmap
h_map = HeatMap(None,
                geo_json,
                filename='toilet',
                square_size=500,
                num_threads=100,
                load_intermediate_results=True)
h_map.generate(toilet_extr.get_value)
h_map.normalize()
# Generate the polygon areas within 1km of a public toilet
h_map.generate_polygon(lambda v: v.get('lin_value', 999) < 1.0,
                       dash_array=[5, 5],
                       color='#0ef',
                       opacity=0.5,
                       weight=2)
# Render and save
h_map.render(renderer, before_saving=toilet_extr.add_markers)
Ejemplo n.º 9
0
def reset():
    global clicks_hm
    global moves_hm
    clicks_hm = HeatMap(grid_resolution)
    moves_hm = HeatMap(grid_resolution)
Ejemplo n.º 10
0
from threading import Lock
from flask import session, request, copy_current_request_context

from datetime import datetime
import re

from heatmap import HeatMap
import json

grid_resolution = (50, 50)

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread_lock = Lock()
clicks_hm = HeatMap(grid_resolution)
moves_hm = HeatMap(grid_resolution)


def bck():
    global clicks_hm
    global moves_hm
    global thread_lock

    while True:
        socketio.sleep(2)
        with thread_lock:
            c = clicks_hm()
            m = moves_hm()

            hms = [c.tolist(), m.tolist()]
Ejemplo n.º 11
0
    return contents


def bikable_zone(unit):
    if 'original_value' not in unit or unit.get('original_value') is None:
        return False
    return unit.get('original_value') > 1.5 and unit.get('bike_val') < 25


renderer = DefaultRenderer(center=home,
                           zoom=12,
                           opacity=0.5,
                           label=make_label,
                           color_scale=custom_color_scale)
h_map = HeatMap(home,
                geo_json,
                filename='bike_vs_ubahn',
                square_size=800,
                num_threads=100,
                load_intermediate_results=True)
h_map.generate(calc_time)
h_map.normalize(normalize_log2_scale)
h_map.generate_polygon(bikable_zone,
                       color='#0012b3',
                       opacity=0.6,
                       weight=5,
                       dash_array=[1, 6])
h_map.render(
    renderer,
    before_saving=lambda r, _: r.add_circle(home, color='#0012b3', radius=20))
Ejemplo n.º 12
0
    def update_heatmap(self):
        if self.heatmap is None:
            self.heatmap = HeatMap(self.cropped_image_size)

        self.heatmap.add_detections(self.detections)
        self.heatmap.update_map()
Ejemplo n.º 13
0
 def setUp(self):
     self.rows = load(open(test_data, 'r'))
     self.heatmap = HeatMap()
     for idx in range(5):
         params = self.rows[idx]
         self.heatmap.process_pitch(*params)
Ejemplo n.º 14
0
with open('./geo/muenchen.json', 'r') as fp:
    geo_json = json.load(fp)


def calc_time(pt1, pt2):
    """ Calculate the time to get somewhere by UBahn """
    t_ubahn = mvg.average_time_between(pt1, pt2, datetime.now())
    if not t_ubahn:
        return None
    value = int(t_ubahn / 60.0)
    # Since the value will be normalized, we save it also on a separate key to show it on the label
    return {'value': value, 'time': value}


renderer = DefaultRenderer(center=home,
                           zoom=12,
                           color_scale=color,
                           label=label)
h_map = HeatMap(home,
                geo_json,
                square_size=250,
                filename='mvg',
                load_intermediate_results=True)
h_map.generate(calc_time)
# Normalize on a log2 scale
h_map.normalize(lambda v, _1, _2: log2(v))
# Then again on a 0 to 1 range
h_map.normalize()
h_map.render(renderer)