예제 #1
0
def _vis_proposals(im, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    class_name = 'obj'
    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1],
                          fill=False,
                          edgecolor='red',
                          linewidth=3.5))
        ax.text(bbox[0],
                bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14,
                color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
예제 #2
0
def visualize_image(digits, num_width, num_height, mode=None, dir=None):
    for h in range(num_height):
        for w in range(num_width):
            # 画像を水平方向に連結していく
            if w != 0:
                tmp_img = np.hstack((tmp_img, digits[w + h * num_width]))
            else:
                tmp_img = digits[w + h * num_width]

        # 画像を垂直方向に連結する
        if h != 0:
            img = np.vstack((img, tmp_img))
        else:
            img = tmp_img

    #表示モード
    if mode == "show":
        plt.imshow(img, cmap='gray')
        plt.axis('off')
        plt.show()
    #保存モード
    elif mode == "save":
        if not dir == None:  #ファイル名がしていされていれば
            pilImg = Image.fromarray(img)  # uintに変換
            pilImg.save(dir)
예제 #3
0
def to_matrix(edges):
    exist = []
    for one in edges:
        for i in range(0, 2):
            if one[i] not in exist:
                exist.append(one[i])
    G = nx.Graph()
    G.add_nodes_from(exist)  # 添加节点和边
    G.add_edges_from([(u, v, {"weight": 1}) for (u, v) in edges])
    part = community.best_partition(G)
    cname = ['#FF6600', '#FFCC33', '#009966', '#0099CC', '#FF6666', '#666699']
    color = [cname[part.get(node) % 6] for node in G.nodes()]
    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(
        G,
        pos,
        node_color=color,
        node_size=[s['size'] for (n, s) in G.nodes(data=True)])
    nx.draw_networkx_edges(
        G,
        pos,
        width=[float(d['weight'] * 0.05) for (u, v, d) in G.edges(data=True)])
    nx.draw_networkx_labels(G, pos, font_size=8)
    nx.write_gexf(G, '111.gexf')
    plt.axis('off')
예제 #4
0
def compareAnimals(animals, precision):
    """Assumes animals is a list of animals, precision an int >= 0
       Builds a table of Euclidean distance between each animal"""
    #Get labels for columns and rows
    columnLabels = []
    for a in animals:
        columnLabels.append(a.getName())
    rowLabels = columnLabels[:]
    tableVals = []
    #Get distances between pairs of animals
    #For each row
    for a1 in animals:
        row = []
        #For each column
        for a2 in animals:
            if a1 == a2:
                row.append('--')
            else:
                distance = a1.distance(a2)
                row.append(str(round(distance, precision)))
        tableVals.append(row)
    #Produce table
    table = numpy.table(rowLabels=rowLabels,
                        colLabels=columnLabels,
                        cellText=tableVals,
                        cellLoc='center',
                        loc='center')
    table.auto_set_font_size(False)
    table.set_fontsize(10)
    table.scale(1, 2.5)
    numpy.axis('off')
    numpy.savefig('distances')
예제 #5
0
def plot_dataset(X, y, axes):
    plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], "bs")
    plt.plot(X[:, 0][y == 1], X[:, 1][y == 1], "ms")
    plt.axis(axes)
    plt.grid(True, which='both')
    plt.xlabel(r"$x_1$", fontsize=20)
    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
예제 #6
0
    def draw(self):
        positions = {}
        Tree.get_positions(self, positions, x=(0, 10), y=(0, 10))
        g = self.to_graph()

        plt.axis('on')
        nx.draw_networkx(g, positions, node_size=1500, font_size=24, node_color='g')
        plt.show()
예제 #7
0
def visualize(win,
              rgb=False,
              imSize=None,
              hidDims=None,
              ordered=False,
              saveFile=None,
              normalize=False):

    if rgb:
        visualizeRGB(win,
                     imSize=imSize,
                     hidDims=hidDims,
                     saveFile=saveFile,
                     normalize=normalize,
                     ordered=ordered)
        return
    w = win - np.min(win)
    w /= np.max(w)
    numVis, numHid = w.shape
    if imSize is None:
        imSize = (int(np.sqrt(numVis)), int(np.sqrt(numVis)))
    assert (imSize[0] * imSize[1] == numVis)
    if hidDims is None:
        tmp = min(20, int(np.ceil(np.sqrt(numHid))))
        hidDims = (tmp, tmp)

    if ordered:
        valList = []
        for h in range(numHid):
            wtmp = w[:, h] - np.mean(w[:, h])
            val = wtmp.dot(wtmp)
            valList.append(val)
        order = np.argsort(valList)[::-1]

    margin = 1
    img = np.zeros(
        (hidDims[0] * (imSize[0] + margin), hidDims[1] * (imSize[1] + margin)))
    for h in range(min(hidDims[0] * hidDims[1], numHid)):
        i = h / hidDims[1]
        j = h % hidDims[1]
        if ordered:
            hshow = order[h]
        else:
            hshow = h
        content = (np.reshape(w[:, hshow], imSize))  # - np.mean(w[:,hshow]))
        img[(i * (imSize[0] + margin)):(i * (imSize[0] + margin) + imSize[0]),
            (j * (imSize[1] + margin)):(j * (imSize[1] + margin) +
                                        imSize[1])] = content
    plt.figure()
    plt.axis('off')
    plt.imshow(img, cmap=plt.cm.Greys_r, interpolation="nearest")
    if saveFile is not None:
        plt.tight_layout()
        plt.savefig('./figures/' + saveFile + ".svg",
                    bbox_inches='tight',
                    dpi=2000)

    plt.show()
