text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline in source files, comments, and docstrings.
"""
"""

# from wavestate import declarative
# import collections
# import numpy as np

try:
    import pygraphviz as pgv
except ImportError:
    pass

class GraphPlottingAlgorithm(object):
    def __init__(self, pa=None, pbg=None, bg=None):
        self.pa = pa
        if bg is None:
            self.bg = self.pa.bg
        if pbg is None:
            self.pbg = self.bg.pbg
        return

    def graph_bond_graph(self, fname):
        G = pgv.AGraph()
        # G.graph_attr['newrank'] = "True"
        edge_str = []
        # TODO, sort to make the plotting stable
        for m_fr, to_set in self.bg.bond_seq.items():
            m_fr = self.pbg.path_str(m_fr[0]) + m_fr[1]
            for m_to in to_set:
                m_to = self.pbg.path_str(m_to[0]) + m_to[1]
                G.add_edge(m_fr, m_to)
                edge_str.append((m_fr, m_to))
        for obj, pset in self.bg.object_ports.items():
            m_nodes = []
            oname = self.pbg.path_str(obj)
            for pname in pset:
                m_nodes.append(oname + pname)
            G.add_subgraph(m_nodes, "cluster_" + oname)
        edge_str.sort()
        # ic(edge_str)
        G.draw(fname, prog="dot")

    def graph_DC_link_matrix(self, fname, cluster_links=False):
        nmap, SREIO = self.pa.dc.SREIO_DC(
            map_nodes=True,
            subtract_1=True,
        )
        (seq, req, edges, inputs, outputs) = SREIO

        # TODO, sort to make the plotting stable
        import pygraphviz as pgv

        edge_str = []
        G = pgv.AGraph(directed=True)
        G.graph_attr["newrank"] = "True"
        for (m_fr, m_to), kmat in edges.items():
            if m_fr == m_to:
                # suppress self-edges
                continue
            G.add_edge(m_fr, m_to)
            edge_str.append((m_fr, m_to, kmat))
        # ic(pa.bg.object_linkages)
        if cluster_links:
            for obj, pset in self.bg.object_linkages.items():
                m_nodes = []
                oname = self.pbg.path_str(obj)
                for pname in pset:
                    m_nodes.append(oname + "+" + pname)
                G.add_subgraph(m_nodes, "cluster_" + oname)
        edge_str.sort()
        # ic(edge_str)
        G.draw(fname, prog="dot")

    def graph_MM_link_matrix(
        self,
        fname,
        color_chains={},
        color_cavities={},
    ):
        SRE = self.pa.mm.SRE_linkage()
        seq, req, edges = SRE

        # TODO, sort to make the plotting stable
        import pygraphviz as pgv

        G = pgv.AGraph(directed=True)
        G.graph_attr["newrank"] = "True"
        for (m_fr, m_to), weight in edges.items():
            if m_fr == m_to:
                # suppress self-edges
                continue
            if weight is not None:
                G.add_edge(m_fr, m_to, label=str(weight))
            else:
                G.add_edge(m_fr, m_to)

        for color, chain in color_chains.items():
            n_fr = chain[0]
            for n_to in chain[1:]:
                G.add_edge(n_fr, n_to, color=color)
                n_fr = n_to

        # TODO, don't use internal API for the cavity targets?
        for target, color in color_cavities.items():
            target_oP = self.pbg.referred_vtup(target)
            chain = list(self.pa.mm.cavity_targets[target_oP])
            # form a loop
            chain = chain + [chain[0]]

            n_fr = chain[0]
            for n_to in chain[1:]:
                G.add_edge(n_fr, n_to, color=color)
                n_fr = n_to

        # ic(pa.bg.object_linkages)
        G.draw(fname, prog="dot")

max_stars_repo_name: wavestate/wavestate-model

max_issues_repo_name: wavestate/wavestate-model

max_forks_repo_name: wavestate/wavestate-model


text:
import numpy as np
nb_classes = 6
data = [[2, 3, 4, 0]]

def indices_to_one_hot(data, nb_classes):
    """Convert an iterable of indices to one-hot encoded labels."""
    targets = np.array(data).reshape(-1)
    return np.eye(nb_classes)[targets]

