python matplotlib绘图

记录这次绘图要的
1 主副坐标的设置
2 刻度字体的设置
3 网格的设置
转载:
https://blog.csdn.net/wuzlun/article/details/80053277
https://blog.csdn.net/wuzlun/article/details/80053277

最终实现结果
import numpy as np
import cv2

中文无法显示

from pylab import *
mpl.rcParams[‘font.sans-serif’]=[‘SimHei’]
mpl.rcParams[‘axes.unicode_minus’]=False
import os
import copy
import matplotlib.pyplot as plt

plt.style.use(‘ggplot’)

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

#保存所有误差
X_error=[]
Y_error=[]
class acc():
def init(self,img):
self.src_img = img
def circle_detect(self):
# BGR图片
# 将BGR图灰度化
# gray=cv2.cvtColor(self.src_img,cv2.COLOR_BGR2GRAY)
# gray = cv2.equalizeHist(gray)
canny=cv2.Canny(self.src_img,50,80)#左边是minval,右边是maxval,低于minval舍弃,图像灰度梯度 高于maxVal被认为是真正的边界,低于minVal的舍弃。
# 两者之间的值要判断是否与真正的边界相连,相连就保留,不相连舍弃
#显示canny算子分割结果
cv2.namedWindow(‘canny’,cv2.WINDOW_NORMAL)
cv2.imshow(‘canny’,canny)
cv2.waitKey()
#输出图片的尺寸
print(‘circle_pic_shape’,self.src_img. shape)
cv2.namedWindow(‘ori_hufu_circle:高度-宽度’,cv2.WINDOW_NORMAL)
while (cv2.waitKey(1) & 0xFF) != ord(‘q’):
img_t=copy.deepcopy(self.src_img)
minDist=cv2.getTrackbarPos(‘minDist’,‘track’)
param1=cv2.getTrackbarPos(‘param1’,‘track’)
param2=cv2.getTrackbarPos(‘param2’,‘track’)
minR=cv2.getTrackbarPos(‘minR’,‘track’)
maxR=cv2.getTrackbarPos(‘maxR’,‘track’)
#霍夫检测圆
gray=self.src_img
self.circles = cv2.HoughCircles(gray, method=cv2.HOUGH_GRADIENT, dp=1, minDist=minDist, param1=param1, param2=param2, minRadius=minR, maxRadius=maxR)
print(‘geshu’,len(self.circles[0]))
for circle in self.circles[0]:
# 坐标行列
x = int(circle[0])#宽度 1轴
y = int(circle[1])#高度 0轴
# 半径
r = int(circle[2])
# 在原图用指定颜色标记出圆的位置
img_t = cv2.circle(img_t, (x, y), r, (0, 0, 255), -1)
cv2.imshow(‘ori_hufu_circle:高度-宽度’, img_t)
cv2.destroyAllWindows()
print(‘type’,type(self.circles),‘shape’,self.circles.shape,self.circles)
# assert len(self.circles[0]) == 36,‘检测到的圆个数不对,请调整霍夫检测参数’
def sort_circle(self):
‘’’
圆心排序
:return:
‘’’
temp = self.circles[0].tolist()
print(‘type of temp’,type(temp),temp)
# print(‘type of circles’,type(self.circles))
temp.sort()#归为各个列
k=0
step=0
if len(self.circles[0])==36:
k=36
step=6
elif len(self.circles[0])==64:
k=64
step=8
elif len(self.circles[0])==90:
k=90
step=9
else:
assert False,‘圆个数不对’
for i in range(0,k,step):#竖着排,列排序
temp[i:i+step]=sorted(temp[i:i+step],key=lambda x:x[1])
print(‘sorted temp:’,temp)
#写入文件中
file=open(r’F:\yuanchengshoushudaohang\camera’
r’\navigationWithZ\camera_develop\01\res_data’
r’\center_data.txt’,‘a’)
for data in temp:
file.write(’{} {},’.format(data[0],data[1]))
file.write(’\n’)
file.flush()
file.write(’\n’)
file.close()
return temp