예제 #8
0
def visualizeRGB(win,
                 imSize=None,
                 hidDims=None,
                 ordered=False,
                 saveFile=None,
                 normalize=False):
    w = win - np.min(win)
    w /= np.max(w)
    numVis, numHid = w.shape
    numVis /= 3

    if imSize is None:
        imSize = (int(np.sqrt(numVis)), int(np.sqrt(numVis)))
    assert (imSize[0] * imSize[1] == numVis)

    if hidDims is None:
        tmp = min(20, int(np.ceil(np.sqrt(numHid))))
        hidDims = (tmp, tmp)
    margin = 2
    img = np.zeros((hidDims[0] * (imSize[0] + margin),
                    hidDims[1] * (imSize[1] + margin), 3))

    if ordered:
        valList = []
        for h in range(numHid):
            wtmp = w[:, h] - np.mean(w[:, h])
            val = wtmp.dot(wtmp)
            valList.append(val)
        order = np.argsort(valList)[::-1]

    for h in range(min(hidDims[0] * hidDims[1], numHid)):
        i = h / hidDims[1]
        j = h % hidDims[1]
        if ordered:
            hshow = order[h]
        else:
            hshow = h
        for co in range(3):
            tmp = np.reshape(w[(numVis * co):(numVis * (co + 1)), hshow],
                             imSize)
            if normalize:
                tmp -= tmp.min()
                tmp /= tmp.max()
            img[(i * (imSize[0] + margin)):(i * (imSize[0] + margin) +
                                            imSize[0]),
                (j * (imSize[1] + margin)):(j * (imSize[1] + margin) +
                                            imSize[1]), co] = tmp

    plt.axis('off')
    if saveFile is not None:
        plt.tight_layout()
        plt.savefig('./figures/' + saveFile + ".svg",
                    bbox_inches='tight',
                    dpi=2000)
    else:
        plt.imshow(img)

    plt.show()
예제 #9
0
def grafico(e):
    plt.plot(k, np.repeat(dfa, N+1), 'k-')
    plt.plot(k, vff, 'go')
    plt.plot(k, vaf, 'ro')
    plt.plot(k, vbf, 'bo')
    
    plt.axis([0, N, dfa - e, dfa + e])
    
    plt.grid(True)
    plt.show()
예제 #10
0
def draw_boxes_on_image(image_path: str,
                        boxes: np.ndarray,
                        scores: np.ndarray,
                        labels: np.ndarray,
                        label_names: List[str],
                        score_thresh: float = 0.5,
                        save_path: str = 'result'):
    """Draw boxes on images."""
    image = np.array(PIL.Image.open(image_path))
    plt.figure()
    _, ax = plt.subplots(1)
    ax.imshow(image)

    image_name = image_path.split('/')[-1]
    print("Image {} detect: ".format(image_name))
    colors = {}
    for box, score, label in zip(boxes, scores, labels):
        if score < score_thresh:
            continue
        if box[2] <= box[0] or box[3] <= box[1]:
            continue
        label = int(label)
        if label not in colors:
            colors[label] = plt.get_cmap('hsv')(label / len(label_names))
        x1, y1, x2, y2 = box[0], box[1], box[2], box[3]
        rect = plt.Rectangle((x1, y1),
                             x2 - x1,
                             y2 - y1,
                             fill=False,
                             linewidth=2.0,
                             edgecolor=colors[label])
        ax.add_patch(rect)
        ax.text(x1,
                y1,
                '{} {:.4f}'.format(label_names[label], score),
                verticalalignment='bottom',
                horizontalalignment='left',
                bbox={
                    'facecolor': colors[label],
                    'alpha': 0.5,
                    'pad': 0
                },
                fontsize=8,
                color='white')
        print("\t {:15s} at {:25} score: {:.5f}".format(
            label_names[int(label)], str(list(map(int, list(box)))), score))
    image_name = image_name.replace('jpg', 'png')
    plt.axis('off')
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.savefig("{}/{}".format(save_path, image_name),
                bbox_inches='tight',
                pad_inches=0.0)
    plt.cla()
    plt.close('all')
예제 #11
0
    def retrieve_input():
        text = T.get("1.0",'end-1c')

        
        #Functions: Remove stopwords, lemmatize the words, tokenize the words, remove punctuation
        def remove_stopwords(text):
          sw=stopwords.words('french')
          #sw=['de','al','se','mi','me','te','le','les','nos','os','les','tu','el','me','un','la','y''que','lo','en','es','a','no','para','una','él','pero','tien','todo','o','está','día','persona','cuando','caso','si','casa','había','muy','ella','esta']
          words = [w for w in text if not w in sw]
          return words
        def make_lower(text):
          words= text.lower()
          return words
        def remove_punc(text):
          words = [word for word in text if word.isalpha()]
          return words
        def lemmatize_words(text):
          porter=PorterStemmer()
          words=[porter.stem(word) for word in text]
          return words

        words = nltk.tokenize.word_tokenize(text)
        words=remove_punc(words)
        words=lemmatize_words(words)
        words=remove_stopwords(words)


        word_dist = nltk.FreqDist(words)
        top_N = 50
        rslt = pd.DataFrame(word_dist.most_common(top_N),
        columns=['Word', 'Frequency'])
        stringss = rslt['Word'][0]+" was your most common word!"
        gameDisplay.fill(light_blue);
        message_to_screen(stringss, black, 40, 100, 100)
        pygame.display.update() 


        
        newstr=''
        for i in words:
          newstr=newstr+' '+i
        from PIL import Image
        from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
        import matplotlib.pyplot as plt

        newstr=''
        for i in words:
          newstr=newstr+' '+i
        wordcloud = WordCloud().generate(newstr)

        # Display the generated image:
        plt.imshow(wordcloud, interpolation='bilinear')
        plt.axis("off")
        plt.show()
        wordcloud.to_file("cloud.tiff")
