matplotlib使用

除了自己寫的,還可以參考:http://blog.csdn.net/u010668907/article/details/51114659,

3D繪圖參考:http://blog.csdn.net/Eddy_zheng/article/details/48713449

最近寫文章要做一些可視化圖,用到matplotlib庫, 留幾個案例備忘:

    def show_imgpair(self,imgs,pt_pairs):
        '''
        show two images and their point-pairs
        :param imgs: the abs-paths of images
        :param pt_pairs: [[pt_i1,pt_i2,...,pt_iN],[pt_j1,pt_j2,...,pt_jN]]
        :return: None
        '''
        fig = plt.figure()
        im0=cv2.imread(imgs[0],1)
        for ptt in pt_pairs[0]:
            pt=(math.floor(ptt[0]),math.floor(ptt[1]))
            im0=cv2.circle(im0,pt,3,(0,0,255),-1)
        fig.add_subplot('121')
        plt.imshow(im0)
        im1 = cv2.imread(imgs[1], 1)
        for ptt in pt_pairs[1]:
            pt = (math.floor(ptt[0]), math.floor(ptt[1]))
            im1 = cv2.circle(im1, pt, 3, (0, 0, 255), -1)
        fig.add_subplot('122')
        plt.imshow(im1)
        plt.show()#, 'gray'
        return

        import matplotlib.pyplot  as plt
        imgs = [Image.open(self.__pics_path+'/'+pic_path) for pic_path in results]#注意這裏不能顯示cv2.imread()創建的圖對象
        fig=plt.figure()
        for l in range(lines):
            for c in range(9):
                if c+l*9+1>topK:
                    break
                ax=fig.add_subplot(eval(str(l+1)+'9'+str(c+1)))
                ax.imshow(imgs[c+l*9])
        plt.show()#這句不能少,不然沒圖出來

繪圖用:

def draw(a,line_lbs,f_lbs=['x','y','title'],save_pic=None,ymin=0.0):
    colors = ['c','r','b','k','g','m','y']
    # lines = [':', '-.', '-', '--']
    a_s=np.array(a)
    if len(a_s.shape)==1:
        a_s=a_s[np.newaxis,:]
    elif len(np.array(a).shape)==2:
        pass
    else:
        raise Exception('Dims of input is not 1 or 2')
    x_r=0
    for i,a in enumerate(a_s):
        x_r=x_r if len(a)<x_r else len(a)
        a_x=[a_i+1 for a_i in range(len(a))]
        # pl.plot(a_x ,a,color=colors[i],linestyle=lines[i],label=line_lbs[i])
        pl.plot(a_x, a, color=colors[i], label=None if line_lbs is None else line_lbs[i])
    # pl.ylim(ymin, 1.0)
    # pl.xlim(1, x_r)
    pl.title(f_lbs[2])
    pl.xlabel(f_lbs[0])
    pl.ylabel(f_lbs[1])
    # pl.legend(loc='lower right')
    # pl.grid(True)
    if save_pic:
        pl.savefig(save_pic)
    pl.show()

使用cv2創建圖顯示:

import cv2
def multiShow(imgs,array=None,selected=None):
    '''
    :param imgs: 存放子圖的列表
    :param array: [row,column],顯示子圖的[行數,列數]
    :param selected: 對imgs中的圖作標記,使標記的圖加一個突出框
    :return: None
    '''
    targetSize=imgs[0].shape #以第一個圖大小爲標準子框
    print(targetSize)
    finalImg=np.zeros(shape=(targetSize[0]*array[0]+5*(array[0]+1),
                             targetSize[1]*array[1]+5*(array[1]+1),
                             3),
                      dtype='uint8')+255

    for index,img in enumerate(imgs):
        if img is None:
            continue
        # print('index:',index,'img:',img.shape)
        curSize=img.shape
        targetSize_adapt = [imgs[0].shape[0],imgs[0].shape[1]]
        ratio1=targetSize_adapt[1]/curSize[1]
        ratio0 = targetSize_adapt[0] / curSize[0]
        if ratio1>ratio0:
            targetSize_adapt[1]=math.floor(ratio0*curSize[1])
            offset1=math.floor((targetSize[1]-targetSize_adapt[1])/2)
            offset0=0
        elif ratio1<ratio0:
            targetSize_adapt[0] = math.floor(ratio1 * curSize[0])
            offset0 = math.floor((targetSize[0] - targetSize_adapt[0]) / 2)
            offset1=0
        else:
            offset0,offset1=[0,0]
        dest=cv2.resize(img, (targetSize_adapt[1],targetSize_adapt[0]))
        print('index:', index,'dest:',dest.shape)
        index_r=math.floor( index/array[1] )
        index_c = math.floor( index % array[1] )
        finalImg[(targetSize[0] + 5) * index_r + 5 + offset0:(targetSize[0] + 5) * index_r + 5 + offset0+targetSize_adapt[0],
                 (targetSize[1] + 5) * index_c + 5 + offset1:(targetSize[1] + 5) * index_c + 5 + offset1+targetSize_adapt[1], :] = dest
        # finalImg[(targetSize[0] + 5) * index_r + 5+offset0:(targetSize[0] + 5) * (index_r + 1),
        #          (targetSize[1] + 5) * index_c + 5+offset1:(targetSize[1] + 5) * (index_c + 1),:]=dest
    if selected is not None:
        for each in selected:
            rc_r = math.floor(each / array[1])
            rc_c = math.floor(each % array[1])
            p1=((targetSize[1] + 5) * rc_c + 10, (targetSize[0] + 5) * rc_r + 10)
            p2=(p1[0]+targetSize[1]-5,p1[1]+targetSize[0] -5)
            finalImg=cv2.rectangle(finalImg,p1,p2,(0,255,0),8)
    cv2.namedWindow('multi-imgs',cv2.WINDOW_NORMAL)
    cv2.imshow('multi-imgs',finalImg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
#======================================================================#
imgs = [cv2.imread(pic_path, cv2.IMREAD_COLOR) for pic_path in pics_path]
lines=math.ceil(len(imgs)/9)
multiShow(imgs, array=(lines, 9), selected=None)

發佈了54 篇原創文章 · 獲贊 25 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章