class read_file():
def init(self,path):
self.path=path
self.res=0
def read_f(self):
names=os.listdir(self.path)
num=len(names)
print(‘文件数:’,len(names),names)
k=-1
for name in names:
img=cv2.imread(self.path+’/’+name)
img=img[:,:,1]
if len(names)==25:
r, img = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)
elif len(names)5:
r, img = cv2.threshold(img, 20, 255, cv2.THRESH_BINARY)
else:
assert False,‘文件夹个数有问题’
# img = cv2.addWeighted(img, 1.5,-50,-0.5,10)
k+=1
color=20
space=20
if k%5
0:
color=int(input(‘please input’))
space=int(input(‘please input’))
#滤波
img = cv2.bilateralFilter(img, d=0, sigmaColor=color, sigmaSpace=space)
img = cv2.GaussianBlur(img, (9, 9), 0)
# img = cv2.medianBlur(img, 3)
# trackbar
cv2.namedWindow(‘track’)
def nothing(x):
pass
cv2.createTrackbar(‘minDist’, ‘track’, 41, 100, nothing)
cv2.createTrackbar(‘param1’, ‘track’, 64, 300, nothing)
cv2.createTrackbar(‘param2’, ‘track’, 12, 100, nothing)
cv2.createTrackbar(‘minR’, ‘track’, 0, 100, nothing)
cv2.createTrackbar(‘maxR’, ‘track’, 75, 500, nothing)
#计算
A = acc(img)
A.circle_detect()
self.res += np.array(A.sort_circle())
print(‘type of res:’,type(self.res),‘shape of res’,self.res.shape)
print(‘resullt’, self.res)
self.res /= num
temp=self.res.tolist()
file=open(r’F:\yuanchengshoushudaohang\camera’
r’\navigationWithZ\camera_develop\01\res_data’
r’\res_data.txt’,‘a’)
for data in temp:
file.write(’{} {},’.format(data[0],data[1]))
file.write(’\n’)
file.flush()
file.write(‘Done!’)
file.close()
im = cv2.imread(self.path+’\’+names[0])
for _ in self.res:
x,y=int([1]),int([0])
print(x,y)
im=cv2.circle(im,(y,x),6,(0,0,255),-1)
cv2.imshow(‘im’,im)
cv2.waitKey()
cv2.destroyAllWindows()
return self.res

class plot_all():
def init(self,path1,path2):
B = read_file(path1)
pro = B.read_f()
print(‘pro.shape:’, pro.shape, ‘pro.type’, type(pro), pro)
B = read_file(path2)
ori = B.read_f()
print(‘ori.shape’, ori.shape, ‘ori.type’, type(ori), ori)
self.pro=pro
self.ori=ori
self.res=(pro-ori)
print(‘error’,self.res)
def plot_01(self):
‘’’
图一,分布图
:return:
‘’’
#pro
x_pro=self.pro[:,np.newaxis,0].flatten().tolist()
y_pro=self.pro[:,np.newaxis,1].flatten().tolist()
#ori
x_ori=self.ori[:,np.newaxis,0].flatten().tolist()
y_ori=self.ori[:,np.newaxis,1].flatten().tolist()
x_err=None
y_err=None
#添加
if len(X_error)==0:
x_err=(self.res[:,np.newaxis,0]*0.21).flatten().tolist()
X_error.append(x_err)
y_err=(self.res[:,np.newaxis,1]*0.21).flatten().tolist()
Y_error.append(y_err)
elif len(X_error)==1:
x_err = (self.res[:, np.newaxis, 0] * 0.23).flatten().tolist()
X_error.append(x_err)
y_err = (self.res[:, np.newaxis, 1] * 0.23).flatten().tolist()
Y_error.append(y_err)
else:
x_err = (self.res[:, np.newaxis, 0] * 0.31).flatten().tolist()
X_error.append(x_err)
y_err = (self.res[:, np.newaxis, 1] * 0.31).flatten().tolist()
Y_error.append(y_err)
#存文件
file = open(r’F:\yuanchengshoushudaohang\camera’
r’\navigationWithZ\camera_develop\01\res_data’
r’\error_x_data.txt’, ‘w’)
for x,y in zip(x_err,y_err):
file.write(’{} {},’.format(x,y))
file.write(’\n’)
file.flush()
file.write(‘done!’)
file.close()

    figsize = 11, 9
    figure, ax = plt.subplots(figsize=figsize)
    #网格
    ax.grid(True,linestyle='-.')

    # 设置坐标刻度值的大小以及刻度值的字体
    # 坐标轴范围
    ax.set_xlim(0,510)
    ax.set_ylim(0,450)
    #坐标轴刻度
    plt.tick_params(labelsize=22)
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]

    #主副刻度
    # 修改主刻度
    xmajorLocator = MultipleLocator(50)  # 将x主刻度标签设置为20的倍数
    xmajorFormatter = FormatStrFormatter('%d')  # 设置x轴标签文本的格式
    ymajorLocator = MultipleLocator(50)  # 将y轴主刻度标签设置为0.5的倍数
    ymajorFormatter = FormatStrFormatter('%d')  # 设置y轴标签文本的格式
    # 设置主刻度标签的位置,标签文本的格式
    ax.xaxis.set_major_locator(xmajorLocator)
    ax.xaxis.set_major_formatter(xmajorFormatter)
    ax.yaxis.set_major_locator(ymajorLocator)
    ax.yaxis.set_major_formatter(ymajorFormatter)

    # 修改次刻度
    xminorLocator = MultipleLocator(10)  # 将x轴次刻度标签设置为5的倍数
    yminorLocator = MultipleLocator(10)  # 将此y轴次刻度标签设置为0.1的倍数
    # 设置次刻度标签的位置,没有标签文本格式
    ax.xaxis.set_minor_locator(xminorLocator)
    ax.yaxis.set_minor_locator(yminorLocator)

    # 打开网格
    ax.xaxis.grid(True, which='major')  # x坐标轴的网格使用主刻度
    ax.yaxis.grid(True, which='minor')  # y坐标轴的网格使用次刻度

    # 绘图
    plt.plot(x_pro, y_pro, '+', markersize=20,label='Projected Center')
    plt.plot(x_ori, y_ori, 'x', markersize=20,label='Actual   Center')

    #x/y-label
    #设置字体格式-label
    font1 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 22,
             }
    plt.legend(loc=1,prop=font1)
    plt.xlabel('X (pixels)',font1)
    plt.ylabel('Y (pixels)',font1)
    plt.show()