예제 #12
0
def plot_harris_points(image, filtered_coords):
    """
        画像中に見つかったコーナーを描画
    """
    plt.figure()
    plt.gray()
    plt.imshow(image)
    plt.plot([p[1] for p in filtered_coords], [p[0] for p in filtered_coords],
             '*')
    plt.axis('off')
    plt.show()
예제 #13
0
    def draw(self):
        positions = {}
        Tree.get_positions(self, positions, x=(0, 10), y=(0, 10))
        g = self.to_graph()

        plt.axis('on')
        nx.draw_networkx(g,
                         positions,
                         node_size=1500,
                         font_size=24,
                         node_color='g')
        plt.show()
예제 #14
0
def print_mislabeled_images(classes, X, y, p):
    a = p + y
    mislabeled_indices = np.asarray(np.where(a == 1))
    plt.rcParams['figure.figsize'] = (40.0, 40.0)  # set default size of plots
    num_images = len(mislabeled_indices[0])
    for i in range(num_images):
        index = mislabeled_indices[1][i]
        plt.subplot(2, num_images, i + 1)
        plt.imshow(X[:, index].reshape(64, 64, 3), interpolation='nearest')
        plt.axis('off')
        plt.title("Prediction: " + classes[int(p[0, index])].decode("utf-8") +
                  " \n Class: " + classes[y[0, index]].decode("utf-8"))
예제 #15
0
def draw_circle(c,r):
	t = arange(0,1.01,.01)*2*pi
	x = r*cos(t) + c[0]
	y = r*sin(t) + c[1]
	plt.plot(x,y,'b',linewidth=2)
	plt.imshow(im)
	if circle:
		for p in locs:
			plt.draw_circle(p[:2],p[2])
	else:
		plt.plot(locs[:,0],locs[:,1],'ob')
	plt.axis('off')
예제 #16
0
파일: tSNE.py 프로젝트: wuzhan11/BOWDANet
def save_image(im, path):
    for i in range(im.shape[0]):
        for j in range(im[i].shape[0]):
            #            image = Image.fromarray(im[i][j])
            #            image = image.resize((224,224))
            #            image = np.array(image)
            plt.figure(str(i) + '_' + str(j))
            plt.imshow(im[i][j], cmap='binary_r')
            plt.axis('off')
            plt.xticks([]), plt.yticks([])  #隐藏坐标线
            fig = plt.gcf()
            dna1name = 'Conter' + str(i) + '_' + str(j) + '.png'
            fig.savefig(path + 'IM/' + dna1name, dpi=100)
예제 #17
0
    def scatterPlot(self):
        axis = [
            min(self.tdata[:, 0]) - 1,
            max(self.tdata[:, 0]) + 1,
            min(self.tdata[:, 1]) - 1,
            max(self.tdata[:, 1]) + 1
        ]

        setx = np.linspace(axis[0], axis[1])
        plt.scatter(self.tdata[:, 0], self.tdata[:, 1])
        plt.plot(setx, self.modelFunction(setx))
        plt.axis(axis)
        plt.show()
예제 #18
0
def the_word(type):
    words = ''
    df = data[data[type] == 1]['comment_text']
    for i in df:
        i = i.lower()
        words = words + i + ' '
    wordcloud_vis = WordCloud(collocations=False, width=800,
                              height=600).generate(words)
    plt.figure(figsize=(10, 8), facecolor='k')
    plt.imshow(wordcloud_vis)
    plt.axis("off")
    plt.tight_layout(pad=0)
    plt.show()
def get_trajectories_for_DF(DF):
    GetXYS=ct.get_xys(DF)
    xys_s=ct.get_xys_s(GetXYS['xys'],GetXYS['Nmin'])
    plt.figure(figsize=(5, 5),frameon=False)
    for m in list(range(9)):
        plt.plot()
        plt.subplot(3,3,m+1)
        xys_s_x_n=xys_s[m]['X']-min(xys_s[m]['X'])
        xys_s_y_n=xys_s[m]['Y']-min(xys_s[m]['Y'])
        plt.plot(xys_s_x_n,xys_s_y_n)
        plt.axis('off')
        axes = plt.gca()
        axes.set_ylim([0,125])
        axes.set_xlim([0,125])
예제 #20
0
def display_images(outputs,
                   outputPath=None,
                   inputs=None,
                   gt=None,
                   is_colormap=True,
                   is_rescale=True,
                   start=0,
                   end=10,
                   imgName=None):
    plt.rcParams.update({'figure.max_open_warning': 0})
    gc.disable()
    # Create a folder
    if outputPath is None:
        #if not os.path.exists(os.path.join(os.getcwd(),'depthMapOutput')):
        if not os.path.exists(os.path.join(args.outputpath(),
                                           'depthMapOutput')):
            os.mkdir(os.path.join(args.outputpath(), 'depthMapOutput'))
        print('Directory for depth mask outputs : {}'.format(
            os.path.join(args.outputpath(), 'depthMapOutput')))

    plasma = plt.get_cmap('plasma')

    shape = (outputs[0].shape[0], outputs[0].shape[1], 3)
    #print(shape)

    #for i in range(end-start):
    for i in np.arange(end - start):

        if is_colormap:
            rescaled = outputs[i][:, :, 0]
            #print(rescaled.shape)
            if is_rescale:
                rescaled = rescaled - np.min(rescaled)
                rescaled = rescaled / np.max(rescaled)
            #print(rescaled.shape)
            # img = Image.fromarray(plasma(rescaled)[:,:,:3],mode="RGB")
            # img.save(f"test{str(start)}.jpg")
            plt.figure(figsize=(2.24, 2.24), dpi=100)
            plt.imshow(plasma(rescaled)[:, :, :3])
            plt.axis("off")
            #plt.savefig(f"test{str(start)}.jpg")
            name = os.path.basename(imgName[i])
            plt.savefig(os.path.join(os.getcwd(), 'depthMapOutput', name))
        start += 1
        [print(start) if start / 500 in range(1000) else None]
    gc.enable()
    #gc.get_threshold()
    gc.collect()
