文章目录
命令行参数传递
vscode配置anaconda:
environments
配置后可以直接F5运行anaconda环境下的Python
Python小记
__file__
当前文件位置
os.makedirs
相当于mkdir -p
os.mkdir
只能make一层
os.listdir(path)
= ls
Python import的时候如果找不到路径
sys.path.append('./')
可以用stdout实现进度条打印,因为不会自动换行
sys.stdout.write sys.stdout.flush()
当然进度条用tqdm更好看
from tqdm import tqdm
import time
for i in tqdm(range(10000)):
time.sleep(0.01)
Python的colorbar蛮好用,如cmap=plt.cm.PRGn
,
各种颜色参考
Python opencv键盘监听:
Pandas
读取没有标题的txt:
import pandas as pd
Input = pd.read_csv("mean12.txt", header=None, names=('c', 'Rref2', 'mean1', 'mean2'), sep = " ")
header=None
说明没有标题,默认header=0
是取第0行也就是第一行为标题,names
可以自己定义列标题,sep
代表分隔符,默认是逗号,如果txt里面用空格应该要指明
Dataframe可以直接操作、新建:
Input['meanDiff'] = Input['mean1'] - Input['mean2']
Input.describe()
可以按列统计mean std各种信息
Input.mean()
输出每列的mean
Input.mean(1)
输出每行的mean
.head(N)
.tail(N)
看头尾N行
.index
.columns
看行标题列标题
to_numpy()
, 0.24新版本才有,旧版本是.values
, 还可以配合.tolist()
使用从numpy到list,Input['c'].values.tolist()
.sort_values('mean1')
根据列标题sort
.sort_index(axis=1, ascending=False)
根据axis排序,横向
all_sort = all.sort_values('rank', ascending=True).reset_index()
排序后行索引是乱的,因为是对应的原来的行索引,可以用reset_index
重新生成新的index
Input['c']
, Input[0:3]
分别是拿列数据、行数据slice
print(Input.iloc[2,2])
, 拿指定位置的数据
print(Input.loc[1:2, 'c'])
, 拿指定范围位置的数据
loc
:通过行标签索引数据
iloc
:通过行号索引行数据
ix
:通过行标签或行号索引数据(基于loc和iloc的混合)
input.ix['min', 'D']
, 行标签,列标签
Input[Input['c'] < 0.2]
, 筛选出符合bool条件的值,拿一列的时候才会取出,否则是下面那样置位,可以先reshape。
Input[Input > 0.2]
, 筛选后符合的是原值,否则nan
print(Input[Input['c'].isin([0.1, 0.2])])
, 有无的筛选
df2 = df.copy()
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three'] 直接加一列
print(Input.apply(lambda x: x.max() - x.min())), 整列的一个函数操作
Input.mean().plot()
Input.to_csv("withDiff.csv")
, 存csv文件
numpy转成DataFrame
frame = cv2.imread("00000201.exr", -1)
print(frame)
df = pd.DataFrame(data=frame)
skimage rescale、PIL和numpy关于图像
For example:
img2 = Image.open('examples.png')
img2_np = np.array(img2, dtype='uint8')
img3_np = np.array(img2, dtype='float64')
img2_np_rescale = skimage.transform.rescale(img2_np, 0.5, order=0)
img3_np_rescale = skimage.transform.rescale(img3_np, 0.5, order=0)
上述代码会产生很不一样的结果,narray如果是uint8的,rescale以后会成为0-1分布的float!!!!!!!!而如果本身就是float的,rescale以后不会到0-1分布!
numpy 可以用b = a.astype('uint8')
转换变量类型
skimage rescale以后的类型是float类型,如果要用PIL显示或转为numpy,需要转到uint8,如下所示:
from PIL import Image
Image.fromarray(img2_np_rescale.astype('uint8'))
skimage的数据结构是[C, H, W],如3, 512, 256是竖着的彩色图,而且基本上用float64
而PIL的数据结构是[H W C],包括调用Image.formarray(arr)
的时候要保证arr是HWC
PIL的resize:
img = Image.open("a.png")
img.resiez((W, H), Image.BICUBIC)
Tips:visdom.image
要求输入图像是CHW(内部做了transpose(1,2,0)然后PIL show)
mark:
skimage的scale中的order选项,补全中预处理选择0:
0: Nearest-neighbor
1: Bi-linear (default)
2: Bi-quadratic
3: Bi-cubic
4: Bi-quartic
5: Bi-quintic
resample – An optional resampling filter. This can be one of PIL.Image.NEAREST(use nearest neighbour), PIL.Image.BILINEAR (linear interpolation),PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.
通道总结:
opencv order:HWC,灰度图就是HW
PIL的Image.open本身size是WH,转成numpy后:HWC, 灰度图就是HW
skimage:HWC
Pytorch里面的tensor顺序是CHW,所以要
img_tensor = torch.from_numpy(img.transpose((2, 0, 1)).copy())
pip记录:
有的时候pip在安装卸载的时候被强行中断,或者手贱直接在local目录删除,会在使用pip指令的时候出现错误:
bash: /home/SENSETIME/chenshenzhou/.local/bin/pip: /home/SENSETIME/chenshenzhou/anaconda3/envs/tf/bin/python3: bad interpreter: No such file or directory
这个时候得用python -m pip
代替pip
。
python 程序拷贝移动文件
import shutil
shutil.copyfile(in_path, out_path)
python 获得文件夹下全部文件名
import glob
glob_pure = os.path.join(root, "intensity_pure/2018-08-01-16-28-52/*.png")
paths_pure = sorted(glob.glob(glob_pure))
当然也可以先ls *.png > image.txt
然后读文件
已经安装ros的环境下opencv-Python的坑:
import cv2
的时候报错
Traceback (most recent call last):
File "main.py", line 12, in <module>
from dataloaders.kitti_loader import load_calib, oheight, owidth, input_options, KittiDepth
File "/home/SENSETIME/chenshenzhou/project/self-supervised-depth-completion/dataloaders/kitti_loader.py", line 11, in <module>
import cv2
ImportError: /opt/ros/kinetic/lib/python2.7/dist-packages/cv2.so: undefined symbol: PyCObject_Type
这是ros安装后系统路径默认是ros的Python2.7目录下导入opencv,但是程序调用的是Python3,所以要把import cv2
改成:
import sys
ros_path = '/opt/ros/kinetic/lib/python2.7/dist-packages'
if ros_path in sys.path:
sys.path.remove(ros_path)
import cv2
sys.path.append(ros_path)