def plot_02(self):
    '''
    图二,误差图
    :return:
    '''
    # 移动坐标轴
    plt.figure()
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    # ax.spines['bottom'].set_color('none')
    # ax.spines['left'].set_color('none')  # 将右边和上边的两条边颜色设置为空 其实就相当于抹掉这两条边
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')  # 指定下边的边作为 x 轴   指定左边的边为 y 轴
    ax.spines['bottom'].set_position(('data', 0))
    ax.spines['left'].set_position(('data', 0))  # 指定 data  设置的bottom(也就是指定的x轴)绑定到y轴的0这个点上

    # 网格
    # ax.grid(True, linestyle='-.')

    # 设置坐标刻度值的大小以及刻度值的字体
    # 坐标轴范围
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    # 坐标轴刻度
    plt.tick_params(labelsize=22)
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]

    # 主副刻度
    # 修改主刻度
    xmajorLocator = MultipleLocator(1)  # 将x主刻度标签设置为20的倍数
    xmajorFormatter = FormatStrFormatter('%d')  # 设置x轴标签文本的格式
    ymajorLocator = MultipleLocator(1)  # 将y轴主刻度标签设置为0.5的倍数
    ymajorFormatter = FormatStrFormatter('%d')  # 设置y轴标签文本的格式
    # 设置主刻度标签的位置,标签文本的格式
    ax.xaxis.set_major_locator(xmajorLocator)
    ax.xaxis.set_major_formatter(xmajorFormatter)
    ax.yaxis.set_major_locator(ymajorLocator)
    ax.yaxis.set_major_formatter(ymajorFormatter)

    # 修改次刻度
    xminorLocator = MultipleLocator(0.1)  # 将x轴次刻度标签设置为5的倍数
    yminorLocator = MultipleLocator(0.1)  # 将此y轴次刻度标签设置为0.1的倍数
    # 设置次刻度标签的位置,没有标签文本格式
    ax.xaxis.set_minor_locator(xminorLocator)
    ax.yaxis.set_minor_locator(yminorLocator)

    # 打开网格
    # plt.grid(True)
    # ax.xaxis.grid(True, which='major')  # x坐标轴的网格使用主刻度
    # ax.yaxis.grid(True, which='major')  # y坐标轴的网格使用次刻度

    # 绘图
    plt.plot(X_error[0],Y_error[0],'o',markersize=10,label='Working distance 30 cm')
    plt.plot(X_error[1],Y_error[1],'o',markersize=10,label='Working distance 40 cm')
    plt.plot(X_error[2],Y_error[2],'o',markersize=10,label='Working distance 50 cm')
    # x/y-label
    # 设置字体格式-label
    font1 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 22,
             }
    font2 = {'family': 'Times New Roman',
             'weight': 'normal',
             'size': 22,
             }
    plt.legend(bbox_to_anchor=(0.5,-0.04),loc=9,prop=font1)
    # plt.xlabel('x',font1)
    # plt.ylabel('y',font2)
    plt.show()

def plot_03(self):
    '''
    误差拟合图
    :return:
    '''
    pass

#30
path1=r’F:\yuanchengshoushudaohang\camera\navigationWithZ\camera_develop\01\30’
path2=r’F:\yuanchengshoushudaohang\camera\navigationWithZ\camera_develop\01\30_’
A=plot_all(path1,path2)
A.plot_01()
#40
path1=r’F:\yuanchengshoushudaohang\camera\navigationWithZ\camera_develop\01\40’
path2=r’F:\yuanchengshoushudaohang\camera\navigationWithZ\camera_develop\01\40_’
A=plot_all(path1,path2)
A.plot_01()

#50

path1=r’F:\yuanchengshoushudaohang\camera\navigationWithZ\camera_develop\01\50’
path2=r’F:\yuanchengshoushudaohang\camera\navigationWithZ\camera_develop\01\50_’
A=plot_all(path1,path2)
A.plot_01()
#总误差图
A.plot_02()

A.plot_03()

你可能感兴趣的:(2018,python,opencv)