예제 #21
0
 def plot_x_rec(self, x_rec_list):
     # Plot all reconstructed samples along epochs
     # input: x_rec_list size=(num_sampling, num_img, rows, cols, dim).
     cur_path = os.getcwd()
     if not os.path.exists('{0}/Images'.format(cur_path)):
         os.makedirs('Images')
     plt.figure(figsize=(5,5))
     for s in range(len(x_rec_list)):
         for i in range(x_rec_list[s].shape[0]):
             plt.subplot(1, x_rec_list[s].shape[0], i+1)
             x_rec_s_i = np.squeeze(x_rec_list[s][i], axis=2)
             plt.imshow(x_rec_s_i, interpolation='nearest', cmap='gray')
             plt.axis('off')
         plt.tight_layout()
         plt.savefig("Images/Image_{0}.png".format(s))
         plt.close()
예제 #22
0
    def comparision_piechart(username):##function declaration to show number of positive and negative comments and plot a pie-chart
    media_id = fetch_post_id(username)
    request_url = (BASE_URL + 'media/%s/comments/?access_token=%s') % (media_id, app_access_token)
    print 'GET request url : %s' % (request_url)
    comment_info = requests.get(request_url).json()
    if comment_info['meta']['code'] == 200:
        if len(comment_info['data']):
            for x in range(0, len(comment_info['data'])):
                comment_id = comment_info['data'][x]['id']
                comment_text = comment_info['data'][x]['text']
                blob = TextBlob(comment_text, analyzer=NaiveBayesAnalyzer())
                if (blob.sentiment.p_neg > blob.sentiment.p_pos):
                    print 'Negative comment : %s' % (comment_text)



            for y in range(0, len(comment_info['data'])):
                comment_id = comment_info['data'][y]['id']
                comment_text = comment_info['data'][y]['text']
                blob = TextBlob(comment_text, analyzer=NaiveBayesAnalyzer())
                if (blob.sentiment.p_neg < blob.sentiment.p_pos):
                    print 'positive comment : %s' % (comment_text)
                    a = y + 1  # positive comments
                    b = x - y  # negative comments
                    print "No. of Positive comments: %s" % (a)
                    print "No. of negative comments: %s" % (b)
                    c = a + b
                    print "Total no. of comments: %s" %(c)
                    
                    
                   
                    #commands to plot pychart
                    labels = 'Positive ', 'Negative'
                    sizes = [a, b]
                    colors = ['blanchedalmond', 'aliceblue']
                    explode = (0.1, 0)  # explode 1st slice
                    plt.pie(sizes, explode=explode, labels=labels, colors=colors,
                            autopct='%1.1f%%', shadow=True, startangle=140)

                    plt.axis('equal')
                    plt.show()


        else:
            print 'Comments not found on the post!'
    else:
        print 'Status code other than 200 received!'
예제 #23
0
    def plot_r_target(self):
        """
        Plot the target reflection spectrum
        
        """
        fig_tgt = plt.figure()
        ax_tgt = fig_tgt.add_subplot(111)
        plt.plot(self.disp_data.wvlen_vec, self.r_target, 'g.', label='Target')
        plt.axis([
            min(self.disp_data.wvlen_vec_fine),
            max(self.disp_data.wvlen_vec_fine), -0.01, 1.01
        ])
        plt.xlabel('wavelength ($\mu$m)')
        plt.ylabel('reflectivity')
        plt.legend()

        plt.show()
예제 #24
0
def fetch(Handle):
    root.destroy()
    summary = {
        "Compilation": 0,
        "Runtime": 0,
        "Wrong": 0,
        "Accepted": 0,
        "Time": 0
    }
    url = "https://codeforces.com/submissions/" + Handle + "/page/"
    source = req.get(url + "1")
    soup = bs(source.text, "lxml")
    no = len(soup.find_all("span", class_="page-index"))
    page_no = i = 1
    while page_no <= no:
        source = req.get(url + str(page_no))
        soup = bs(source.text, "lxml")
        table = soup.find_all("tr")
        page_no = page_no + 1
        for tag in range(26, len(table) - 1):
            required = table[tag].find_all("td", class_="status-small")
            contest_name = required[1].a.text.strip()
            try:
                result = required[2].span.span.text
            except:
                result = required[2].span.text
            result = result.split(" ")
            length = len(result)
            if length == 1:
                print(Fore.GREEN + str(i) + " : " + contest_name)
            if length == 2:
                print(Fore.CYAN + str(i) + " : " + contest_name)
            if length == 6:
                print(Fore.BLUE + str(i) + " : " + contest_name)
            if length == 5:
                if result[0] == "Wrong":
                    print(Fore.RED + str(i) + " : " + contest_name)
                else:
                    print(Fore.WHITE + str(i) + " : " + contest_name)
            summary[result[0]] += 1
            print(Style.RESET_ALL, end="")
            i = i + 1

    plt.axis("equal")
    plt.pie(summary.values(), labels=summary.keys(), autopct=None)
    plt.show()
