Talk is cheap, Show me the code

0%

Python常忘操作

Python经常忘记的操作:文件和文件夹操作 嵌套语句

1、文件操作

参考链接:Python 3 菜鸟教程

  • 文件/文件夹/路径操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 判断路径是否存在
for tmpdir in [mask_dir, viz_dir]:
if not os.path.exists(tmpdir):
os.mkdir(tmpdir) # os.mkdirs()可创建多级目录

# 提取路径中的文件名
(file, ext) = os.path.splitext(url) # 分割文件名和扩展名
(path, filename) = os.path.split(url) # 分割路径和文件名
# 绝对路径
os.path.abspath(__file__) # 包括软链接
os.path.realpath(__file__) # 去除软链接
# 复制文件
shutil.copy(LAST, BEST)

# 枚举所有路径
names = os.listdir(project_path)



  • 文本读写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
read()	# 将文本文件所有行读到一个字符串中。
readline() # 一行一行的读
readlines() # 将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素。

# 方法1
file1 = open("test.txt")
file2 = open("output.txt","w")
while True:
line = file1.readline()
file2.write('"'+line[:s]+'"'+",")
if not line:
break
file1.close()
file2.close()

# 方法2
file2 = open("output.txt","w")
for line in open("test.txt"):
file2.write('"'+line[:s]+'"'+",")
file2.close()

# 方法3
with open('somefile.txt', 'r') as f:
data = f.read()

# Iterate over the lines of the file
with open('somefile.txt', 'r') as f:
for line in f:
# ...

# Write chunks of text data
with open('somefile.txt', 'w') as f:
f.write(text1)

# Redirected print statement
with open('somefile.txt', 'w') as f:
print(line1, file=f)
print(line2, file=f)

2、Numpy / PyTorch

转换

  • 维度
1
2
np.shape  # (height, width, channels) OpenCV
torch.shape # (N, channel, height, width) 2D
  • 互相转换
1
2
3
4
5
tor_arr = torch.from_numpy(np_arr)
np_arr = tor_arr.numpy()

# cuda tensor转为numpy
np_arr = cuda_arr.cpu().detach().numpy()

Numpy

  • 随机数
1
2
3
4
5
6
7
8
9
10
np.random.random   # 生成指定形状的0- 1之间的随机数;
np.random.rand # 生成指定形状的0- 1之间的随机数;
np.random.randint # 生成指定数值范围内的随机整数;
np.random.randn # 生成服从均值为0,标准差为1的标准正态分布随机数;
np.random.normal # 生成指定均值和标准差的正态分布随机数;
np.random.uniform # 生成均匀分布随机数;
np.random.seed # 按照种子来生成随机数,种子一样,生成的随机数也一样;
np.random.shuffle # 打乱数组元素顺序;
np.random.choice # 按照指定概率从指定数组中,随机抽出某个数;
# 注意:由于是生成随机数,只要是没有设置随机种子,每次刷新结果后的值都是不一样的;
  • 运算
1
2
3
4
5
6
7
8
# 数乘
a*b
# 点乘
a.dot(b)
np.dot(a, b)
# 求逆
np.linalg.inv(a)
np.matrix().I
  • 数据格式转换
1
arr.astype(np.int32) 
  • 通道变换
1
2
3
4
5
6
7
8
9
10
11
12
```



## Torch

* GPU

```python
# 设置可用gpu的id
# 一定一定放在文件开头,在任何包调用cuda之前,设置该选项后,cuda_id重新计数
os.environ["CUDA_VISIBLE_DEVICES"] = '0,1,2,3'
  • 运算
1
2
# 转置
tesor.transpose()
  • 维度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
```



# 3、OpenCV

* 单应性估计和变换

```python
# 估计
cv2.getPerspectiveTransform(pts2, pts1)
cv2.findHomography()

# 变换
cv2.warpPerspective()
  • 图像绘制
1
2
# 画点或圆
cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]])
  • 基础编辑
1
2
3
4
5
# 裁剪图像

# 添加文字
cv2.putText(src, text, place, Font, Font_Size, Font_Color, Font_Overstriking)
img_1 = cv2.putText(img_1, 'image 1', (10,height-10), cv2.FONT_HERSHEY_COMPLEX, 1.0, (100, 200, 200), 1)
  • 形态学
1
2
3
4
5
6
7
8
# 腐蚀,膨胀
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3))
cv2.erode(mask, kernel)
cv2.dilate(mask, kernel)
# 开操作: 先腐蚀再膨胀
# 闭操作:先膨胀再腐蚀
# cv2.MORPH_CLOSE,cv2.MORPH_OPEN
cv2.morphologyEX(mask, cv2.MORPH_CLOSE, kernel)

4、基础操作

1
2
3
# ASSIC 转换
n = ord(s)
s = chr(n)
  • 相对路径问题
1
2
3
4
// vscode调试时指定工作目录为当前文件所在目录
"cwd": "${fileDirname}" // 添加到lunch.json中

// 执行时,勾选python扩展中的Execute in File Dir
-------------The End-------------