python 使用记录
0.安装python后菜单栏不显示, 快速pip install
修改 C:\Anaconda2\Lib\site-packages\menuinst\knownfolders.py
import ctypes, sys from ctypes import windll, wintypes from uuid import UUID reload(sys) sys.setdefaultencoding('utf-8')
然后
cd C:\Anaconda2\Lib
..\python _nsis.py mkmenus
搞定!
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyspider xxx
1. python 加载 caffe mean.binaryproto
#### mean_file #### proto_data = open(mean_filename, "rb").read() a = caffe.io.caffe_pb2.BlobProto.FromString(proto_data) mean = caffe.io.blobproto_to_array(a)[0]
2. python 加载caffe 图片输入
若是caffe.io.load_image()读进来是RGB格式和0~1(float)
所以在进行特征提取之前要在transformer中设置transformer.set_raw_scale('data',255)(缩放至0~255)
以及transformer.set_channel_swap('data',(2,1,0)(将RGB变换到BGR)
#### load input and configure preprocessing type 1 #### im = caffe.io.load_image("tmp.jpg") # 读进来是RGB格式和0~1 transformer = caffe.io.Transformer({'data': net_full_conv.blobs['data'].data.shape}) #transformer.set_mean('data', np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1)) transformer.set_transpose('data', (2, 0, 1)) # channel width(cols) height(cows) transformer.set_channel_swap('data', (2, 1, 0)) # 将RGB变换到BGR transformer.set_raw_scale('data', 255.0) # 缩放至0~255
如果用cv2.imread()接口读图像,读进来直接是BGR 格式and 0~255
所以不需要再缩放到【0,255】和通道变换【2,1,0】,不需要 transformer.set_raw_scale('data',255) 和 transformer.set_channel_swap('data',(2,1,0)
#### load input and configure preprocessing type 2 #### cv_im = cv2.imread("tmp.jpg") transformer.set_transpose('data', (2, 0, 1)) # channel
3. python opencv
# pip install opencv-python
####python opencv#### img.shape[0] = img.rows = 高 img.shape[1] = img.cols = 宽 Python: dst = cv2.resize(src, NewShape[1], NewShape[0], interpolation = cv2.INTER_LINEAR) C++: resize(midImage, tmpImage, cv::Size(ratio*midImage.cols, ratio*midImage.rows), (0, 0), (0, 0), cv::INTER_AREA);
4. python Matplotlib
####python Matplotlib#### import matplotlib.pyplot as plt # plt 用于显示图片 import matplotlib.image as mpimg # mpimg 用于读取图片 import numpy as np lena = mpimg.imread('lena.png') # 读取和代码处于同一目录下的 lena.png # 此时 lena 就已经是一个 np.array 了,可以对它进行任意处理 lena.shape #(512, 512, 3) plt.imshow(lena) # 显示图片 plt.axis('off') # 不显示坐标轴 plt.show() fig = plt.figure() # 新图 0 plt.savefig() # 保存 plt.close('all') # 关闭图 0
5. 颜色

""" Visualization of named colors. Simple plot example with the named colors and its visual representation. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as np import matplotlib.pyplot as plt from matplotlib import colors colors_ = list(six.iteritems(colors.cnames)) # Add the single letter colors. for name, rgb in six.iteritems(colors.ColorConverter.colors): hex_ = colors.rgb2hex(rgb) colors_.append((name, hex_)) # Transform to hex color values. hex_ = [color[1] for color in colors_] # Get the rgb equivalent. rgb = [colors.hex2color(color) for color in hex_] # Get the hsv equivalent. hsv = [colors.rgb_to_hsv(color) for color in rgb] # Split the hsv values to sort. hue = [color[0] for color in hsv] sat = [color[1] for color in hsv] val = [color[2] for color in hsv] # Sort by hue, saturation and value. ind = np.lexsort((val, sat, hue)) sorted_colors = [colors_[i] for i in ind] n = len(sorted_colors) ncols = 4 nrows = int(np.ceil(1. * n / ncols)) fig, ax = plt.subplots(1, figsize=(16,16)) X, Y = fig.get_dpi() * fig.get_size_inches() # row height h = Y / (nrows + 1) # col width w = X / ncols for i, (name, color) in enumerate(sorted_colors): col = int(i / nrows) row = i % nrows y = Y - (row * h) - h xi_line = w * (col + 0.05) xf_line = w * (col + 0.3) xi_text = w * (col + 0.35) ax.text(xi_text, y, name, fontsize=(h * 0.7), horizontalalignment='left', verticalalignment='center') # Add extra black line a little bit thicker to make # clear colors more visible. # ax.hlines(y, xi_line, xf_line, color='black', linewidth=(h * 0.7)) ax.hlines(y + h * 0.1, xi_line, xf_line, color=color, linewidth=(h * 0.7)) ax.set_xlim(0, X) ax.set_ylim(0, Y) ax.set_axis_off() fig.subplots_adjust(left=0, right=1, top=1, bottom=0, hspace=0, wspace=0) plt.show()
6.初始化list
all_change_group = [[0 for x in range(len(change_scope))] for y in range(len(thresholds))] # 初始化为0 all_change_group = [[] for y in range(len(thresholds))] # 初始化为空
7.画直方图和拟合曲线
def show_hist(data_mat): all_change_group = scipy.io.loadmat(data_mat) all_change_group = all_change_group['IOU_change_statistic'] color = ['k', 'b', 'g', 'r', 'm'] for i in range(0, len(all_change_group), 1): fig, ax = plt.subplots(1) plt.plot(change_scope, all_change_group[i], lw=2,color=color[i]) rects = plt.bar(left=change_scope, height=all_change_group[i], color='lightyellow', width=0.05, align="center", yerr=0.000001) #autolabel(rects, 1.0) # 为每个直方图加标注 plt.xlim((-1, 1)) ax.set_title('IOU_change: '+ '%.1f' % thresholds[i]) ax.set_ylabel('Num') ax.set_xlabel('IOU change') plt.grid() plt.show()
8.python绘制各种图
Python数据可视化:Matplotlib 直方图、箱线图、条形图、热图、折线图、散点图。。。
Python操作Excel新版本xlsx文件
9.字典
all_change_group = [] # 初始化 for i in range(0, len(thresholds), 1): all_change_group.append({'Neg': 0, 'Pos': 0})
10.中文显示
print line.decode("gb2312")
from matplotlib.font_manager import FontProperties import matplotlib.pyplot as plt import numpy as np font = FontProperties(fname=r"C:\\WINDOWS\\Fonts\\simsun.ttc", size=14)#C:\WINDOWS\Fonts t = np.linspace(0, 10, 1000) y = np.sin(t) plt.plot(t, y) plt.xlabel(u"时间", fontproperties=font) plt.ylabel(u"振幅", fontproperties=font) plt.title(u"正弦波", fontproperties=font) plt.show()
print image_file.decode("gbk")
11.转exe
pip install pyinstaller
pyinstaller -F ipynb2pdf.py
12.取目录和文件字符串
# 'COMPARE/softmax_MAX_NEGATIVE/softmax_MAX_NEGATIVE.log' log_dirname = os.path.dirname(logfile_path) # 'COMPARE/softmax_MAX_NEGATIVE'
PS: 路径最后
# 'COMPARE/softmax_MAX_NEGATIVE/softmax_MAX_NEGATIVE.log' log_basename = os.path.basename(logfile_path) # 'softmax_MAX_NEGATIVE.log'
(dirname, filename) = os.path.split(pathname) # 'COMPARE/softmax_MAX_NEGATIVE' 'softmax_MAX_NEGATIVE.log'
(shortname, extension) = os.path.splitext(filename) # 'softmax_MAX_NEGATIVE' '.log'
import os import os.path rootdir = "./database" for parent,dirnames,filenames in os.walk(rootdir): print "parent is" + parent for dirname in dirnames: print "dirname is" + dirname for filename in filenames: print "filename is" + filename
字符替换
xml_name = os.path.join(ROOTDIR,result_date[0].replace('jpg','xml').replace('JPEGImages','Annotations'))
13.array list
1. array to list
labels = thresholds.tolist() labels = [thresholds[i] for i in s_ids]
2. list to array
np.array('d',[1,2,3])
3.list 排序
no_match_boxes = match_box_list[index] no_match_boxes.sort(key=lambda x: x[1], reverse=True)
14.文件存在删除+追加写文件
if os.path.exists(result_file): os.remove(result_file) output = open(result_file, 'a') ... output.close()
15.复制和移动文件
import shutil if not os.path.exists(dst_img_dir): os.makedirs(dst_img_dir) shutil.move(img_name, dst_dir) shutil.copy(img_name, dst_dir)
16. 未知数量参数
def draw_curve(*curves): fig, axes = plt.subplots(nrows=1, figsize=(10, 8)) for curve_i, curve_name in enumerate(curves): 。。。
17. matplotlib.pyplot 标记出曲线上最大点和最小点的位置
import matplotlib.pyplot as plt import numpy as np def demo_test(): a=np.array([0.15,0.16,0.14,0.17,0.12,0.16,0.1,0.08,0.05,0.07,0.06]); max_indx=np.argmax(a)#max value index min_indx=np.argmin(a)#min value index plt.plot(a,'r-o') plt.plot(max_indx,a[max_indx],'ks') show_max='['+str(max_indx)+' '+str(a[max_indx])+']' plt.annotate(show_max,xytext=(max_indx,a[max_indx]),xy=(max_indx,a[max_indx])) plt.plot(min_indx,a[min_indx],'gs') plt.show() if __name__=="__main__": demo_test();
18.读写文件
1.读取某一行
import linecache theline = linecache.getline(feature_name, feature_num)
2.读取文件
# the good way with open('pimpin-aint-easy.txt') as f: for line in f: print (line)
3.写文件
output_feature = open(save_feature_name, "w") output_feature.write(theline) output_feature.close()
4.追加写
output = open(result_file, 'a') ... output.close()
18.python3 opencv中文
image = cv2.imdecode(np.fromfile('E:/View/卡口图片1白天车尾_1_329/100722114913-205.jpg',dtype=np.uint8), cv2.IMREAD_UNCHANGED) #image = cv2.imread(u'E:/View/卡口图片1白天车尾_1_329/100722114913-205.jpg'.encode('gbk')) cv2.imencode('.jpg', frame)[1].tofile('我/9.jpg') //正确方法
19.matplotlib中ion()和ioff()的使用
在Python Consol命令行中,默认是交互模式。而在python脚本中,matplotlib默认是阻塞模式。
其中的区别是:
在交互模式下ion():
- plt.plot(x)或plt.imshow(x)是直接出图像,不需要plt.show()
- 如果在脚本中使用ion()命令开启了交互模式,没有使用ioff()关闭的话,则图像会一闪而过,并不会常留。要想防止这种情况,需要在plt.show()之前加上ioff()命令。
在阻塞模式下ioff():
- 打开一个窗口以后必须关掉才能打开下一个新的窗口。这种情况下,默认是不能像Matlab一样同时开很多窗口进行对比的。
- plt.plot(x)或plt.imshow(x)是直接出图像,需要plt.show()后才能显示图像