예제 #25
0
def save_cloud_fig(data_in, x1, x2, y1, y2, font_size_label, name):

    in_sep = max(loc for loc, val in enumerate(name) if val == '/')

    str_time = name[in_sep + 1:in_sep + 18]

    yyyy = str_time[0:4]
    mm = str_time[5:7]
    dd = str_time[8:10]

    hh = str_time[11:13]
    MM = str_time[13:15]
    ss = str_time[15:17]

    timestamp = str(dd) + '/' + str(mm) + '/' + str(yyyy) + ' ' + str(
        hh) + ':' + str(MM) + ':' + str(ss)
    #-----------------------------------------------------------------------------#
    #-----------------------------------------------------------------------------#
    fig = plt.figure(1)
    #-----------------------------------------------------------------------------#

    fig_cloud = plt.subplot2grid((6, 2), (2, 1), rowspan=4, colspan=1)
    #-   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -#
    plt.imshow(data_in, aspect=1)

    plt.title(timestamp)
    #-   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -#
    plt.axis([x1, x2, y1, y2])
    plt.xlabel(r'$pixel$', fontsize=font_size_label)
    fig_cloud.xaxis.set_label_position("bottom")
    #plt.xticks([0,512,1024], fontsize = font_size_ticks)
    fig_cloud.xaxis.tick_bottom()

    plt.ylabel(r'$pixel$', fontsize=font_size_label)
    fig_cloud.yaxis.set_label_position("right")
    #plt.yticks([0,512,1024], fontsize = font_size_ticks)
    fig_cloud.yaxis.tick_right()
    #-----------------------------------------------------------------------------#

    #-----------------------------------------------------------------------------#
    fig.savefig(str(name) + '.png', bbox_inches='tight', dpi=300)
    #-----------------------------------------------------------------------------#
    #-----------------------------------------------------------------------------#


###############################################################################
예제 #26
0
def paint():
    a1 = df[df.监控等级 == 3].入库
    a2 = df[df.监控等级 == 3].营业收入
    b1 = df[df.监控等级 == 2].入库
    b2 = df[df.监控等级 == 2].营业收入
    c1 = df[df.监控等级 == 1].入库
    c2 = df[df.监控等级 == 1].营业收入
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12)
    plt.grid()
    plt.axis([0, 1e6, 0, 1e8])
    plt.scatter(a1, a2, c='r', marker='.')
    plt.scatter(b1, b2, c='y', marker='.')
    plt.scatter(c1, c2, c='g', marker='.')
    plt.xlabel(u'入库', fontproperties=font)
    plt.ylabel(u'营业收入', fontproperties=font)
    plt.show()
    print('作图运行时间为:{}s'.format(clock()))
예제 #27
0
def imgOut(epoch, generator):
    rand_nums = np.random.randint(0, x_test_hr.shape[0], size=1)
    image_batch_hr = denormalize(x_test_hr[rand_nums])
    image_batch_lr = x_test_lr[rand_nums]
    gen_img = generator.predict(image_batch_lr)
    generated_image = denormalize(gen_img)
    image_batch_lr = denormalize(image_batch_lr)
    image_batch_bc = upsample(image_batch_lr, 4)

    plt.figure(figsize=(15, 5))

    dim = (1, 4)  # 4 wide

    # lowres
    plt.subplot(dim[0], dim[1], 1)
    plt.title('Low Res')
    plt.imshow(image_batch_lr[0], interpolation='nearest')
    plt.axis('off')

    # naive resize
    plt.subplot(dim[0], dim[1], 2)
    plt.title('Naive Resize')
    plt.imshow(image_batch_bc[0], interpolation='nearest')
    plt.axis('off')

    # generated
    plt.subplot(dim[0], dim[1], 3)
    plt.title('Generated SR')
    plt.imshow(generated_image[0], interpolation='nearest')
    plt.axis('off')

    # truth
    plt.subplot(dim[0], dim[1], 4)
    plt.title('Truth')
    plt.imshow(image_batch_hr[0], interpolation='nearest')
    plt.axis('off')

    # save file
    plt.tight_layout()
    plt.savefig(imgSav % epoch)
    plt.close('all')

    # learning gif images
    me_dir = os.path.join('C:\\', 'Users', 'cruze', 'Documents', 'CS767',
                          'finalProj--')
    me_path = os.path.join(me_dir, 'lowresme.jpg')
    me = Image.open(me_path)
    me = np.expand_dims(me, axis=0)
    me_lr = np.array(me)
    me_lr_norm = normalize(me_lr)
    gen_img = generator.predict(me_lr_norm)
    generated_image = denormalize(gen_img)
    plt.imshow(generated_image[0])
    plt.savefig(imgMeSav % epoch)
    plt.close('all')
예제 #28
0
def plot(tf_confidence, num_groundtruthbox):
    """
    从上到下截取tf_confidence, 计算并画图
    :param tf_confidence: np.array, 存放所有检测框对应的tp或fp和置信度
    :param num_groundtruthbox: int, 标注框的总数
    """
    fp_list = []
    recall_list = []
    precision_list = []
    auc = 0
    mAP = 0
    for num in range(len(tf_confidence)):
        arr = tf_confidence[:(num + 1), 0]  # 截取, 注意要加1
        tp = np.sum(arr)
        fp = np.sum(arr == 0)
        recall = tp / num_groundtruthbox
        precision = tp / (tp + fp)
        auc = auc + recall
        mAP = mAP + precision

        fp_list.append(fp)
        recall_list.append(recall)
        precision_list.append(precision)

    auc = auc / len(fp_list)
    mAP = mAP * max(recall_list) / len(recall_list)

    plt.figure()
    plt.title('ROC')
    plt.xlabel('False Positives')
    plt.ylabel('True Positive rate')
    plt.ylim(0, 1)
    plt.plot(fp_list, recall_list, label='AUC: ' + str(auc))
    plt.legend()

    plt.figure()
    plt.title('Precision-Recall')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.axis([0, 1, 0, 1])
    plt.plot(recall_list, precision_list, label='mAP: ' + str(mAP))
    plt.legend()

    plt.show()