def one_hot_to_indices(data):
    indices = []
    for el in data:
        indices.append(list(el).index(1))
    return indices

hot = indices_to_one_hot(data, nb_classes)
indices = one_hot_to_indices(hot)
print(hot)
print(data)
print(indices)

ext: py

reason: import numpy


text:
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import os
from time import gmtime, strftime
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np

from utils import *

os.environ["CUDA_VISIBLE_DEVICES"]="1"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model_type = 'mobilenet_v2'   # 'mobilenet_v1' 'mobilenet_v2' 'mobilenet_v2_torchhub'
pretrained = False                     # load imagenet weight (only for 'mobilenet_v2_torchhub')
experiment_dir = 'pretrained_baseline_{}_{}_sgdl2reg1e-3'.format(model_type, strftime("%Y%m%d%H%M", gmtime()))
os.mkdir(experiment_dir)
checkpoint = None
teacher_checkpoint = './experiments/pretrained_mobilenet_v2_best/checkpoint_best.pt'
input_size = 224
n_classes = 120

# optimization parameters
batch_size = 32
n_epochs = 160
learning_rate = 2e-3         # 1e-4 for finetuning, 1e-3 (?) for training from scratch
weight_decay = 0 #1e-3          # l2 regularization

def run_validation(model, valid_dataloader):
    model.eval()

    loss_func = nn.CrossEntropyLoss()
    acc_list, loss_list = [], []
    with torch.no_grad():
        for i, (inputs, labels) in enumerate(tqdm(valid_dataloader)):
            inputs, labels = inputs.float().to(device), labels.to(device)
            preds= model(inputs)
            pred_idx = preds.max(1).indices
            acc = (pred_idx == labels).sum().item() / labels.size(0)
            acc_list.append(acc)

            loss = loss_func(preds, labels).item()
            loss_list.append(loss)

    valid_loss = np.array(loss_list).mean()
    valid_acc = np.array(acc_list).mean()

    return valid_loss, valid_acc

def run_pretrain():
    log = open(experiment_dir + '/pretrain.log', 'w')

    model = create_model(model_type=model_type, pretrained=pretrained, n_classes=n_classes,
                         input_size=input_size, checkpoint=checkpoint)# , width_mult=0.5)
    model = model.to(device)

    teacher_model = create_model(model_type='mobilenet_v2_torchhub', pretrained=True, n_classes=n_classes,
                                 input_size=input_size, checkpoint=teacher_checkpoint)
    teacher_model = teacher_model.to(device)
    print(teacher_model)
    print(model)

    # count_flops(model)

    train_dataset = TrainDataset('./data/stanford-dogs/Processed/train')
    train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
    valid_dataset = EvalDataset('./data/stanford-dogs/Processed/valid')
    valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False)

    # criterion = nn.CrossEntropyLoss()
    # optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
    optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=weight_decay)
    # optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, amsgrad=True)

    # for distillation
    # alpha, temperature = 0.99, 8
    alpha, temperature = 0, 1

    best_valid_acc = 0.0
    for epoch in range(n_epochs):
        print('Start training epoch {}'.format(epoch))
        loss_list = []

        # train
        model.train()
        for i, (inputs, labels) in enumerate(tqdm(train_dataloader)):
            optimizer.zero_grad()
            inputs, labels = inputs.float().to(device), labels.to(device)
            with torch.no_grad():
                teacher_preds = teacher_model(inputs)

            preds = model(inputs)
            soft_loss = nn.KLDivLoss()(F.log_softmax(preds/temperature, dim=1),
                                       F.softmax(teacher_preds/temperature, dim=1))
            hard_loss = F.cross_entropy(preds, labels)
            loss = soft_loss * (alpha * temperature * temperature) + hard_loss * (1. - alpha)
            loss_list.append(loss.item())
            loss.backward()
            optimizer.step()

        # validation
        valid_loss, valid_acc = run_validation(model, valid_dataloader)
        train_loss = np.array(loss_list).mean()
        print('Epoch {}: train loss {:.4f}, valid loss {:.4f}, valid acc {:.4f}'.format
              (epoch, train_loss, valid_loss, valid_acc))
        log.write('Epoch {}: train loss {:.4f}, valid loss {:.4f}, valid acc {:.4f}\n'.format
                  (epoch, train_loss, valid_loss, valid_acc))

        # save
        if valid_acc > best_valid_acc:
            best_valid_acc = valid_acc
            torch.save(model.state_dict(), experiment_dir + '/checkpoint_best.pt')

    log.close()

