def detect(img, xdim, ydim): # convert to grayscale gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) utils.show_image(gray, 'gray') # threshold to convert to binary image ret, thresh = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV+cv.THRESH_OTSU) utils.show_image(thresh, 'threshold') # erode image to isolate the sure foreground kernel = np.ones((3,3),np.uint8) opening = cv.morphologyEx(thresh,cv.MORPH_OPEN, kernel, iterations=3) utils.show_image(opening, 'opening') # get the median pixel value (should be background) mode = utils.get_mode(img, xdim, ydim) # replace the foreground (trees) with the median pixel for i in xrange(xdim): for j in xrange(ydim): # if it's white in the eroded image, then it's vegetation if opening[i,j] == 255: # set to black img[i,j] = mode utils.show_image(img, 'color-overlay') return img
def mask(img, xdim, ydim): utils.plot_histogram(img) [B,G,R] = cv.split(img) blue = B.astype(float) green = G.astype(float) red = R.astype(float) meanR = np.mean(red) stdR = np.std(red) print meanR + 1.6 * stdR meanB = np.mean(blue) stdB = np.std(blue) print meanB + 1.1 * stdB mode_pixel = utils.get_mode(img, xdim, ydim) # separate into roads and houses for i in xrange(xdim): for j in xrange(ydim): # road: red value is at least 2 std above the mean if red[i,j] > meanR + 1.6 * stdR: # red[i,j] > 180 img[i,j] = mode_pixel # houses: blue value is at least 1 std above the mean if blue[i,j] > meanB + 1.1 * stdB: # 182: #and blue[i,j] <= 238: img[i,j] = (0,0,0) utils.show_image(img, 'mask') return img
def detect(img, xdim, ydim): # convert to grayscale gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) utils.show_image(gray, 'gray') # threshold to convert to binary image ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU) utils.show_image(thresh, 'threshold') # erode image to isolate the sure foreground kernel = np.ones((3, 3), np.uint8) opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=3) utils.show_image(opening, 'opening') # get the median pixel value (should be background) mode = utils.get_mode(img, xdim, ydim) # replace the foreground (trees) with the median pixel for i in range(xdim): for j in range(ydim): # if it's white in the eroded image, then it's vegetation if opening[i, j] == 255: # set to black img[i, j] = mode utils.show_image(img, 'color-overlay') return img
def run(self): self.running = True match_ids = set() for details in self.highlights.values(): match_id = details['match_id'] if match_id is not None: region = details['region'] match_ids.add((region, match_id)) no_of_ids = len(match_ids) retrieved = {} for x, (region, match_id) in enumerate(match_ids, 1): if not self.running: break url = f'https://slick.co.ke/v1/match/{region}/{match_id}' match_details = requests.get(url).json() retrieved[match_id] = match_details self.status.emit( f'Retrieving match details: {round((x/no_of_ids) * 100, 1)}%') no_of_highlights = len(self.highlights) summoner_name = DataStore.get_preferences()['user_name'] index = 1 for name, details in self.highlights.items(): match_id = details['match_id'] if match_id in retrieved: full_details = retrieved[match_id] game_mode = full_details['gameMode'] queue_id = full_details['queueId'] mode = utils.get_mode(game_mode, queue_id) self.highlights[name]['game_mode'] = mode for participant in full_details['participantIdentities']: if participant['player']['summonerName'] == summoner_name: participant_id = participant['participantId'] for participant in full_details['participants']: if participant['participantId'] == participant_id: champion_id = participant['championId'] champion_name = DataStore.get_champion_by_id( champion_id) self.highlights[name]['played_as'] = champion_name self.highlights[name]['win'] = \ participant['stats']['win'] percentage = round((index/no_of_highlights) * 100) self.status.emit( f'Processing highlights: {percentage}%') index += 1 DataStore.save_partial_highlights(self.highlights, to_file=True) self.status.emit('Done') self.done_status.emit()
def mask(img, xdim, ydim): utils.plot_histogram(img) [B, G, R] = cv.split(img) blue = B.astype(float) green = G.astype(float) red = R.astype(float) meanR = np.mean(red) stdR = np.std(red) print meanR + 1.6 * stdR meanB = np.mean(blue) stdB = np.std(blue) print meanB + 1.1 * stdB mode_pixel = utils.get_mode(img, xdim, ydim) # separate into roads and houses for i in xrange(xdim): for j in xrange(ydim): # road: red value is at least 2 std above the mean if red[i, j] > meanR + 1.6 * stdR: # red[i,j] > 180 img[i, j] = mode_pixel # houses: blue value is at least 1 std above the mean if blue[i, j] > meanB + 1.1 * stdB: # 182: #and blue[i,j] <= 238: img[i, j] = (0, 0, 0) utils.show_image(img, 'mask') return img
def mapper(model, result_record, neg_index, img_feature, bin_num, interval, bound): for local_num in range(interval, bound, interval): mode = utils.get_mode( result_record[max(0, len(result_record) - local_num):len(result_record):])[0] if mode != neg_index: return mode, 1.0 bin_feature = utils.mapper_feature(l=result_record, global_num=bin_num, neg=neg_index) bin_feature = torch.from_numpy(bin_feature).view([-1, bin_num]).cuda() process_feature = torch.from_numpy(np.array([len(result_record) * 1.0 ])).float().view([1, 1]).cuda() img_feature = torch.from_numpy(img_feature).view([1, 2048]).cuda() hx, cx = torch.zeros((1, 1, 32)).cuda(), torch.zeros((1, 1, 32)).cuda() res = model(bin_feature, img_feature, hx, cx, alpha_hand=0.95) res = F.softmax(res, dim=1) predict = int(res.max(1)[1][0]) c = float(res.max(1)[0][0]) return predict, c
def main(api_endpoint, credentials, device_model_id, device_id, lang, display, verbose, grpc_deadline, *args, **kwargs): # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logging.info('Connecting to %s', api_endpoint) with utils.TextAssistant(lang, device_model_id, device_id, display, grpc_channel, grpc_deadline) as assistant: # If current mode is ECO mode, change it to HEAT mode if (utils.get_mode(assistant) == NestMode.ECO): logging.info('Set mode to HEAT') utils.query_assistant(assistant, constants.SET_MODE_HEAT)
def to_resoult(date, play_type, nums): data_dict = { "种类": play_type, "日期": date, "平均数": utils.get_mean(nums), "中位数": utils.get_median(nums), "众数": utils.get_mode(nums) } data = pd.DataFrame(data_dict, index=[0]) return data
def f(d_): cells = d_["topo_cells"] ids = [] features = [] for id_, cell_ in cells.iteritems(): ids += [id_] res_ = [] for mode in modes: res_ += [get_mode(cell_, mode)] features += [res_] return {"ids": ids, "features": features}
def __call__(self, cells, topo_eta, topo_phi): """ Returns matrices from cells Args: cells a dict of dict layer_extractors: a dict of layer extractor, one for each layer topo_eta: eta of cluster topo_phi: phi of cluster Returns a dict of np arrays d[layer nb] = np array if np array is not empty else shape of the np array """ layer_extractors = self.layer_extractors matrices = dict() for dep, extractor in layer_extractors.iteritems(): assert dep == extractor.dep, "Dep mismatch in {}".format( self.__class__.__name__) matrices[dep] = dict() for mode in self.modes: matrices[dep][mode] = np.zeros([extractor.n_phi, extractor.n_eta]) for id_, cell_ in cells.iteritems(): dep = cell_["dep"] # only add matrices for which we have an extractor if dep in self.layer_extractors.keys(): self.preservation_ratio[dep]["cell"] += 1 eta_id, phi_id = layer_extractors[dep](cell_, topo_eta, topo_phi) for mode in self.modes: if mode != "cluster": matrices[dep][mode][phi_id, eta_id] += get_mode(cell_, mode) else: matrices[dep][mode][phi_id, eta_id] = get_mode(cell_, mode) for dep, modes_ in matrices.iteritems(): self.preservation_ratio[dep]["mat"] += np.count_nonzero(modes_[self.filter_mode]) if np.sum(modes_[self.filter_mode]) == 0: for mode in self.modes: modes_[mode] = modes_[mode].shape return matrices
def main(api_endpoint, credentials, device_model_id, device_id, lang, display, verbose, grpc_deadline, *args, **kwargs): # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logging.info('Connecting to %s', api_endpoint) with utils.TextAssistant(lang, device_model_id, device_id, display, grpc_channel, grpc_deadline) as assistant: nest_mode = utils.get_mode(assistant) # Variables temp, humidity, home_temp, home_humidity, home_target = ('', ) * 5 home_humidity, home_temp, home_target = get_inconditions( assistant, nest_mode) humidity, temp = get_current_weather() payload = { 'temp': temp, 'humidity': humidity, 'hometemp': home_temp, 'hometarget': home_target, 'homehumidity': home_humidity, 'nestmode': nest_mode } logging.info('Payload %s ', payload) if not DEBUG: r = requests.get(constants.SPREADSHEET, params=payload)
def f(d_): cells = d_["topo_cells"] features = [] for id_, cell_ in cells.iteritems(): res = [] for mode in modes: if mode in ["topo_pt", "topo_eta", "topo_phi"]: feat = d_[mode] else: feat = get_mode(cell_, mode) if type(feat) == list: res += feat else: res += [feat] features += [res] return features