def draw(data):
    """
    Method to draw single patient with bounding box(es) if present 

    """
    # --- Open DICOM file
    d = pydicom.read_file(data['dicom'])
    im = d.pixel_array

    # --- Convert from single-channel grayscale to 3-channel RGB
    im = np.stack([im] * 3, axis=2)

    # --- Add boxes with random color if present
    for box in data['boxes']:
        #rgb = np.floor(np.random.rand(3) * 256).astype('int')
        rgb = [255, 251, 204] # Just use yellow
        im = overlay_box(im=im, box=box, rgb=rgb, stroke=15)

    plt.imshow(im, cmap=plt.cm.gist_gray)
    plt.axis('off')
예제 #30
0
def show_image(image, grayscale=True, ax=None, title=''):
    if ax is None:
        plt.figure()
    plt.axis('off')

    if len(image.shape) == 2 or grayscale == True:
        if len(image.shape) == 3:
            image = np.sum(np.abs(image), axis=2)

        vmax = np.percentile(image, 99)
        vmin = np.min(image)

        plt.imshow(image, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)
        plt.title(title)
    else:
        image = image + 127.5
        image = image.astype('uint8')

        plt.imshow(image)
        plt.title(title)
예제 #31
0
def getHistogram2PGN(df):
    y = df.iloc[:, -1]
    c = Counter(y)
    numDiffClasses = len(y.unique())
    target_names = y.unique()
    colors = colors = ['lightcoral', 'gold', 'yellowgreen',
                       'cyan'][:numDiffClasses]
    plt.rcParams["figure.figsize"] = [10, 5]
    plt.pie([c[i] / len(y) * 100.0 for i in c],
            labels=target_names,
            colors=colors,
            autopct='%1.1f%%',
            shadow=True,
            startangle=90)
    plt.axis('equal')
    plt.title(df.columns.values[-1])
    path = WORKING_PATH + "/___circle_labels.png"
    plt.savefig(path)
    plt.clf()
    return path
예제 #32
0
    def plot_spectrum(self):
        """
        Plots the spectrum of the most optimum structure
            
        """

        n_material_final = self.n_material_best
        d_final = self.d_best

        print('The optimum structure found was: ')
        self.print_struct(n_material_final, d_final)

        n_final_fine = self.disp_data.ref_ind_fine[:, n_material_final]

        # Display the best structure (including the fixed materials above the substrate)
        #        structure_best = convert2struct(material_key, n_material_final, d_final)

        # Compute the optimized structure's spectrum
        self.optim_R_spectrum_fine = refl_disp(self.n_in_fine, self.n_sub_fine,
                                               n_final_fine, d_final,
                                               self.disp_data.wvlen_vec_fine,
                                               self.theta_in)

        # Plot the optimized spectrum
        fig_spect = plt.figure()
        ax_spect = fig_spect.add_subplot(111)
        plt.plot(self.disp_data.wvlen_vec_fine,
                 self.optim_R_spectrum_fine,
                 'b',
                 label='Optimized spectrum')
        plt.plot(self.disp_data.wvlen_vec, self.r_target, 'g.', label='Target')

        plt.axis([
            min(self.disp_data.wvlen_vec_fine),
            max(self.disp_data.wvlen_vec_fine), -0.01, 1.01
        ])
        plt.xlabel('wavelength ($\mu$m)')
        plt.ylabel('reflectivity')
        plt.legend()

        plt.show()
예제 #33
0
def Harris(img):
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    blur = cv.GaussianBlur(gray, (5, 5), 7)
    Ix = cv.Sobel(blur, cv.CV_64F, 1, 0, ksize=5)
    Iy = cv.Sobel(blur, cv.CV_64F, 0, 1, ksize=5)

    IxIy = np.multiply(Ix, Iy)
    Ix2 = np.multiply(Ix, Ix)
    Iy2 = np.multiply(Iy, Iy)

    Ix2_blur = cv.GaussianBlur(Ix2, (7, 7), 10)
    Iy2_blur = cv.GaussianBlur(Iy2, (7, 7), 10)
    IxIy_blur = cv.GaussianBlur(IxIy, (7, 7), 10)

    det = np.multiply(Ix2_blur, Iy2_blur) - np.multyply(IxIy_blur, IxIy_blur)
    trace = Ix2_blur + Iy2_blur

    R = det - 0.05 * np.multiply(trace, trace)

    plt.subplot(1, 2, 1), plt.imshow(img), plt.axis('off')
    plt.subplot(1, 2, 2), plt.imshow(R, cmap='gray'), plt.axis('off')
예제 #34
0
def checkOverlap(flag, n, a1, b1, a2, b2):
    ## Generate the sets of points and find their hulls
    if flag:
        setA = generateUniform(n, a1, b1)
        setB = generateUniform(n, a2, b2)
    else:
        setA = generateNormal(n, a1, b1)
        setB = generateNormal(n, a2, b2)
    hullA = jarvisMarch(setA)
    hullB = jarvisMarch(setB)

    ## Do all the plotting
    setAx, setAy = extractCoords(setA)
    setBx, setBy = extractCoords(setB)
    hullAx, hullAy = extractCoords(hullA)
    hullBx, hullBy = extractCoords(hullB)
    plt.plot(setAx, setAy, 'b.')
    plt.plot(setBx, setBy, 'c.')
    plt.plot(hullAx, hullAy, 'ro')
    plt.plot(hullBx, hullBy, 'mo')

    ## Approximate the centers of the hulls
    centerA = (avg(hullAx), avg(hullAy))
    centerB = (avg(hullBx), avg(hullBy))
    ## Find the maximum radii of the hulls and add the bounding
    ## circles to the plot
    rA = radius(centerA, hullA)
    rB = radius(centerB, hullB)
    circleA = plt.Circle(centerA, rA, color='r', fill=False)
    circleB = plt.Circle(centerB, rB, color='m', fill=False)
    ax = plt.gca()
    ax.add_patch(circleA)
    ax.add_patch(circleB)
    plt.axis('scaled')
    plt.show()
    ## If the distance between the centers is less than the sum
    ## of the radii the circles overlap
    if rA + rB >= dist(centerA, centerB):
        return 1
    return 0