if __name__ == '__main__':
    torch.set_num_threads(16)
    run_pretrain()


text:
# --------------
# Importing header files
import numpy as np
import warnings

warnings.filterwarnings('ignore')

#New record
new_record=[[50,  9,  4,  1,  0,  0, 40,  0]]

#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)

#Code starts here

census=np.concatenate((new_record,data))

age=np.array(census[:,:1])
max_age=np.max(age)
min_age=np.min(age)
age_mean=np.mean(age)
age_std=np.std(age)
print(max_age)
print(min_age)
print(age_mean)
print(age_std)

race_0=census[census[:,2]==0]
race_1=census[census[:,2]==1]
race_2=census[census[:,2]==2]
race_3=census[census[:,2]==3]
race_4=census[census[:,2]==4]
len_0=len(race_0)
len_1=len(race_1)
len_2=len(race_2)
len_3=len(race_3)
len_4=len(race_4)
min_race=0
min_race=min(len_0,len_1,len_2,len_3,len_4)
if min_race==len_0:
    minority_race=0
if min_race==len_1:
    minority_race=1
if min_race==len_2:
    minority_race=2
if min_race==len_3:
    minority_race=3
if min_race==len_4:
    minority_race=4

print(minority_race)

senior_citizens=census[census[:,0]>60]
working_hours_sum=sum(senior_citizens[:,6])
print(working_hours_sum)
senior_citizens_len=len(senior_citizens)
avg_working_hours=working_hours_sum/senior_citizens_len
print(avg_working_hours)

high=census[census[:,1]>10]
low=census[census[:,1]<=10]
avg_pay_high=np.mean(high[:,7])
avg_pay_low=np.mean(low[:,7])
print(round(avg_pay_high,2))
print(round(avg_pay_low,2))

np.array_equal(avg_pay_high,avg_pay_low)


text:
"""
pygama tier 0 processing
raw daq data --> pandas dfs saved to hdf5 file (tier 1)
"""
import os, re, sys, glob, time
import numpy as np
import h5py
import pandas as pd
from pprint import pprint

from ..utils import *
from ..io.digitizers import *
from ..io.pollers import *
from ..io.io_base import *
from ..io.orca_helper import *
from ..io.llama_3316 import *

def daq_to_raw(t0_file, run, prefix="t1", suffix="", chan_list=None, n_max=np.inf,
               verbose=False, output_dir=None, overwrite=True, decoders=None,
               config={}):
    """
    """
    print("Starting pygama daq_to_raw processing ...")
    print("  Input file:", t0_file)

    output_dir = os.getcwd() if output_dir is None else output_dir

    # ###############################################################
    # # Change for HADES style output
    # # TODO: as vince would say, i need to do something smart here
    #
    # if ftype == "hades_char":
    # # declare Tier 1 output file
    #
    #    file_body = t0_file.split("/")[-1].replace("fcio","h5")
    #    t1_file = "{}/{}_{}".format(output_dir,prefix,file_body)
    #    if os.path.isfile(t1_file):
    #        if overwrite:
    #            print("Overwriting existing file...")
    #            os.remove(t1_file)
    #        else:
    #            print("File already exists, continuing ...")
    #            return
    # ################################################################
    # else:
    t1_file = f"{output_dir}/{prefix}_run{run}.{suffix}"
    if os.path.isfile(t1_file):
       if overwrite:
           print("Overwriting existing file...")
           os.remove(t1_file)
       else:
           print("File already exists, continuing ...")
           return

    t_start = time.time()

    # set max number of events (useful for debugging)
    if n_max is not np.inf and n_max is not None:
        n_max = int(n_max)

    # get the DAQ mode
    if config["daq"] == "ORCA":
        process_orca(t0_file, t1_file, n_max, decoders, config, verbose, run)

    elif config["daq"] == "FlashCam":
        process_flashcam(t0_file, t1_file, run, n_max, decoders, config, verbose)

    elif config["daq"] == "SIS3316":
        process_llama_3316(t0_file, t1_file, run, n_max, config, verbose)

    elif config["daq"] == "CAENDT57XXDecoder":
        process_compass(t0_file, t1_file, decoders, output_dir)

    else:
        print(f"DAQ: {config['daq']} not recognized.  Exiting ...")
        exit()

    # --------- summary ------------

    statinfo = os.stat(t1_file)
    print("File size: {}".format(sizeof_fmt(statinfo.st_size)))
    elapsed = time.time() - t_start
    print("Time elapsed: {:.2f} sec".format(elapsed))
    print("  Output file:", t1_file)
    print("Done.\n")

