def set_default_locators_and_formatters(self, axis): axis.set_major_locator(NullLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(FixedLocator(third(12.5, 20000))) axis.set_minor_formatter(ScalarFormatter())
def detect_object(): global opt response_data = {"success": False} # 这就是要返回的对象 # 提取post参数 save_output_images = flask.request.form.get('save_output_images') print("\nPOST argument:") print("\t+ save_output_images: %s\n" % save_output_images) dataloader = DataLoader( ImageFolder(opt.image_folder, img_size=opt.img_size), batch_size=opt.batch_size, shuffle=False, num_workers=opt.n_cpu, ) classes = load_classes(opt.class_path) # 解析对应的class名称 Tensor = torch.cuda.FloatTensor if torch.cuda.is_available( ) else torch.FloatTensor imgs = [] # imgs存储每一张图片的路径 img_detections = [] # 存储对应路径的图片的探测结果 response_data["detections"] = list() # 开始 Detection print("Start object detection:") prev_time = time.time() for batch_i, (img_paths, input_imgs) in enumerate(dataloader): input_imgs = Variable(input_imgs.type(Tensor)) with torch.no_grad(): detections = model(input_imgs) detections = non_max_suppression(detections, opt.conf_thres, opt.nms_thres) imgs.extend(img_paths) img_detections.extend(detections) tmp = { "img_path": img_paths, "img_detection": detections[0].cpu().numpy().tolist() } response_data["detections"].append(tmp) current_time = time.time() inference_time = datetime.timedelta(seconds=current_time - prev_time) prev_time = current_time print("\t+ Batch %d, Inference Time: %s" % (batch_i, inference_time)) # 将bounding box画在图上并保存 if save_output_images == "True": print("\nSaving images:") os.makedirs("output", exist_ok=True) # 标记的输出图片将被存放在./output文件夹中 # 决定Bounding Box的颜色 cmap = plt.get_cmap("tab20b") colors = [cmap(i) for i in np.linspace(0, 1, 20)] # 开始画Bounding Box并保存 for img_i, (path, detections) in enumerate(zip(imgs, img_detections)): print("(%d) Image: '%s'" % (img_i, path)) # 创建plot与底图 img = np.array(Image.open(path)) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) # 画出Bounding Box并标上 label名 if detections is not None: detections = rescale_boxes(detections, opt.img_size, img.shape[:2]) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item())) box_w = x2 - x1 box_h = y2 - y1 color = bbox_colors[int( np.where(unique_labels == int(cls_pred))[0])] bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") ax.add_patch(bbox) plt.text( x1, y1, s=classes[int(cls_pred)], color="white", verticalalignment="top", bbox={ "color": color, "pad": 0 }, ) # 保存一张画好的图片 plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) filename = path.split("/")[-1].split(".")[0] plt.savefig(f"output/{filename}.png", bbox_inches="tight", pad_inches=0.0) plt.close() response_data["success"] = True return flask.jsonify(response_data)
def set_default_locators_and_formatters(self, axis): axis.set_major_locator(FixedLocator(octave(16, 16000))) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_locator(NullLocator()) axis.set_minor_formatter(NullFormatter())
def check(): fn = '/home/yeezy/Dat/Megvii/train.txt' boxes_list = list() box_cnt = 0 with open(fn, 'r') as imgs: for img in imgs: src_img = img.split('\n')[0] src_label = src_img.replace('jpg', 'txt').replace('images', 'labels') img_fn = src_img.split('/')[-1] print src_img print src_label print img_fn image = cv2.imread(src_img, cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) height, width = image.shape[0:2] plt.figure() fig, ax = plt.subplots(1) ax.imshow(image) boxes = list() with open(src_label, 'r') as bbox: for box in bbox: box = box.split(' ')[1:5] box = [float(cord) for cord in box] x1 = box[0] - box[2] / 2.0 x2 = box[0] + box[2] / 2.0 y1 = box[1] - box[3] / 2.0 y2 = box[1] + box[3] / 2.0 x1 *= width x2 *= width y1 *= height y2 *= height cord = [ float(int(x1)), float(int(y1)), float(int(x2)), float(int(y2)) ] boxes.append(cord) bbox = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, edgecolor='blue', facecolor='none') ax.add_patch(bbox) plt.axis('off') plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) plt.savefig('/home/yeezy/Desktop/vis/{}'.format(img_fn), bbox_inches='tight', pad_inches=0.0) plt.close() box_cnt += len(boxes) boxes_list.append(boxes)
def plot(df, path, useexpo=False, dpi=600, part=['p', 'v'], price_part=0.7, xsize=10, ysize=10): ''' plot(df, path, useexpo=False, dpi=600, part=['p', 'v'], price_part=0.7, xsize=10, ysize=10): 根据数据绘制png格式的量价k线图,文件名'股票代码_日期_天数_pv.png',如'600000_20161129_60_pv.png' Input: df: (DataFrame): 股票数据 path: (string): 图片文件存储路径 useexpo: (boolean): 是否使用对数坐标,True为使用对数坐标,False为线性坐标 dpi: (int): 图片分辨率 part: (list of string): 图片包含的内容,接受['p'], ['v'], ['p', 'v'],即单独价格k线图,成交量图,和量价k线图 price_part: (float): 价格k线部分所占比例,仅当part为['p', 'v']时生效 xsize: (int): 图片宽度 ysize: (int): 图片高度 ''' if set(part) == set(['p', 'v']): rect_1 = (0, 1 - price_part, 1, price_part) # K线图部分 rect_2 = (0, 0, 1, 1 - price_part) # 成交量部分 elif part == ['p']: rect_1 = (0, 0, 1, 1) elif part == ['v']: rect_2 = (0, 0, 1, 1) else: print('part name invalid') return df = df.reset_index(drop=True) length = len(df['date']) highest_price, lowest_price = df['high'].max(), df['low'].min() raise_color, fall_color, keep_color = 'red', 'green', 'yellow' bg_color = 'black' if useexpo: expbase = 1.1 xlen_fig = length * 0.05 #0.055是经验数值 ylen_fig = 2.7 #2.7是经验数值 xshrink = xsize / xlen_fig yshrink = ysize / ylen_fig # 建立 Figure 对象 figobj = pyplot.figure(figsize=(xsize, ysize), dpi=dpi) xindex = numpy.arange(length) # X 轴上的 index,一个辅助数据 zipoc = zip(df['open'], df['close']) up = numpy.array( df.apply(lambda x: True if x['open'] < x['close'] and x['open'] != None else False, axis=1)) # 标示出该天股价日内上涨的一个序列 down = numpy.array( df.apply(lambda x: True if x['open'] > x['close'] and x['open'] != None else False, axis=1)) # 标示出该天股价日内下跌的一个序列 side = numpy.array( df.apply(lambda x: True if x['open'] == x['close'] and x['open'] != None else False, axis=1)) # 标示出该天股价日内走平的一个序列 for i in range(len(df)): if df.loc[i, 'open'] == df.loc[i, 'close']: var = min(round(df.loc[i, 'open'] + 1 / 2000, 5), 0.005) df.loc[i, 'open'] -= var df.loc[i, 'close'] += var #====== 成交量 if 'v' in part: axes_2 = figobj.add_axes(rect_2, axis_bgcolor=bg_color) volume = df['volume'] rarray_vol = numpy.array(volume) volzeros = numpy.zeros(length) # 辅助数据 if True in up: axes_2.vlines(xindex[up], volzeros[up], rarray_vol[up], color=raise_color, linewidth=3.0 * xshrink, label='_nolegend_') if True in down: axes_2.vlines(xindex[down], volzeros[down], rarray_vol[down], color=fall_color, linewidth=3.0 * xshrink, label='_nolegend_') if True in side: axes_2.vlines(xindex[side], volzeros[side], rarray_vol[side], color=keep_color, linewidth=3.0 * xshrink, label='_nolegend_') # 设定x轴坐标范围 axes_2.set_xlim(-1, length) axes_2.xaxis.set_major_locator(NullLocator()) axes_2.xaxis.set_major_formatter(NullFormatter()) # 设定 Y 轴坐标的范围 maxvol = max(volume) axes_2.set_ylim(0, maxvol * 1.01) axes_2.yaxis.set_major_locator(NullLocator()) axes_2.yaxis.set_major_formatter(NullFormatter()) #======= K 线图 if set(part) == set(['p', 'v']): axes_1 = figobj.add_axes(rect_1, axis_bgcolor=bg_color, sharex=axes_2) elif part == ['p']: axes_1 = figobj.add_axes(rect_1, axis_bgcolor=bg_color) if 'p' in part: if useexpo: axes_1.set_yscale('log', basey=expbase) # 使用对数坐标 rarray_open = numpy.array(df['open']) rarray_close = numpy.array(df['close']) rarray_high = numpy.array(df['high']) rarray_low = numpy.array(df['low']) if True in up: axes_1.vlines(xindex[up], rarray_low[up], rarray_high[up], color=raise_color, linewidth=0.6 * xshrink, label='_nolegend_') axes_1.vlines(xindex[up], rarray_open[up], rarray_close[up], color=raise_color, linewidth=3.0 * xshrink, label='_nolegend_') if True in down: axes_1.vlines(xindex[down], rarray_low[down], rarray_high[down], color=fall_color, linewidth=0.6 * xshrink, label='_nolegend_') axes_1.vlines(xindex[down], rarray_open[down], rarray_close[down], color=fall_color, linewidth=3.0 * xshrink, label='_nolegend_') if True in side: axes_1.vlines(xindex[side], rarray_low[side], rarray_high[side], color=keep_color, linewidth=0.6 * xshrink, label='_nolegend_') axes_1.vlines(xindex[side], rarray_open[side], rarray_close[side], color=keep_color, linewidth=3.0 * xshrink, label='_nolegend_') # 在k线上面叠加绘制均线 ''' rarray_5dayave= numpy.array(df['close'].rolling(center=False, window=5).mean()) rarray_30dayave= numpy.array(df['close'].rolling(center=False, window=30).mean()) axes_1.plot(xindex, rarray_5dayave, 'o-', color='yellow', linewidth=0.1, markersize=0.7, markeredgecolor='yellow', markeredgewidth=0.1) # 5日均线 axes_1.plot(xindex, rarray_30dayave, 'o-', color='green', linewidth=0.1, markersize=0.7, markeredgecolor='green', markeredgewidth=0.1) # 30日均线 ''' # 设定 X 轴坐标的范围 axes_1.set_xlim(-1, length) axes_1.xaxis.set_major_locator(NullLocator()) axes_1.xaxis.set_major_formatter(NullFormatter()) # 设定 Y 轴坐标的范围 yhighlim_price, ylowlim_price = highest_price * 1.005, lowest_price * 0.995 axes_1.set_ylim(ylowlim_price, yhighlim_price) axes_1.yaxis.set_major_locator(NullLocator()) axes_1.yaxis.set_major_formatter(NullFormatter()) date = str(df.tail(1)['date'].values[0]) date = date[0:4] + date[5:7] + date[8:10] filetype = '_' + ('pv' if set(part) == set(['p', 'v']) else part[0]) + '.png' figpath = path + '_' + date + '_' + str(length) + filetype figobj.savefig(figpath, dpi=dpi)
def plot_2d(image, height=16, dpi=None, mask=None, bboxes=None, overlay=None, linewidth=2, mask_color='r', bbox_color='b', overlay_cmap='jet', overlay_threshold=0.1, overlay_alpha=0.1, overlay_local_max_min_distance=75, overlay_local_max_color='r', overlay_contour_color='g', save_as=None): """Plot image with contours. Parameters ---------- image : ndarray 2D image. height : float height in inches. dpi : int dpi when saving image. mask : ndarray binary mask to plot overlay. linewidth : float thickness of the overlay lines. mask_color : str matplotlib supported color for mask overlay. bbox_color : str matplotlib supported color for bbox overlay. overlay_cmap : str matplotlib support overlay cmap. overlay_threshold : str Threshold value before an overlay value is shown. overlay_alpha : float alpha value for overlay. save_as : str path where image will be saved. BUG: Sometimes the output has a white edge to the left of the image. """ aspect = float(image.shape[1]) / image.shape[0] fig, ax = plt.subplots(1, figsize=(aspect * height, height)) fig.subplots_adjust(left=0, right=1, bottom=0, top=1) cmap = None if image.ndim == 2: cmap = 'gray' elif (image.ndim == 3 and image.shape[-1] == 1): image = image[..., 0] cmap = 'gray' ax.imshow(image, cmap=cmap, aspect='equal', extent=(0, image.shape[1], image.shape[0], 0)) if mask is not None: add_2d_contours(mask, ax, linewidth, mask_color) if bboxes is not None: for bbox in bboxes: add_2d_bbox(bbox, ax, linewidth, bbox_color) if overlay is not None: add_2d_overlay(overlay, ax, linewidth, threshold=overlay_threshold, cmap=overlay_cmap, alpha=overlay_alpha, contour_color=overlay_contour_color) if overlay is not None and overlay_local_max_min_distance: add_local_maxima(overlay, ax, overlay_local_max_min_distance, overlay_threshold, overlay_local_max_color) if not save_as: plt.show() else: fig.gca().set_axis_off() fig.gca().xaxis.set_major_locator(NullLocator()) fig.gca().yaxis.set_major_locator(NullLocator()) fig.savefig(save_as, bbox_inches=Bbox([[0, 0], [aspect * height, height]]), pad_inches=0, dpi=dpi) plt.close()
def process(self): # data span start = self.gpstime - self.duration / 2. end = self.gpstime + self.duration / 2. # get data if self.use_nds: data = TimeSeriesDict.fetch(self.chanlist, start, end) else: from glue.datafind import GWDataFindHTTPConnection conn = GWDataFindHTTPConnection() cache = conn.find_frame_urls(self.ifo[0], '%s_C' % self.ifo, self.start, self.end, urltype='file') if len(cache) == 0: data = {} else: data = TimeSeriesDict.read(cache, self.chanlist, start=start, end=end, nproc=self.nproc) # make plot plot, axes = subplots(nrows=self.geometry[0], ncols=self.geometry[1], sharex=True, subplot_kw={'projection': 'timeseries'}, FigureClass=TimeSeriesPlot, figsize=[12, 6]) axes[0, 0].set_xlim(start, end) for channel, ax in zip(self.chanlist, axes.flat): ax.set_epoch(self.gpstime) # plot data try: ax.plot(data[channel]) except KeyError: ax.text(self.gpstime, 0.5, "No data", va='center', ha='center', transform=ax.transData) # plot trip indicator ylim = ax.get_ylim() ax.plot([self.gpstime, self.gpstime], ylim, linewidth=0.5, linestyle='--', color='red') ax.set_ylim(*ylim) ax.set_xlabel('') ax.set_title(channel.texname, fontsize=10) ax.xaxis.set_minor_locator(NullLocator()) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(10) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(16) plot.text(0.5, 0.04, 'Time [seconds] from trip (%s)' % self.gpstime, ha='center', va='bottom', fontsize=24) plot.text(0.01, 0.5, 'Amplitude %s' % self.unit, ha='left', va='center', rotation='vertical', fontsize=24) plot.suptitle('%s %s %s watchdog trip: %s' % (self.ifo, self.chamber, self.sensor, self.gpstime), fontsize=24) plot.save(self.outputfile) plot.close() return self.outputfile
def recycle(model, image_path): model.eval() transform = transforms.Compose([transforms.ToTensor()]) img = Image.open(image_path) img = transform(img) img, _ = pad_to_square(img, 0) img = resize(img, opt.img_size) img = torch.unsqueeze(img, 0) print(image_path) classes = load_classes(opt.class_path) # Extracts class labels from file Tensor = torch.cuda.FloatTensor if torch.cuda.is_available( ) else torch.FloatTensor imgs = [] # Stores image paths img_detections = [] # Stores detections for each image index print("\nPerforming object detection:") prev_time = time.time() # Configure input input_imgs = Variable(img.type(Tensor)) #save_image(input_imgs, 'img.png') # Get detections with torch.no_grad(): detections = model(input_imgs) detections = non_max_suppression(detections, opt.conf_thres, opt.nms_thres) print(detections) # Log progress current_time = time.time() inference_time = datetime.timedelta(seconds=current_time - prev_time) prev_time = current_time print("\t+ Inference Time: %s" % (inference_time)) # Save image and detections imgs.append(image_path) img_detections.extend(detections) # Bounding-box colors cmap = plt.get_cmap("tab20b") colors = [cmap(i) for i in np.linspace(0, 1, 20)] #print(imgs) print("\nSaving images:") # Iterate through images and save plot of detections for img_i, (path, detections) in enumerate(zip(imgs, img_detections)): print("(%d) Image: '%s'" % (img_i, path)) # Create plot img = Image.open(path) #img = img.resize((opt.img_size, opt.img_size)) img = np.array(img) #print(img.shape) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) returns = [] dates = [] filenames = [] # Draw bounding boxes and labels of detections if detections is not None: # Rescale boxes to original image detections = rescale_boxes(detections, opt.img_size, img.shape[:2]) #print(detections) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) count = 0 for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item())) box_w = x2 - x1 box_h = y2 - y1 color = bbox_colors[int( np.where(unique_labels == int(cls_pred))[0])] # Create a Rectangle patch bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text( x1, y1, s=str(count) + ':' + classes[int(cls_pred)] + ':' + str(round(cls_conf.item(), 4)), color="white", verticalalignment="top", bbox={ "color": color, "pad": 0 }, ) date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') returns.append(classes[int(cls_pred)]) dates.append(date) count = count + 1 # Save generated image with detections plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) first_image = '' for i, date in enumerate(dates): if i == 0: folder = date.split(' ')[0] folder = 'recycles/image_results/' + folder if not (os.path.isdir(folder)): os.makedirs(os.path.join(folder)) filename = returns[i] + '_' + dates[i] + '_' + str(i).zfill(5) first_image = folder + '/' + filename + '.jpg' filenames.append(folder + '/' + filename + '.jpg') plt.savefig(f"{folder}/{filename}.jpg", bbox_inches="tight", pad_inches=0.0) plt.close() else: folder = date.split(' ')[0] folder = 'recycles/image_results/' + folder if not (os.path.isdir(folder)): os.makedirs(os.path.join(folder)) filename = returns[i] + '_' + dates[i] + '_' + str(i).zfill(5) filenames.append(folder + '/' + filename + '.jpg') shutil.copy2(first_image, folder + '/' + filename + '.jpg') return returns, dates, filenames
def plot_pressure_dir(histdir, srchstr, logplot, nosave, noread, vb): """ Plot the pressure for all files in directory matching string. """ me = me0 + ".plot_pressure_dir: " t0 = time.time() ##------------------------------------------------------------------------- ## Read in existing data or calculate afresh try: assert noread == False pressdata = np.load(histdir + "/PRESS_" + srchstr + ".npz") print me + "Pressure data file found:", histdir + "/PRESS_" + srchstr + ".npz" except (IOError, AssertionError): print me + "No pressure data found. Calculating from histfiles." pressdata = calc_pressure_dir(histdir, srchstr, noread, vb) A = pressdata["A"] R = pressdata["R"] S = pressdata["S"] T = pressdata["T"] PR = pressdata["PR"] PS = pressdata["PS"] PT = pressdata["PT"] PU = pressdata["PU"] PR_WN = pressdata["PR_WN"] PS_WN = pressdata["PS_WN"] PT_WN = pressdata["PT_WN"] PU_WN = pressdata["PU_WN"] del pressdata Casimir = "_DL_" not in histdir and "_DC_" not in histdir ##------------------------------------------------------------------------- ## FIT if DL if 0 and not Casimir: ## Fit log fitfunc = lambda x, m, c: m * x + c Au = np.unique(A) + int(logplot) for Si in np.unique(S): fitPR = sp.optimize.curve_fit(fitfunc, np.log(1 + Au), np.log(PR[S == Si]), p0=[-0.5, +1.0])[0] fitPS = sp.optimize.curve_fit(fitfunc, np.log(1 + Au), np.log(PS[S == Si]), p0=[-0.5, +1.0])[0] if vb: print me+"Fit S=%.1f: PR=%.1f*(1+a)^(%.2f), PS=%.1f*(1+a)^(%.2f)"%\ (Si,np.exp(fitPR[1]),fitPR[0],np.exp(fitPS[1]),fitPS[0]) ##------------------------------------------------------------------------- ## PLOTTING t0 = time.time() fig, ax = plt.subplots(1, 1, figsize=fs["figsize"]) sty = ["-", "--", ":"] ## Add a=0 point if 0.0 not in A: nlin = np.unique(S).size A = np.hstack([[0.0] * nlin, A]) R = np.hstack([R[:nlin], R]) S = np.hstack([S[:nlin], S]) T = np.hstack([T[:nlin], T]) PR = np.hstack([[1.0] * nlin, PR]) PS = np.hstack([[1.0] * nlin, PS]) PT = np.hstack([[1.0] * nlin, PT]) PU = np.hstack([[1.0] * nlin, PU]) Au = np.unique(A) + int(logplot) ##------------------------------------------------------------------------- ## Hold R & T fixed and vary S if np.unique(R).size == 1: plotfile = histdir+"/PAS_R%.1f_S%.1f_T%.1f."%(R[0],S[0],T[0])+fs["saveext"] if T[0]>=0.0\ else histdir+"/PAS_R%.1f_S%.1f."%(R[0],S[0])+fs["saveext"] title = r"Pressure as a function of $\alpha$ for $R=%.1f,T=%.1f$"%(R[0],T[0]) if T[0]>=0.0\ else r"Pressure as a function of $\alpha$ for $R=%.2f$"%(R[0]) ## To plot a single S if np.unique(S).size == 1: ax.plot(Au, PR, "gv--", label=r"$P_R$", zorder=2) ax.plot(Au, PS, "go-", label=r"$P_S$", zorder=2) ax.plot(Au, PT, "bo-", label=r"$P_T$", zorder=2) if "_ML_" in histdir: ax.plot(Au, PU, "bv--", label=r"$P_U$", zorder=2) ax.plot(Au, -(PR - PS + PT - PU), "ks:", label=r"Net", zorder=2) ##--------------------------------- ## Casimir insets if "_CL_" in histdir: ## Pressure key left, bottom, width, height = [0.25, 0.15, 0.63, 0.4] axin = fig.add_axes([left, bottom, width, height]) UP_CL(axin, 3.0, 2.0, 0.0) axin.patch.set_alpha(0.3) ## Potential sketch left, bottom, width, height = [0.18, 0.75, 0.25, 0.13] axin = fig.add_axes([left, bottom, width, height]) x = np.linspace(-R[0] - 2, +R[0] + 2, 1000) fx = force_clin([x, 0], R[0], S[0], T[0])[0] U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() axin.plot(x, U, "k-", lw=2, zorder=1) axin.set_xlim(x[0], x[-1]) # axin.set_ylim(0,1.2*ax.get_ylim()[1]) axin.set_xlabel(r"$x$", fontsize=fs["fsa"] - 4) axin.set_ylabel(r"$U$", fontsize=fs["fsa"] - 4) axin.xaxis.set_major_locator(NullLocator()) axin.yaxis.set_major_locator(NullLocator()) axin.patch.set_alpha(0.3) ##--------------------------------- ## Single wall insets elif "_ML_" in histdir: ## Plot potential as inset Uleft, Ubottom, Uwidth, Uheight = [0.21, 0.18, 0.30, 0.21] Rschem, Sschem, Tschem = 4.0, 2.0, 0.0 x = np.linspace(-Rschem - 2.0, +Rschem + 2.0, 501) fx = force_mlin([x, 0], Rschem, Sschem, Tschem)[0] U = -sp.integrate.cumtrapz(fx, x, initial=0.0) U -= U.min() cuspind = np.abs(x - 0.5 * (Sschem + Tschem)).argmin() axin = fig.add_axes([Uleft, Ubottom, Uwidth, Uheight]) axin.plot(x, U, "k-") axin.axvspan(x[0], x[cuspind], color="b", alpha=0.2) axin.axvspan(x[cuspind], x[-1], color="g", alpha=0.2) axin.set_xlim(x[0], x[-1]) axin.set_ylim(top=3 * U[cuspind]) axin.xaxis.set_major_locator(NullLocator()) axin.set_yticks([1.0]) axin.set_yticklabels(["1"]) axin.grid() axin.set_xlabel(r"$x$", fontsize=fs["fsa"] - 5) axin.set_ylabel(r"$U/T$", fontsize=fs["fsa"] - 5) ## Pressure key # left, bottom, width, height = [0.25, 0.15, 0.63, 0.4] # axin = fig.add_axes([left, bottom, width, height]) # UP_ML(axin,R[0],S[0],T[0]) # axin.patch.set_alpha(0.1) ##--------------------------------- ## If S varies else: for Si in np.unique(S)[::-1]: if Casimir: ax.plot(Au, PR[S == Si], "o" + sty[0], label=r"$S=%.1f$" % (Si)) ax.plot(Au, PS[S == Si], "o" + sty[1], c=ax.lines[-1].get_color()) ax.plot(Au, PT[S == Si], "o" + sty[2], c=ax.lines[-1].get_color()) else: ## If DL, label should be bulk width ### One line, average. P = 0.5 * (PR + PS) ax.plot(Au, PR[S == Si], "o" + sty[0], label=r"$L=%.1f$" % (R[0] - Si)) # ax.plot(Au, PR[S==Si], "o"+sty[0], label=r"$S=%.1f$"%(Si)) # ax.plot(Au, PS[S==Si], "o"+sty[1], c=ax.lines[-1].get_color()) ## Inset of potential left, bottom, width, height = [0.19, 0.58, 0.35, 0.30] axin = fig.add_axes([left, bottom, width, height]) if "_DL_" in histdir: plot_U1D_Cartesian(axin, "dlin", 2.0, 0.0, 0.0) elif "_DC_" in histdir: plot_U1D_Cartesian(axin, "dcon", 1.0, -1.0, 0.0) ## axin.patch.set_alpha(0.5) ## Prediction for zero and infinite bulk if "_DL_" in histdir: ax.plot(Au, (Au)**(-0.5), "--", c=ax.lines[0].get_color()) ax.plot(Au, np.ones(Au.size), "y--", label=r"$L\to\infty$") if "_DC_" in histdir: ax.plot(Au, np.ones(Au.size), "y--", label=r"$L\to\infty$") ##------------------------------------------------------------------------- ## Plot appearance if logplot: ax.set_xscale("log") ax.set_yscale("log") ax.set_xlim((ax.get_xlim()[0], A[-1] + 1)) xlabel = r"$1+\frac{k\tau}{\zeta}$" plotfile = plotfile[:-4] + "_loglog." + fs["saveext"] else: ax.set_xlim((0.0, A[-1])) ax.set_ylim(bottom=0.0, top=max(1.2 * ax.get_ylim()[1], 1.0)) xlabel = r"$\alpha$" # ax.set_ylim(1e-1,1e1) ax.set_xlabel(xlabel, fontsize=fs["fsa"]) ax.set_ylabel(r"$P/P^{\rm passive}$", fontsize=fs["fsa"]) ax.grid() ax.legend(loc="best", fontsize=fs["fsl"]).get_frame().set_alpha(0.5) # fig.suptitle(title, fontsize=fs["fst"]) if not nosave: fig.savefig(plotfile) if vb: print me + "Figure saved to", plotfile if vb: print me + "Plotting time %.1f seconds." % (time.time() - t0) return
def predict(self, img_path, output_file_path=None): """ Returns: List of dictionaries. Each dictionary is like {"left": int, "top": int, "width": int, "height": int: "category": str, "confidence": float} """ from matplotlib.ticker import NullLocator dataset_mean = (104, 117, 123) image = cv2.imread(img_path, cv2.IMREAD_COLOR) height, width, _ = image.shape rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) x = base_transform(rgb_image, 300, dataset_mean) x = x.astype(np.float32) x = torch.from_numpy(x).permute(2, 0, 1) xx = Variable(x.unsqueeze(0)) # wrap tensor in Variable # if self.device.startswith("cuda"): xx = xx.to(self.device) y = self.model(xx) # (batch, num_classes, top_k, 5), 5 means (confidence, ) detections = y.data results = [] # scale each detection back up to the image scale = torch.Tensor(rgb_image.shape[1::-1]).repeat(2) for i in range(detections.size(1)): j = 0 while detections[0, i, j, 0] >= 0.6: score = detections[0, i, j, 0].item() label_name = VOC_CLASSES[i - 1] pt = (detections[0, i, j, 1:] * scale).cpu().numpy() # result = ((pt[0], pt[1]), (pt[2] - pt[0] + 1, pt[3] - pt[1] + 1), label_name, score) result = { "left": max(int(np.round(pt[0])), 0), "top": max(int(np.round(pt[1])), 0), "width": min(int(np.round(pt[2] - pt[0] + 1)), width), "height": min(int(np.round(pt[3] - pt[1] + 1)), height), "category": label_name, "confidence": score } results.append(result) j += 1 if output_file_path is not None: # plt.figure(figsize=(10,10)) colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist() plt.imshow(rgb_image) # plot the image for matplotlib current_axis = plt.gca() current_axis.set_axis_off() current_axis.xaxis.set_major_locator(NullLocator()) current_axis.yaxis.set_major_locator(NullLocator()) # scale each detection back up to the image for i in range(detections.size(1)): j = 0 while detections[0, i, j, 0] >= 0.6: score = detections[0, i, j, 0] label_name = VOC_CLASSES[i - 1] display_txt = '%s: %.2f' % (label_name, score) pt = (detections[0, i, j, 1:] * scale).cpu().numpy() coords = (pt[0], pt[1]), pt[2] - pt[0] + 1, pt[3] - pt[1] + 1 color = colors[i] current_axis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2)) current_axis.text(pt[0], pt[1], display_txt, bbox={'facecolor': color, 'alpha': 0.5}) j += 1 plt.axis('off') plt.tight_layout() save_name = img_path.split('/')[-1] save_name = save_name.split('.') save_name = '.'.join(save_name[:-1]) + "_prediction." + save_name[-1] plt.savefig(os.path.join(output_file_path, save_name), bbox_inches='tight', pad_inches=0) plt.clf() return results
def plot_2d(image, mask=None, bboxes=None, points=None, overlay=None, linewidth=2, mask_color='r', bbox_color='b', points_color='g', overlay_cmap='jet', overlay_threshold=0.1, overlay_alpha=0.1): """ Plot image with contours and point annotations. Contours are automatically extracted from masks. Parameters ---------- image : ndarray Image data of shape N x M x num channels. mask : ndarray Mask data of shape N x M. bboxes : tuple Bounding boxes to overlay. In the form of [[x, y, h, w], ...]. points : ndarray ndarray of shape (num points, 2). overlay : ndarray Heatmap of data. linewidth : int Width of plotted lines. mask_color : str Matplotlib supported color for the masks. bbox_color : str Matplotlib supported color for the bounding boxes. points_color : str Matplotlib supported color for the points. overlay_cmap : str overlay_threshold : float Value below which overlay should not be displayed. overlay_alpha : float Overlay alpha Examples -------- Can be used in Tensorboard, for instance as follows: >>> plot_overlay = torch.from_numpy(np.array(plot_2d(image_arr, mask=masks_arr))) >>> writer.add_image('train/overlay', plot_overlay, epoch, dataformats='HWC') Returns ------- PIL Image """ dpi = 100 width = image.shape[1] height = image.shape[0] figsize = width / float(dpi), height / float(dpi) fig, ax = plt.subplots(1, figsize=figsize) plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) cmap = None if image.ndim == 3: if image.shape[-1] == 1: image = image[..., 0] elif image.shape[0] == 1: image = image[0, ...] if image.ndim == 2: cmap = 'gray' ax.imshow(image, cmap=cmap, aspect='equal', extent=(0, width, height, 0)) ax.set_adjustable('datalim') if mask is not None: add_2d_contours(mask, ax, linewidth, mask_color) if bboxes is not None: for bbox in bboxes: add_2d_bbox(bbox, ax, linewidth, bbox_color) if overlay is not None: add_2d_overlay(overlay, ax, threshold=overlay_threshold, cmap=overlay_cmap, alpha=overlay_alpha) if points is not None: ax.plot(points[:, 1], points[:, 0], points_color + '.', markersize=2, alpha=1) fig.gca().set_axis_off() fig.gca().xaxis.set_major_locator(NullLocator()) fig.gca().yaxis.set_major_locator(NullLocator()) buffer = io.BytesIO() fig.savefig(buffer, pad_inches=0, dpi=dpi) buffer.seek(0) plt.close() pil_image = PIL.Image.open(buffer) return pil_image
def detect(self, dataloader, output_dir, conf_thres=0.8, nms_thres=0.4): Tensor = torch.cuda.FloatTensor if torch.cuda.is_available( ) else torch.FloatTensor imgs = [] # Stores image paths img_detections = [] # Stores detections for each image index prev_time = time.time() for batch_i, (img_paths, input_imgs) in enumerate(dataloader): input_imgs = Variable(input_imgs.type(Tensor)) with torch.no_grad(): detections = self.model(input_imgs) detections = non_max_suppression(detections, conf_thres, nms_thres) current_time = time.time() inference_time = datetime.timedelta(seconds=current_time - prev_time) prev_time = current_time logging.info("\t+ Batch %d, Inference time: %s" % (batch_i, inference_time)) imgs.extend(img_paths) img_detections.extend(detections) # Bounding-box colors colors = plt.get_cmap("tab20b").colors logging.info("\nSaving images:") for img_i, (path, detections) in enumerate(zip(imgs, img_detections)): logging.info("(%d) Image: '%s'" % (img_i, path)) # Create plot img = np.array(Image.open(path)) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) if detections is not None: detections = rescale_boxes(detections, self.model.img_size, img.shape[:2]) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: logging.info( "\t+ Label: %s, Conf: %.5f" % (self.classes[int(cls_pred)], cls_conf.item())) box_w = x2 - x1 box_h = y2 - y1 color = bbox_colors[int( np.where(unique_labels == int(cls_pred))[0])] bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text(x1, y1, s=self.classes[int(cls_pred)], color="white", verticalalignment="top", bbox={ "color": color, "pad": 0 }) # Save generated image with detections plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) filename = os.path.basename(path).split(".")[0] output_path = os.path.join(output_dir, filename + ".png") plt.savefig(output_path, bbox_inches="tight", pad_inches=0.0) plt.close()
def hide_axes(ax): for x in [ax.xaxis, ax.yaxis]: x.set_major_formatter(NullFormatter()) x.set_major_locator(NullLocator()) for _, spine in ax.spines.items(): spine.set_color('none')
def detect(self, image): cuda = torch.cuda.is_available() and self.opt.use_cuda if self.opt.showfig: os.makedirs('output', exist_ok=True) # Set up model model = Darknet(self.opt.config_path, img_size=self.opt.img_size) model.load_weights(self.opt.weights_path) print('model path: ' + self.opt.weights_path) if cuda: model.cuda() print("using cuda model") model.eval() # Set in evaluation mode h, w, _ = image.shape dim_diff = np.abs(h - w) # Upper (left) and lower (right) padding pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2 # Determine padding pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ((0, 0), (pad1, pad2), (0, 0)) # Add padding input_img = np.pad(image, pad, 'constant', constant_values=127.5) / 255. # Resize and normalize input_img = resize(input_img, (*self.img_shape, 3), mode='reflect') # Channels-first input_img = np.transpose(input_img, (2, 0, 1)) # add new axis input_img = input_img[np.newaxis, ...] # As pytorch tensor input_img = torch.from_numpy(input_img).float() classes = self.opt.FULL_LABEL_CLASSES # Extracts class labels from file Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor print('\nPerforming object detection:') # Configure input input_img = Variable(input_img.type(Tensor)) # Get detections with torch.no_grad(): detections = model(input_img) detections = non_max_suppression(detections, 80, self.opt.conf_thres, self.opt.nms_thres)[0] # Bounding-box colors cmap = plt.get_cmap('tab20b') #cmap = plt.get_cmap('Vega20b') colors = [cmap(i) for i in np.linspace(0, 1, 20)] bbox_list = [] cls_ids = [] confs = [] if self.opt.showfig: print('\nSaving images:') # Create plot img = image plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) #kitti_img_size = 11*32 kitti_img_size = 416 # The amount of padding that was added #pad_x = max(img.shape[0] - img.shape[1], 0) * (opt.img_size / max(img.shape)) #pad_y = max(img.shape[1] - img.shape[0], 0) * (opt.img_size / max(img.shape)) pad_x = max(img.shape[0] - img.shape[1], 0) * (kitti_img_size / max(img.shape)) pad_y = max(img.shape[1] - img.shape[0], 0) * (kitti_img_size / max(img.shape)) # Image height and width after padding is removed unpad_h = kitti_img_size - pad_y unpad_w = kitti_img_size - pad_x # Draw bounding boxes and labels of detections if detections is not None: print(type(detections)) print(detections.size()) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: cls_ids.append(int(cls_pred)) confs.append(cls_conf.item()) print('\t+ Label: %s, Conf: %.5f' % (classes[int(cls_pred)], cls_conf.item())) # Rescale coordinates to original dimensions box_h = int(((y2 - y1) / unpad_h) * (img.shape[0])) box_w = int(((x2 - x1) / unpad_w) * (img.shape[1])) y1 = int(((y1 - pad_y // 2) / unpad_h) * (img.shape[0])) x1 = int(((x1 - pad_x // 2) / unpad_w) * (img.shape[1])) color = bbox_colors[int( np.where(unique_labels == int(cls_pred))[0])] # Create a Rectangle patch bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor='none') bbox_list.append([(x1, y1), (x1 + box_w, y1 + box_h)]) # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text(x1, y1 - 30, s=classes[int(cls_pred)] + ' ' + str('%.4f' % cls_conf.item()), color='white', verticalalignment='top', bbox={ 'color': color, 'pad': 0 }) # Save generated image with detections plt.axis('off') plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) plt.savefig('output.png', bbox_inches='tight', pad_inches=0.0) plt.close() return bbox_list, cls_ids, confs
def corner_hack(xs, bins=20, range=None, weights=None, color="k", hist_bin_factor=1, smooth=None, smooth1d=None, labels=None, ticklabelsize=None, label_kwargs=None, show_titles=False, title_fmt=".2f", title_kwargs=None, truths=None, truth_color="#4682b4", scale_hist=False, quantiles=None, verbose=False, fig=None, max_n_ticks=5, top_ticks=False, use_math_text=False, reverse=False, hist_kwargs=None, **hist2d_kwargs): """ Make a *sick* corner plot showing the projections of a data set in a multi-dimensional space. kwargs are passed to hist2d() or used for `matplotlib` styling. Parameters ---------- xs : array_like[nsamples, ndim] The samples. This should be a 1- or 2-dimensional array. For a 1-D array this results in a simple histogram. For a 2-D array, the zeroth axis is the list of samples and the next axis are the dimensions of the space. bins : int or array_like[ndim,] The number of bins to use in histograms, either as a fixed value for all dimensions, or as a list of integers for each dimension. weights : array_like[nsamples,] The weight of each sample. If `None` (default), samples are given equal weight. color : str A ``matplotlib`` style color for all histograms. hist_bin_factor : float or array_like[ndim,] This is a factor (or list of factors, one for each dimension) that will multiply the bin specifications when making the 1-D histograms. This is generally used to increase the number of bins in the 1-D plots to provide more resolution. smooth, smooth1d : float The standard deviation for Gaussian kernel passed to `scipy.ndimage.gaussian_filter` to smooth the 2-D and 1-D histograms respectively. If `None` (default), no smoothing is applied. labels : iterable (ndim,) A list of names for the dimensions. If a ``xs`` is a ``pandas.DataFrame``, labels will default to column names. label_kwargs : dict Any extra keyword arguments to send to the `set_xlabel` and `set_ylabel` methods. ticklabelsize : int size of the tick labels show_titles : bool Displays a title above each 1-D histogram showing the 0.5 quantile with the upper and lower errors supplied by the quantiles argument. title_fmt : string The format string for the quantiles given in titles. If you explicitly set ``show_titles=True`` and ``title_fmt=None``, the labels will be shown as the titles. (default: ``.2f``) title_kwargs : dict Any extra keyword arguments to send to the `set_title` command. range : iterable (ndim,) A list where each element is either a length 2 tuple containing lower and upper bounds or a float in range (0., 1.) giving the fraction of samples to include in bounds, e.g., [(0.,10.), (1.,5), 0.999, etc.]. If a fraction, the bounds are chosen to be equal-tailed. truths : iterable (ndim,) A list of reference values to indicate on the plots. Individual values can be omitted by using ``None``. truth_color : str A ``matplotlib`` style color for the ``truths`` makers. scale_hist : bool Should the 1-D histograms be scaled in such a way that the zero line is visible? quantiles : iterable A list of fractional quantiles to show on the 1-D histograms as vertical dashed lines. verbose : bool If true, print the values of the computed quantiles. plot_contours : bool Draw contours for dense regions of the plot. use_math_text : bool If true, then axis tick labels for very large or small exponents will be displayed as powers of 10 rather than using `e`. reverse : bool If true, plot the corner plot starting in the upper-right corner instead of the usual bottom-left corner max_n_ticks: int Maximum number of ticks to try to use top_ticks : bool If true, label the top ticks of each axis fig : matplotlib.Figure Overplot onto the provided figure object. hist_kwargs : dict Any extra keyword arguments to send to the 1-D histogram plots. **hist2d_kwargs Any remaining keyword arguments are sent to `corner.hist2d` to generate the 2-D histogram plots. """ if quantiles is None: quantiles = [] if title_kwargs is None: title_kwargs = dict() if label_kwargs is None: label_kwargs = dict() # Try filling in labels from pandas.DataFrame columns. if labels is None: try: labels = xs.columns except AttributeError: pass # Deal with 1D sample lists. xs = np.atleast_1d(xs) if len(xs.shape) == 1: xs = np.atleast_2d(xs) else: assert len(xs.shape) == 2, "The input sample array must be 1- or 2-D." xs = xs.T assert xs.shape[0] <= xs.shape[1], "I don't believe that you want more " \ "dimensions than samples!" # Parse the weight array. if weights is not None: weights = np.asarray(weights) if weights.ndim != 1: raise ValueError("Weights must be 1-D") if xs.shape[1] != weights.shape[0]: raise ValueError("Lengths of weights must match number of samples") # Parse the parameter ranges. if range is None: if "extents" in hist2d_kwargs: logging.warn("Deprecated keyword argument 'extents'. " "Use 'range' instead.") range = hist2d_kwargs.pop("extents") else: range = [[x.min(), x.max()] for x in xs] # Check for parameters that never change. m = np.array([e[0] == e[1] for e in range], dtype=bool) if np.any(m): raise ValueError( ("It looks like the parameter(s) in " "column(s) {0} have no dynamic range. " "Please provide a `range` argument.").format(", ".join( map("{0}".format, np.arange(len(m))[m])))) else: # If any of the extents are percentiles, convert them to ranges. # Also make sure it's a normal list. range = list(range) for i, _ in enumerate(range): try: emin, emax = range[i] except TypeError: q = [0.5 - 0.5 * range[i], 0.5 + 0.5 * range[i]] range[i] = quantile(xs[i], q, weights=weights) if len(range) != xs.shape[0]: raise ValueError("Dimension mismatch between samples and range") # Parse the bin specifications. try: bins = [int(bins) for _ in range] except TypeError: if len(bins) != len(range): raise ValueError("Dimension mismatch between bins and range") try: hist_bin_factor = [float(hist_bin_factor) for _ in range] except TypeError: if len(hist_bin_factor) != len(range): raise ValueError("Dimension mismatch between hist_bin_factor and " "range") # Some magic numbers for pretty axis layout. K = len(xs) factor = 2.0 # size of one side of one panel if reverse: lbdim = 0.2 * factor # size of left/bottom margin trdim = 0.5 * factor # size of top/right margin else: lbdim = 0.5 * factor # size of left/bottom margin trdim = 0.2 * factor # size of top/right margin whspace = 0.05 # w/hspace size plotdim = factor * K + factor * (K - 1.) * whspace dim = lbdim + plotdim + trdim # Create a new figure if one wasn't provided. if fig is None: fig, axes = pl.subplots(K, K, figsize=(dim, dim)) else: try: axes = np.array(fig.axes).reshape((K, K)) except: raise ValueError("Provided figure has {0} axes, but data has " "dimensions K={1}".format(len(fig.axes), K)) # Format the figure. lb = lbdim / dim tr = (lbdim + plotdim) / dim fig.subplots_adjust(left=lb, bottom=lb, right=tr, top=tr, wspace=whspace, hspace=whspace) # Set up the default histogram keywords. if hist_kwargs is None: hist_kwargs = dict() # hist_kwargs["color"] = hist_kwargs.get("color", color) if smooth1d is None: hist_kwargs["histtype"] = hist_kwargs.get("histtype", "step") for i, x in enumerate(xs): # Deal with masked arrays. if hasattr(x, "compressed"): x = x.compressed() if np.shape(xs)[0] == 1: ax = axes else: if reverse: ax = axes[K - i - 1, K - i - 1] else: ax = axes[i, i] # Plot the histograms. # if i == 0: # color = 'k' # elif 1 <= i <= 3: # color = 'MediumAquaMarine' # elif 4 <= i <= 7: # color = 'Crimson' if i == 0: color = 'k' elif 1 <= i <= 2: color = 'MediumAquaMarine' elif 3 <= i <= 5: color = 'Crimson' # hist_kwargs["color"] = hist_kwargs.get("color", color) hist_kwargs["lw"] = hist_kwargs.get("lw", 2) if smooth1d is None: bins_1d = int(max(1, np.round(hist_bin_factor[i] * bins[i]))) n, _, _ = ax.hist(x, bins=bins_1d, weights=weights, color=color, range=np.sort(range[i]), **hist_kwargs) else: if gaussian_filter is None: raise ImportError("Please install scipy for smoothing") n, b = np.histogram(x, bins=bins[i], weights=weights, range=np.sort(range[i])) n = gaussian_filter(n, smooth1d) x0 = np.array(list(zip(b[:-1], b[1:]))).flatten() y0 = np.array(list(zip(n, n))).flatten() ax.plot(x0, y0, **hist_kwargs) if truths is not None and truths[i] is not None: ax.axvline(truths[i], color=truth_color) # Plot quantiles if wanted. if len(quantiles) > 0: qvalues = quantile(x, quantiles, weights=weights) for q in qvalues: ax.axvline(q, ls="dashed", color=color) if verbose: print("Quantiles:") print([item for item in zip(quantiles, qvalues)]) if show_titles: title = None if title_fmt is not None: # Compute the quantiles for the title. This might redo # unneeded computation but who cares. if len(quantiles) == 3: q_low, q_mid, q_high = quantile( x, [quantiles[0], quantiles[1], quantiles[2]], weights=weights) q_m, q_p = q_mid - q_low, q_high - q_mid elif len(quantiles) == 2: q_low, q_50, q_high = quantile( x, [quantiles[0], 0.5, quantiles[1]], weights=weights) q_m, q_p = q_50 - q_low, q_high - q_50 else: q_16, q_50, q_84 = quantile(x, [0.16, 0.5, 0.84], weights=weights) q_m, q_p = q_50 - q_16, q_84 - q_50 # Format the quantile display. fmt = "{{0:{0}}}".format(title_fmt).format title = r"${{{0}}}_{{-{1}}}^{{+{2}}}$" title = title.format(fmt(q_50), fmt(q_m), fmt(q_p)) # Add in the column name if it's given. if labels is not None: title = "{0} = {1}".format(labels[i], title) elif labels is not None: title = "{0}".format(labels[i]) if title is not None: if reverse: ax.set_xlabel(title, **title_kwargs) else: ax.set_title(title, **title_kwargs) # Set up the axes. ax.set_xlim(range[i]) if scale_hist: maxn = np.max(n) ax.set_ylim(-0.1 * maxn, 1.1 * maxn) else: ax.set_ylim(0, 1.1 * np.max(n)) ax.set_yticklabels([]) if max_n_ticks == 0: ax.xaxis.set_major_locator(NullLocator()) ax.yaxis.set_major_locator(NullLocator()) else: ax.xaxis.set_major_locator(MaxNLocator(max_n_ticks, prune="lower")) ax.yaxis.set_major_locator(NullLocator()) if i < K - 1: if top_ticks: ax.xaxis.set_ticks_position("top") [l.set_rotation(45) for l in ax.get_xticklabels()] else: ax.set_xticklabels([]) else: if reverse: ax.xaxis.tick_top() [l.set_rotation(45) for l in ax.get_xticklabels()] if labels is not None: if reverse: ax.set_title(labels[i], y=1.25, **label_kwargs) else: ax.set_xlabel(labels[i], **label_kwargs) # use MathText for axes ticks ax.xaxis.set_major_formatter( ScalarFormatter(useMathText=use_math_text)) for j, y in enumerate(xs): if np.shape(xs)[0] == 1: ax = axes else: if reverse: ax = axes[K - i - 1, K - j - 1] else: ax = axes[i, j] if j > i: ax.set_frame_on(False) ax.set_xticks([]) ax.set_yticks([]) continue elif j == i: continue # Deal with masked arrays. if hasattr(y, "compressed"): y = y.compressed() # if j == 0: # color = 'k' # elif 1 <= j <= 3 and 1 <= i <= 3: # color = 'LightSeaGreen' # elif 4 <= j <= 7 and 4 <= i <= 7: # color = 'Crimson' # elif 1 <= j <= 3 and 4 <= i <= 7: # # color = '#143cdb' # color = '#db8214' if j == 0: color = 'k' elif 1 <= j <= 2 and 1 <= i <= 2: color = 'LightSeaGreen' elif 3 <= j <= 5 and 3 <= i <= 5: color = 'Crimson' elif 1 <= j <= 2 and 3 <= i <= 5: # color = '#143cdb' color = '#db8214' hist2d(y, x, ax=ax, range=[range[j], range[i]], weights=weights, color=color, smooth=smooth, bins=[bins[j], bins[i]], **hist2d_kwargs) if truths is not None: if truths[i] is not None and truths[j] is not None: ax.plot(truths[j], truths[i], "s", color=truth_color) if truths[j] is not None: ax.axvline(truths[j], color=truth_color) if truths[i] is not None: ax.axhline(truths[i], color=truth_color) if max_n_ticks == 0: ax.xaxis.set_major_locator(NullLocator()) ax.yaxis.set_major_locator(NullLocator()) else: ax.xaxis.set_major_locator( MaxNLocator(max_n_ticks, prune="lower")) ax.yaxis.set_major_locator( MaxNLocator(max_n_ticks, prune="lower")) if i < K - 1: ax.set_xticklabels([]) else: if reverse: ax.xaxis.tick_top() [l.set_rotation(45) for l in ax.get_xticklabels()] if labels is not None: ax.set_xlabel(labels[j], **label_kwargs) if reverse: ax.xaxis.set_label_coords(0.5, 1.4) else: ax.xaxis.set_label_coords(0.5, -0.3) ax.tick_params(axis='x', labelsize=ticklabelsize) # use MathText for axes ticks ax.xaxis.set_major_formatter( ScalarFormatter(useMathText=use_math_text)) if j > 0: ax.set_yticklabels([]) else: if reverse: ax.yaxis.tick_right() [l.set_rotation(45) for l in ax.get_yticklabels()] if labels is not None: if reverse: ax.set_ylabel(labels[i], rotation=-90, **label_kwargs) ax.yaxis.set_label_coords(1.3, 0.5) else: ax.set_ylabel(labels[i], **label_kwargs) ax.yaxis.set_label_coords(-0.3, 0.5) ax.tick_params(axis='y', labelsize=ticklabelsize) # use MathText for axes ticks ax.yaxis.set_major_formatter( ScalarFormatter(useMathText=use_math_text)) axes[-1, -1].xaxis.set_label_coords(0.5, -0.3) # stupid label hack axes[-1, -1].tick_params(axis='x', labelsize=ticklabelsize) return fig
def run(img_path, conf, target_path): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") os.makedirs("output", exist_ok=True) classes = load_classes(conf.class_path) model = Darknet(conf.model_def, img_size=conf.img_size).to(device) if conf.weights_path.endswith(".weights"): # Load darknet weights model.load_darknet_weights(conf.weights_path) else: # Load checkpoint weights model.load_state_dict(torch.load(conf.weights_path)) model.eval() img = Image.open(img_path).convert("RGB") # print(img.size) img = img.resize(((img.size[0] // 32) * 32, (img.size[1] // 32) * 32)) # print(img.size) # img_array = np.array(img) # print("target shape ",img_array.shape) # img = img.resize((conf.img_size, conf.img_size)) img_array = np.array(img) img_tensor = pad_to_square(transforms.ToTensor()(img), 0)[0].unsqueeze(0) conf.img_size = img_tensor.shape[2] with torch.no_grad(): detections = model(img_tensor) detections = non_max_suppression(detections, conf.conf_thres, conf.nms_thres)[0] cmap = plt.get_cmap("tab20b") colors = [cmap(i) for i in np.linspace(0, 1, 20)] plt.figure() fig, ax = plt.subplots(1) ax.imshow(img_array) if detections is not None: # Rescale boxes to original image detections = rescale_boxes(detections, conf.img_size, img_array.shape[:2]) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item())) box_w = x2 - x1 box_h = y2 - y1 color = bbox_colors[int( np.where(unique_labels == int(cls_pred))[0])] # Create a Rectangle patch bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text( x1, y1, s=classes[int(cls_pred)], color="white", verticalalignment="top", bbox={ "color": color, "pad": 0 }, ) # Save generated image with detections plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) filename = img_path.split("/")[-1].split(".")[0] # plt.savefig(f"output/{filename}.png", bbox_inches="tight", pad_inches=0.0) plt.savefig(target_path, bbox_inches='tight', pad_inches=0.0) plt.close()
def detected(): parser = argparse.ArgumentParser() parser.add_argument("--image_folder", type=str, default="data/samples", help="path to dataset") parser.add_argument("--model_def", type=str, default="config/yolov3.cfg", help="path to model definition file") parser.add_argument("--weights_path", type=str, default="weights/yolov3.weights", help="path to weights file") parser.add_argument("--class_path", type=str, default="data/coco.names", help="path to class label file") parser.add_argument("--conf_thres", type=float, default=0.8, help="object confidence threshold") parser.add_argument("--nms_thres", type=float, default=0.4, help="iou thresshold for non-maximum suppression") parser.add_argument("--batch_size", type=int, default=1, help="size of the batches") parser.add_argument( "--n_cpu", type=int, default=0, help="number of cpu threads to use during batch generation") parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension") parser.add_argument("--checkpoint_model", type=str, help="path to checkpoint model") opt = parser.parse_args() print(opt) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") os.makedirs("output", exist_ok=True) # Set up model model = Darknet(opt.model_def, img_size=opt.img_size).to(device) if opt.weights_path.endswith(".weights"): # Load darknet weights model.load_darknet_weights(opt.weights_path) else: # Load checkpoint weights model.load_state_dict(torch.load(opt.weights_path)) model.eval() # Set in evaluation mode dataloader = DataLoader( ImageFolder(opt.image_folder, img_size=opt.img_size), batch_size=opt.batch_size, shuffle=False, num_workers=opt.n_cpu, ) classes = load_classes(opt.class_path) # Extracts class labels from file Tensor = torch.cuda.FloatTensor if torch.cuda.is_available( ) else torch.FloatTensor imgs = [] # Stores image paths img_detections = [] # Stores detections for each image index print("\nPerforming object detection:") prev_time = time.time() for batch_i, (img_paths, input_imgs) in enumerate(dataloader): # Configure input input_imgs = Variable(input_imgs.type(Tensor)) # Get detections with torch.no_grad(): detections = model(input_imgs) detections = non_max_suppression(detections, opt.conf_thres, opt.nms_thres) # Log progress current_time = time.time() inference_time = datetime.timedelta(seconds=current_time - prev_time) prev_time = current_time print("\t+ Batch %d, Inference Time: %s" % (batch_i, inference_time)) # Save image and detections imgs.extend(img_paths) img_detections.extend(detections) # Bounding-box colors cmap = plt.get_cmap("tab20b") colors = [cmap(i) for i in np.linspace(0, 1, 20)] print("\nSaving images:") # Iterate through images and save plot of detections for img_i, (path, detections) in enumerate(zip(imgs, img_detections)): print("(%d) Image: '%s'" % (img_i, path)) # Create plot img = np.array(Image.open(path)) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) # Draw bounding boxes and labels of detections if detections is not None: # Rescale boxes to original image detections = rescale_boxes(detections, opt.img_size, img.shape[:2]) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item())) box_w = x2 - x1 box_h = y2 - y1 color = bbox_colors[int( np.where(unique_labels == int(cls_pred))[0])] # Create a Rectangle patch bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text( x1, y1, s=classes[int(cls_pred)], color="white", verticalalignment="top", bbox={ "color": color, "pad": 0 }, ) # Save generated image with detections plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) filename = path.split("/")[-1].split(".")[0] plt.savefig(f"output/{filename}.jpg", bbox_inches="tight", pad_inches=0.0) plt.close()
def plot_detections(img_paths, img_detections, class_names, output_path): # bbox colors cmap = plt.get_cmap("tab20b") colors = [cmap(i) for i in np.linspace(0, 1, len(class_names))] print("\nSaving images:") os.makedirs(output_path, exist_ok=True) # Iterate through images and save plot of detections for img_i, (path, detections) in enumerate(zip(img_paths, img_detections)): print("(%d) Image: '%s'" % (img_i, path)) # Create plot img = np.array(Image.open(path)) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) # Draw bounding boxes and labels of detections if detections is not None: # Rescale boxes to original image detections = rescale_boxes(detections, opt.img_size, img.shape[:2]) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: print("\t+ Label: %s, Conf: %.5f" % (class_names[int(cls_pred)], cls_conf.item())) box_w = x2 - x1 box_h = y2 - y1 color = bbox_colors[int( np.where(unique_labels == int(cls_pred))[0])] # Create a Rectangle patch bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text( x1, y1, s=class_names[int(cls_pred)], color="white", verticalalignment="top", bbox={ "color": color, "pad": 0 }, ) # Save generated image with detections plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) filename = path.split("/")[-1].split(".")[0] fig.savefig("{}/{}.png".format(output_path, filename), bbox_inches="tight", pad_inches=0.0) plt.close()
elif line[1] == "NONE" or line[1] == "UNKNOWN": convertedData.append([line[0], 0]) else: pass if len(convertedData) > 0: x, y = zip(*convertedData) mobiledataAxis.plot(x, y, linestyle=LINESTYLE, marker=MARKER, linewidth=LINEWIDTH) # Plotting batteryAxis.yaxis.set_major_formatter(FuncFormatter(graphHelper.percentage_formatter)) batteryAxis.set_title("Battery Level") chargingAxis.yaxis.set_major_locator(yAxisMajorLocator) chargingAxis.yaxis.set_minor_locator(NullLocator()) chargingAxis.yaxis.set_major_formatter(FuncFormatter(graphHelper.trueFalse_formatter)) chargingAxis.set_title("Device Charging") chargingAxis.set_ylim([trueMin, trueMax]) screenAxis.yaxis.set_major_locator(yAxisMajorLocator) screenAxis.yaxis.set_minor_locator(NullLocator()) screenAxis.yaxis.set_major_formatter(FuncFormatter(graphHelper.onOff_formatter)) screenAxis.set_title("Screen Status") screenAxis.set_ylim([trueMin, trueMax]) wifiAxis.yaxis.set_major_locator(yAxisMajorLocator) wifiAxis.yaxis.set_minor_locator(NullLocator()) wifiAxis.yaxis.set_major_formatter(FuncFormatter(graphHelper.trueFalse_formatter)) wifiAxis.set_title("WiFi Connected") wifiAxis.set_ylim([trueMin, trueMax])
def print_detections(results_path, class_path="data/classes.names", n_cpu=0): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Get dataloader dataloader = DataLoader( ImageFolder(results_path), batch_size=1, shuffle=False, num_workers=n_cpu, ) classes = load_classes(class_path) # Extracts class labels from file Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor # Bounding-box colors cmap = plt.get_cmap("tab20b") colors = [cmap(i) for i in np.linspace(0, 1, 20)] print("\nSaving images:") for img_i, (path, detections) in enumerate(dataloader): path = path[0] detections = detections[0] print("(%d) Image: '%s'" % (img_i, path)) # Create plot img = np.array(Image.open(path)) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) # Draw bounding boxes and labels of detections if detections is not None: unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item())) box_w = x2 - x1 box_h = y2 - y1 color = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])] # Create a Rectangle patch bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text( x1, y1, s=classes[int(cls_pred)], color="white", verticalalignment="top", bbox={"color": color, "pad": 0}, ) # Save generated image with detections path = path[:-4]+'_bbx.jpg' print(path) plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) plt.savefig(path, bbox_inches="tight", pad_inches=0.0) plt.close()
bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Add label plt.text( x1, y1, s=classes[int(cls_pred)], color="white", verticalalignment="top", bbox={ "color": color, "pad": 0 }, ) # Save generated image with detections plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) filename = path.split("/")[-1].split(".")[0] plt.savefig(f"output/{filename}.png", bbox_inches="tight", pad_inches=0.0) plt.close()
def draw(variationID, distortion): """This function generates the optical illusion figure. The function should return a bokeh figure of size 500x500 pixels. :param variationID: select which variation to draw (range: 0 to getNumVariations()-1) :param distortion: the selected distorion (range: 0.0 to 1.0) :return handle to bokeh figure that contains the optical illusion """ illusion_selector = variationID + 1 distort = (distortion * 2 - 1) * 0.15 ## Create bokeh figure and disable axes and tools bokehFig = figure(plot_width=500, plot_height=500, x_range=(0, 1), y_range=(0, 1)) #p.outline_line_color = None bokehFig.toolbar.active_drag = None bokehFig.toolbar.logo = None bokehFig.toolbar_location = None bokehFig.xaxis.visible = None bokehFig.yaxis.visible = None bokehFig.xgrid.grid_line_color = None bokehFig.ygrid.grid_line_color = None # Load the parameters for the selected illusion params_dict = illusion_variation_dict[illusion_selector] img_scale = params_dict["image_scale"] pattern_linewidth = params_dict["pattern_linewidth"] density = params_dict["density"] purple_width = params_dict["purple_width"] hatch_1 = params_dict["hatch_1"] hatch_2 = params_dict["hatch_2"] pattern_angle = params_dict["pattern_angle"] originalID = params_dict["originalID"] # print(pattern_angle) ### Draw the nine background squares # The width of the line of the pattern. This is a parameter of Matplotlib. matplotlib.rcParams['hatch.linewidth'] = pattern_linewidth # Container for all the elements to be drawn patches_arr = [] sizes = np.arange(0., pattern_square_width * 3, pattern_square_width) h1 = hatch_1 h2 = hatch_2 if pattern_angle is None: # If we don't need an angle applied to the background pattern # Draw the 3x3 pattern: simple version for size_1 in sizes: for size_2 in sizes: patches_arr += get_patches(size_1, size_2, dist, density, hatch_1=h1, hatch_2=h2) if h1 == hatch_2: h1 = hatch_1 h2 = hatch_2 else: h1 = hatch_2 h2 = hatch_1 ### Draw the three purple squares # The location of the purple square purple_loc = pattern_square_width + dist / 2 # the size of the square current_size = pattern_square_width - dist # Uncomment to see the value of the distortion # print("Distort input: {}".format(distort)) purple_patches = [] for i in range(3): # Make distortion proportional to the size of the square distort_ = distort * current_size # print "Distort value for square {}: {}".format(i + 1, distort_) if i == 0: square, rhombus_degrees = get_distorted_square( purple_loc, current_size, purple_width, distort_, print_degrees=True, reverse_distort=False) purple_patches.append(square) elif i == 1: # Distort middle square in the opposite direction purple_patches.append( get_distorted_square(purple_loc, current_size, purple_width, distort_, print_degrees=False, reverse_distort=True)) else: purple_patches.append( get_distorted_square(purple_loc, current_size, purple_width, distort_, reverse_distort=False)) # Update location and size for the next square to be drawn purple_loc += dist current_size -= dist * 2 ### Render final figure fig = plt.figure(figsize=(img_scale, img_scale), dpi=100) #ax = fig.add_subplot(111, aspect='equal') # fig = plt.figure(figsize=(img_scale,img_scale), dpi=100, frameon=False) ax = fig.add_axes([0, 0, 1, 1]) if pattern_angle is None: for p in patches_arr: # add_patch adds a patch to the current figure ax.add_patch(p) else: ## Draw the 3x3 background pattern: more complicated version def display_single_pattern(size_1, size_2, hatches): """Plot a single square of the pattern :param size_1, size_2: starting coordinates of this plot""" a, b, c, d = size_1[0], size_1[1], size_2[0], size_2[1] for i in range(4): # print("this is hatches: ", hatches) img = Image.open(hatches[i]) width, height = img.size # Crop the image with PIL library, because Matplotlib adds a little white border img = img.crop((3, 3, width - 3, height - 3)) plt.imshow(img, interpolation="none", aspect="equal", extent=(a, b, c, d), origin='upper') a += dist b -= dist c += dist d -= dist # Get the list of patterns (redraw or from disk) hatches_1 = plot_pattern(pattern_angle) hatches_2 = plot_pattern(-pattern_angle) print("Their Hatches: ", hatches_1) sizes = np.arange(0., pattern_square_width * 4, pattern_square_width) reverse = True # A switch for the angle for size_1 in window(sizes): for size_2 in window(sizes): if reverse: display_single_pattern(size_1, size_2, hatches_2) else: display_single_pattern(size_1, size_2, hatches_1) reverse = not reverse # Display purple squares for p in purple_patches: ax.add_patch(p) total_figure_size = pattern_square_width * 3 # Add a red cross in the center of the image plt.scatter([total_figure_size / 2], [total_figure_size / 2], color='#a10000', marker="+", s=150, lw=2, zorder=1) # Clean extra whitespace around the plot and remove axes axes = plt.gca() axes.set_xlim([0., total_figure_size]) axes.set_ylim([0., total_figure_size]) plt.axis('off') axes.xaxis.set_major_locator(NullLocator()) axes.yaxis.set_major_locator(NullLocator()) # convert matplotfig to bitmap and display it on bokeh figure bokehFig.image_rgba([np.flip(fig2data(fig), 0)], x=[0], y=[0], dw=[1], dh=[1]) #img = Image.fromarray(fig2data(fig), 'RGBA') #img.save('my.png') plt.close(fig) return bokehFig