예제 #35
0
#The fit ellipse equations
#b_f is the minor axis of the fit ellipse
b_f=a*(np.cos(out_x[0][0]))

#equation of fit ellipse only considering inclination
x2=a*(np.cos(t/T))
y2=b_f*(np.sin(t/T))

#equation of the fit ellipse with error values and considering longitude of 
#ascending node
x_f=(x2*np.cos(out_y[0][1]))-(y2*np.sin(out_y[0][1]))
y_f=(x2*np.sin(out_y[0][1]))-(y2*np.cos(out_y[0][1]))
print (out_x), (out_y)

#plotting the fit ellipse
plt.plot(x_f,y_f, color='b')


#plot customization   
plt.xlabel("Declination(deg)")
plt.ylabel("Right Ascention(deg)")
plt.title("Position of the pulsar")
#chose these values ti show declination and right ascension
plt.axis([-90, 90, -180, 180])
plt.legend(('Actual ellipse','fit ellipse') , loc='upper right')
plt.locator_params(nbins=10)
#plt.text(i, w, fontsize=20, fontname='Times New Roman')
print "i=", (i), "w=", (w)
plt.show()
예제 #36
0
def train_dcgan_labeled(gen, dis, epoch0=0):
    print('CHAINER begin training');    sys.stdout.flush()

    o_gen = optimizers.Adam(alpha=0.0002, beta1=0.5)
    o_dis = optimizers.Adam(alpha=0.0002, beta1=0.5)
    print('CHAINER begin gen');    sys.stdout.flush()
    o_gen.setup(gen)
    o_dis.setup(dis)
    print('CHAINER begin add');    sys.stdout.flush()
    o_gen.add_hook(chainer.optimizer.WeightDecay(0.00001))
    o_dis.add_hook(chainer.optimizer.WeightDecay(0.00001))
    print('CHAINER begin zvis');    sys.stdout.flush()
    # zvis = (xp.random.uniform(-1, 1, (100, nz), dtype=np.float32))
    print('CHAINER begin for');    sys.stdout.flush()
    for epoch in range(epoch0,n_epoch):
        print("epoch:",epoch)
        sys.stdout.flush()
        perm = np.random.permutation(n_train)
        sum_l_dis = np.float32(0)
        sum_l_gen = np.float32(0)
        
        for i in range(0, n_train, batchsize):
            # discriminator
            # 0: from dataset
            # 1: from noise

            #print "load image start ", i
            x2 = np.zeros((batchsize, 3, 96, 96), dtype=np.float32)
            for j in range(batchsize):
                #try:
                    rnd = np.random.randint(len(dataset))
                    rnd2 = np.random.randint(2)

                    img = np.asarray(Image.open(io.BytesIO(dataset[rnd])).convert('RGB')).astype(np.float32).transpose(2, 0, 1)
                    x2[j,:,:,:] = (img[:,0:96,0:96]-128.0)/128.0
                #except:
                #    print('read image error occured', fs[rnd])
            #print "load image done"
            
            # train generator
            z = Variable(xp.random.uniform(-1, 1, (batchsize, nz), dtype=np.float32))
            x = gen(z)
            yl = dis(x)
            L_gen = F.softmax_cross_entropy(yl, Variable(xp.zeros(batchsize, dtype=np.int32)))
            L_dis = F.softmax_cross_entropy(yl, Variable(xp.ones(batchsize, dtype=np.int32)))
            
            # train discriminator
                    
            x2 = Variable(cuda.to_gpu(x2))
            yl2 = dis(x2)
            L_dis += F.softmax_cross_entropy(yl2, Variable(xp.zeros(batchsize, dtype=np.int32)))
            
            #print "forward done"

            o_gen.zero_grads()
            L_gen.backward()
            o_gen.update()
            
            o_dis.zero_grads()
            L_dis.backward()
            o_dis.update()
            
            sum_l_gen += L_gen.data.get()
            sum_l_dis += L_dis.data.get()
            
            #print "backward done"

            if i%image_save_interval==0:
                pylab.rcParams['figure.figsize'] = (16.0,16.0)
                pylab.clf()
                vissize = 100
                z = zvis
                z[50:,:] = (xp.random.uniform(-1, 1, (50, nz), dtype=np.float32))
                z = Variable(z)
                x = gen(z, test=True)
                x = x.data.get()
                for i_ in range(100):
                    tmp = ((np.vectorize(clip_img)(x[i_,:,:,:])+1)/2).transpose(1,2,0)
                    pylab.subplot(10,10,i_+1)
                    pylab.imshow(tmp)
                    pylab.axis('off')
                pylab.savefig('%s/vis_%d_%d.png'%(out_image_dir, epoch,i))
                
        serializers.save_hdf5("%s/dcgan_model_dis_%d.h5"%(out_model_dir, epoch),dis)
        serializers.save_hdf5("%s/dcgan_model_gen_%d.h5"%(out_model_dir, epoch),gen)
        serializers.save_hdf5("%s/dcgan_state_dis_%d.h5"%(out_model_dir, epoch),o_dis)
        serializers.save_hdf5("%s/dcgan_state_gen_%d.h5"%(out_model_dir, epoch),o_gen)
        print('epoch end', epoch, sum_l_gen/n_train, sum_l_dis/n_train)
예제 #37
0
M=train.as_matrix()
plt.imshow(im)
plt.show()
plt.imshow(im,cmap="gray")


from scipy.stats import norm
norm.pdf(0)
norm.pdf(0,loc=5, scale=10)
r=np.random.randn(10)
norm.pdf(r)
norm.cdf(r)
r=10*np.random.randn(10000)+5
plt.hist(r,bins=100)