def process_orca(t0_file, t1_file, n_max, decoders, config, verbose, run=None):
    """
    convert ORCA DAQ data to pygama "raw" lh5
    """
    ROW_LIMIT = 5e4

    start = time.time()
    f_in = open(t0_file.encode('utf-8'), "rb")
    if f_in == None:
        print("Couldn't find the file %s" % t0_file)
        sys.exit(0)

    # parse the header
    reclen, reclen2, header_dict = parse_header(t0_file)

    # figure out the total size
    SEEK_END = 2
    f_in.seek(0, SEEK_END)
    file_size = float(f_in.tell())
    f_in.seek(0, 0)  # rewind
    file_size_MB = file_size / 1e6
    print("Total file size: {:.3f} MB".format(file_size_MB))

    if run is not None:
        run = get_run_number(header_dict)
    print("Run number: {}".format(run))

    # figure out which decoders we can use.  should simplify this block
    decoders = []
    id_dict = get_decoder_for_id(header_dict)
    if verbose:
        print("Data IDs present in this header are:")
        for id in id_dict:
            print(f"    {id}: {id_dict[id]}")
    used_ids = set([id_dict[id] for id in id_dict])
    for sub in DataTaker.__subclasses__():
        try:
            tmp = sub() # instantiate the class
            if tmp.decoder_name in used_ids:
                # tmp.apply_config(config) # broken rn
                decoders.append(tmp)
        except:
            continue

    decoder_to_id = {d.decoder_name: d for d in decoders}
    if verbose:
        print("pygama will run these decoders:")
        for d in decoders:
            print("   ", d.decoder_name)

    # -- scan over raw data --
    print("Beginning Tier 0 processing ...")

    packet_id = 0  # number of events decoded
    unrecognized_data_ids = []

    # skip the header.
    # reclen is in number of longs, and we want to skip a number of bytes
    f_in.seek(reclen * 4)

    # start scanning
    while (packet_id < n_max and f_in.tell() < file_size):
        packet_id += 1

        if verbose and packet_id % 1000 == 0:
            update_progress(float(f_in.tell()) / file_size)

        # write periodically to the output file instead of writing all at once
        if packet_id % ROW_LIMIT == 0:
            for d in decoders:
                d.save_to_pytables(t1_file, verbose=True)
        try:
            event_data, data_id = get_next_event(f_in)
        except EOFError:
            break
        except Exception as e:
            print("Failed to get the next event ... Exception:",e)
            break

        try:
            decoder = decoder_to_id[id_dict[data_id]]
        except KeyError:
            if data_id not in id_dict and data_id not in unrecognized_data_ids:
                unrecognized_data_ids.append(data_id)
            continue

        # sends data to the pandas dataframe
        decoder.decode_event(event_data, packet_id, header_dict)

    print("done.  last packet ID:", packet_id)
    f_in.close()

    # final write to file
    for d in decoders:
            try:
                d.save_to_pytables(t1_file, verbose=True)
            except Exception as e:
                print("WARNING: " + str(d) + " cannot be saved ... Exception:",e)

    if verbose:
        update_progress(1)

    if len(unrecognized_data_ids) > 0:
        print("WARNING, Found the following unknown data IDs:")
        for id in unrecognized_data_ids:
            print("  {}".format(id))
        print("hopefully they weren't important!\n")

    print("Wrote Tier 1 File:\n    {}\nFILE INFO:".format(t1_file))
    with pd.HDFStore(t1_file,'r') as store:
        print(store.keys())
        # print(store.info())