r=np.random.randn(10000,2)
plt.scatter(r[:,0],r[:,1])
r[:,1]=5*r[:,1]+2
plt.scatter(r[:,0],r[:,1])

cov = np.array([[1,.8],[.8,3]])
from scipy.stats import multivariate_normal as mvn
mu=np.array([0,2])
r = mvn.rvs(mean=mu,cov=cov, size=1000)
plt.scatter(r[:,0],r[:,1])
plt.axis('equal')
plt.show()



import matplotlib as plt
import matplotlib.pyplot as plt


inputfile = open('Female_x_y.txt','r')

inputword = inputfile.read()
inputfile.close()
ys = inputword.split("\n")

keyword = set()

x = 1

for y in ys:
	try:
		int(y)
	except ValueError:
		continue 
	plt.plot(x,int(y),'ro')
	x += 7


plt.axis([0,1000,0,500])

plt.show()
for i, assembly in enumerate(assembly_list):
    kinf_list = []
    filename = assembly + '-trackspacing-errors.h5'
    if os.path.isfile('results/' + filename):
        f = h5py.File('results/' + filename, 'r')
    else:
        f = h5py.File('results/' + assembly + '-errors.h5', 'r')
    for j, x in enumerate(x_axis):
        value_keys = f[test][sorted_keys[j]].keys()
        for key in value_keys:
            if 'Kinf_Error' in key:
                kinf_list.append(f[test][sorted_keys[j]][key][...]*10**5)
    plt.plot(x_axis,kinf_list, colors[i] + 'o-', ms = 10, lw = 2)
    f.close()

plt.axis([max(x_axis), 0, 0, 400])
plt.title('Error in K-Infinity')
plt.xlabel('Track Spacing [cm]')
plt.ylabel('K-Infinity Error [pcm]')
plt.grid()
plt.legend(legend)
plt.show()
fig.savefig('K-Infinity-Error-TS.png')

fig = plt.figure()
for i, assembly in enumerate(assembly_list):
    mean_list = []
    filename = assembly + '-trackspacing-errors.h5'
    if os.path.isfile('results/' + filename):
        f = h5py.File('results/' + filename, 'r')
    else:
예제 #40
0
for i, assembly in enumerate(assembly_list):
    kinf_list = []
    filename = assembly + '-numazim-errors.h5'
    if os.path.isfile('results/' + filename):
        f = h5py.File('results/' + filename, 'r')
    else:
        f = h5py.File('results/' + assembly + '-errors.h5', 'r')
    for j, x in enumerate(x_axis):
        value_keys = f[test][sorted_keys[j]].keys()
        for key in value_keys:
            if 'Kinf_Error' in key:
                kinf_list.append(f[test][sorted_keys[j]][key][...]*10**5)
    plt.plot(x_axis,kinf_list, colors[i] + 'o-', ms = 10, lw = 2)
    f.close()

plt.axis([0, 130, 0, 500])
plt.title('Error in K-Infinity')
plt.xlabel('Number of Azimuthal Angles')
plt.ylabel('K-Infinity Error [pcm]')
plt.grid()
plt.legend(legend)
plt.show()
fig.savefig('K-Infinity-Error-Azim.png')


################################################################################

'''fig = plt.figure()
for i, assembly in enumerate(assembly_list):
    mean_list = []
    filename = assembly + '-numazim-errors.h5'
예제 #41
0
for i, assembly in enumerate(assembly_list):
    kinf_list = []
    filename = assembly + "-numazim-errors.h5"
    if os.path.isfile("results/" + filename):
        f = h5py.File("results/" + filename, "r")
    else:
        f = h5py.File("results/" + assembly + "-errors.h5", "r")
    for j, x in enumerate(x_axis):
        value_keys = f[test][sorted_keys[j]].keys()
        for key in value_keys:
            if "Kinf_Error" in key:
                kinf_list.append(f[test][sorted_keys[j]][key][...] * 10 ** 5)
    plt.plot(x_axis, kinf_list, colors[i] + "o-", ms=10, lw=2)
    f.close()

plt.axis([0, 130, 0, 500])
plt.title("Error in K-Infinity")
plt.xlabel("Number of Azimuthal Angles")
plt.ylabel("K-Infinity Error [pcm]")
plt.grid()
plt.legend(legend)
plt.show()
fig.savefig("K-Infinity-Error-Azim.png")

fig = plt.figure()
for i, assembly in enumerate(assembly_list):
    mean_list = []
    filename = assembly + "-numazim-errors.h5"
    if os.path.isfile("results/" + filename):
        f = h5py.File("results/" + filename, "r")
    else:
예제 #42
0
    f.close()

for array in fsr_kinf_error:
    nparray = numpy.array(array)
    fig = plt.figure()
    plt.pcolor(
        numpy.linspace(0, 5, 5),
        numpy.linspace(0, 5, 5),
        nparray,
        edgecolors="k",
        linewidths=1,
        vmin=nparray[:, :].min(),
        vmax=nparray[:, :].max(),
    )
    plt.colorbar()
    plt.axis([0, 5, 0, 5])
    plt.title("FSR K-infinity Errors")
    plt.gca().axes.get_xaxis().set_ticks([])
    plt.gca().axes.get_yaxis().set_ticks([])
    plt.show()
    fig.savefig(assembly_list[fsr_kinf_error.index(array)] + "-fsr-kinf-errors.jpeg")

for array in fsr_mean_error:
    nparray = numpy.array(array)
    fig = plt.figure()
    plt.pcolor(
        numpy.linspace(0, 5, 5),
        numpy.linspace(0, 5, 5),
        nparray,
        edgecolors="k",
        linewidths=1,