def process_llama_3316(t0_file, t1_file, run, n_max, config, verbose):
    """
    convert llama DAQ data to pygama "raw" lh5

    Mario's implementation for the Struck SIS3316 digitizer.
    Requires the llamaDAQ program for producing compatible input files.
    """
    ROW_LIMIT = 5e4

    start = time.time()
    f_in = open(t0_file.encode('utf-8'), "rb")
    if f_in == None:
        print("Couldn't find the file %s" % t0_file)
        sys.exit(0)

    #file = llama_3316(f_in,2) #test

    verbosity = 1 if verbose else 0     # 2 is for debug
    sisfile = llama_3316(f_in, verbosity)

    # figure out the total size
    SEEK_END = 2
    f_in.seek(0, SEEK_END)
    file_size = float(f_in.tell())
    f_in.seek(0, 0)  # rewind
    file_size_MB = file_size / 1e6
    print("Total file size: {:.3f} MB".format(file_size_MB))

    header_dict = sisfile.parse_channelConfigs()    # parse the header dict after manipulating position in file

    # run = get_run_number(header_dict)
    print("Run number: {}".format(run))

    pprint(header_dict)

    #see pygama/pygama/io/decoders/io_base.py
    decoders = []
    #decoders.append(LLAMAStruck3316(metadata=pd.DataFrame.from_dict(header_dict)))   #we just have that one
    decoders.append(LLAMAStruck3316(metadata=header_dict))  #we just have that one
                    # fix: saving metadata using io_bases ctor
                    # have to convert to dataframe here in order to avoid
                    # passing to xml_header.get_object_info in io_base.load_metadata
    channelOne = list(list(header_dict.values())[0].values())[0]
    decoders[0].initialize(1000./channelOne["SampleFreq"], channelOne["Gain"])
        # FIXME: gain set according to first found channel, but gain can change!

    print("pygama will run this fancy decoder: SIS3316Decoder")

    # pass in specific decoder options (windowing, multisampling, etc.)
    #for d in decoders:
    #    d.apply_config(config) #no longer used (why?)

    # ------------ scan over raw data starts here -----------------
    # more code duplication

    print("Beginning Tier 0 processing ...")

    packet_id = 0  # number of events decoded
    row_id = 0      #index of written rows, FIXME maybe gets unused
    unrecognized_data_ids = []

    # header is already skipped by llama_3316,

    def toFile(digitizer, filename_raw, rowID, verbose):
        numb = str(rowID).zfill(4)
        filename_mod = filename_raw + "." + numb
        print("redirecting output file to packetfile "+filename_mod)
        digitizer.save_to_pytables(filename_mod, verbose)

    # start scanning
    while (packet_id < n_max and f_in.tell() < file_size):
        packet_id += 1

        if verbose and packet_id % 1000 == 0:
            update_progress(float(f_in.tell()) / file_size)

        # write periodically to the output file instead of writing all at once
        if packet_id % ROW_LIMIT == 0:
            for d in decoders:
                d.save_to_lh5(t1_file)
            row_id += 1

        try:
            fadcID, channelID, event_data = sisfile.read_next_event(header_dict)
        except Exception as e:
            print("Failed to get the next event ... Exception:",e)
            break
        if event_data is None:
            break

        decoder = decoders[0]       #well, ...
        # sends data to the pandas dataframe
        decoder.decode_event(event_data, packet_id, header_dict, fadcID, channelID)

    print("done.  last packet ID:", packet_id)
    f_in.close()

    # final write to file
    for d in decoders:
        d.save_to_lh5(t1_file)

    if verbose:
        update_progress(1)

    if len(unrecognized_data_ids) > 0:
        print("WARNING, Found the following unknown data IDs:")
        for id in unrecognized_data_ids:
            print("  {}".format(id))
        print("hopefully they weren't important!\n")

    # ---------  summary ------------

    print("Wrote: Tier 1 File:\n    {}\nFILE INFO:".format(t1_file))
    with pd.HDFStore(t1_file,'r') as store:
        print(store.keys())
    #    # print(store.info())

def process_compass(t0_file, t1_file, digitizer, output_dir=None):
    """
    Takes an input .bin file name as t0_file from CAEN CoMPASS and outputs t1_file
    t0_file: input file name, string type
    t1_file: output file name, string type
    digitizer: CAEN digitizer, Digitizer type
    options are uncalibrated or calibrated.  Select the one that was outputted by CoMPASS, string type
    output_dir: path to output directory string type
    """
    start = time.time()
    f_in = open(t0_file.encode("utf-8"), "rb")
    if f_in is None:
        raise LookupError("Couldn't find the file %s" % t0_file)
    SEEK_END = 2
    f_in.seek(0, SEEK_END)
    file_size = float(f_in.tell())
    f_in.seek(0, 0)
    file_size_MB = file_size / 1e6
    print("Total file size: {:.3f} MB".format(file_size_MB))

    # ------------- scan over raw data starts here ----------------

    print("Beginning Tier 0 processing ...")

    event_rows = []
    waveform_rows = []
    event_size = digitizer.get_event_size(t0_file)
    with open(t0_file, "rb") as metadata_file:
        event_data_bytes = metadata_file.read(event_size)
        while event_data_bytes != b"":
            event, waveform = digitizer.get_event(event_data_bytes)
            event_rows.append(event)
            waveform_rows.append(waveform)
            event_data_bytes = metadata_file.read(event_size)
    all_data = np.concatenate((event_rows, waveform_rows), axis=1)
    output_dataframe = digitizer.create_dataframe(all_data)
    f_in.close()

    output_dataframe.to_hdf(path_or_buf=output_dir+"/"+t1_file, key="dataset", mode="w", table=True)
    print("Wrote Tier 1 File:\n  {}\nFILE INFO:".format(t1_file))

    # --------- summary -------------

    with pd.HDFStore(t1_file, "r") as store:
        print(store.keys())

def process_flashcam(t0_file, t1_file, run, n_max, decoders, config, verbose):
    """
    decode FlashCam data, using the fcutils package to handle file access,
    and the FlashCam DataTaker to save the results and write to output.
    """
    import fcutils

    fcio = fcutils.fcio(t0_file)
    decoder = FlashCam()
    decoder.get_file_config(fcio)

    # ROW_LIMIT = 5e4
    ROW_LIMIT = 1000

    # loop over raw data packets
    i_debug = 0
    packet_id = 0
    while fcio.next_event() and packet_id < n_max:
      packet_id += 1
      if verbose and packet_id % 1000 == 0:
          update_progress(float(fcio.telid) / file_size)

      # write periodically to the output file
      if packet_id % ROW_LIMIT == 0:

          # decoder.save_to_pytables(t1_file, verbose=True)

          decoder.save_to_lh5(t1_file)

          i_debug += 1
          if i_debug == 1:
              print("breaking early")
              break # debug, deleteme

      decoder.decode_event(fcio, packet_id)

    # end of loop, write to file once more
    # decoder.save_to_pytables(t1_file, verbose=True)
    # decoder.save_to_lh5(t1_file, verbose=True)

    if verbose:
      update_progress(1)


text:
import cv2
import numpy as np

roi = cv2.imread('rose_red.png')
hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)

target = cv2.imread('rose.png')
hsvt = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)

# calculating object histogram
roihist = cv2.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )

# normalize histogram and apply backprojection
cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)
dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)

# Now convolute with circular disc
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
cv2.filter2D(dst,-1,disc,dst)

# threshold and binary AND
ret,thresh = cv2.threshold(dst,50,255,0)
thresh = cv2.merge((thresh,thresh,thresh))
res = cv2.bitwise_and(target,thresh)

res = np.vstack((target,thresh,res))
cv2.imwrite('res.jpg',res)

max_stars_repo_name: TheoSaify/Yolo-Detector

max_issues_repo_name: TheoSaify/Yolo-Detector

max_forks_repo_name: TheoSaify/Yolo-Detector