在处理数据,绘图,批量处理文件时,python能大大提高工作的效率,这篇文章就记录一下在各种场景下常用的一些功能实现。

批量复制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 导入os和shutil模块
import os
import shutil

# 定义源目录和目标目录的路径,注意要用绝对路径或相对路径
source_dir = "C:/Users/xxx/source" # 源目录,假设是C盘下的source文件夹
target_dir = "C:/Users/xxx/target" # 目标目录,假设是C盘下的target文件夹

# 遍历源目录下的所有子文件夹和文件
for root, dirs, files in os.walk(source_dir):
# 对于每一个文件,获取它的完整路径
for file in files:
file_path = os.path.join(root, file)
# 复制或移动文件到目标目录,注意要保留原来的文件名
# 如果要复制文件,用shutil.copy,如果要移动文件,用shutil.move
shutil.copy(file_path, target_dir) # 复制文件
# shutil.move(file_path, target_dir) # 移动文件

# 打印完成提示信息
print("All files have been copied or moved to the target directory.")

显示obj模型

1
2
3
4
5
6
7
8
9
10
11
# 导入open3d库
import open3d as o3d

# 从文件中读取obj格式的网格
mesh = o3d.io.read_triangle_mesh("D:/WORK/DTact/obj_gather/00000003_1ffb81a71e5b402e966b9341_trimesh_002.obj")

# 计算网格的顶点法线
mesh.compute_vertex_normals()

# 在一个OpenGL窗口中显示网格
o3d.visualization.draw_geometries([mesh])

数据可视化

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
# print(matplotlib.__version__)

h=0.04494988870551895

# 读取./6d_force/food文件夹下food.npy
data_list = np.load("./6d_force/food/food.npy")
# 创建6个空列表来存储x,y,z方向的力和力矩
force_x = []
force_y = []
force_z = []
torque_x = []
torque_y = []
torque_z = []
#给6个列表赋值
for data in data_list:
force_x.append(data[0])
force_y.append(data[1])
force_z.append(data[2])
torque_x.append(data[3])
torque_y.append(data[4])
torque_z.append(data[5])
# 绘制各个力和力矩的分布直方图
# plt.figure()
# plt.subplot(2,3,1)#画布分为2行3列6个子图,这是第1个子图
# plt.hist(force_x, bins=100)#直方图,bins表示直方图的柱数,也就是100个子区间
# plt.title("force_x")
# plt.subplot(2,3,2)
# plt.hist(force_y, bins=100)
# plt.title("force_y")
# plt.subplot(2,3,3)
# plt.hist(force_z, bins=100)
# plt.title("force_z")
# plt.subplot(2,3,4)
# plt.hist(torque_x, bins=100)
# plt.title("torque_x")
# plt.subplot(2,3,5)
# plt.hist(torque_y, bins=100)
# plt.title("torque_y")
# plt.subplot(2,3,6)
# plt.hist(torque_z, bins=100)
# plt.title("torque_z")
# plt.show()

# 绘制六边形图
# plt.hexbin(force_x, force_y, gridsize=20)
# plt.xlabel('force_x')
# plt.ylabel('force_y')
# plt.colorbar()
# plt.show()

# # 假设你的force_x和force_y是列表
# force_x = pd.Series (force_x)
# force_y = pd.Series (force_y)
# force_z = pd.Series (force_z)
# # 绘制单变量核密度图
# force_z.plot.kde (color='red')
# plt.show ()
# # 绘制双变量核密度图
# df = pd.DataFrame ({'force_x': force_x, 'force_y': force_y})
# df.plot.kde ()
# plt.show ()

# pd.Series (force_x).plot.kde (color='red')

# 散点图
#force_x 和 force_y
# plt.scatter (force_x, force_y, s=0.1, color='blue')
# plt.xlabel ('force_x')
# plt.ylabel ('force_y')

# torque_x 和 torque_y
# plt.scatter (torque_x, torque_y, s=0.1, color='blue')
# plt.xlabel ('torque_x')
# plt.ylabel ('torque_y')

# force_y and torque_x
# plt.scatter (force_y, torque_x, s=0.1, color='blue')
# plt.xlabel ('force_y')
# plt.ylabel ('torque_x')

# force_x and torque_y
# plt.scatter (force_x, torque_y, s=0.1, color='blue')
# plt.xlabel ('force_x')
# plt.ylabel ('torque_y')

# plt.show ()

# 绘制三维曲面图
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# ax.plot_surface(force_x, force_y, force_z)
# ax.set_xlabel('force_x')
# ax.set_ylabel('force_y')
# ax.set_zlabel('force_z')
# plt.show()

# 绘制三维散点图
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')

# # force_x and force_y and force_z
# ax.scatter3D(force_x, force_y, force_z, s=0.1,color='red')
# ax.set_xlabel('force_x')
# ax.set_ylabel('force_y')
# ax.set_zlabel('force_z')

# # torque_x and torque_y and torque_z
# # ax.scatter3D(torque_x, torque_y, torque_z,s=0.1,color='red')
# # ax.set_xlabel('torque_x')
# # ax.set_ylabel('torque_y')
# # ax.set_zlabel('torque_z')

# plt.show()

#位置分布
x = []
y = []

center_list = np.load("./image/food/food.npy")
for center in center_list:
x.append(center[0])
y.append(center[1])

# x[i] = torque_y[i]/force_z[i]
# y[i] = torque_x[i]/force_z[i]
#给x,y列表赋值
# Mx = -Fy*h + Fz*y
# My = Fx*h - Fz*x
# x = (Fx*h - My)/Fz
# y = (Mx + Fy*h)/Fz
# len = len(force_x)
# #for遍历列表
# for i in range(len):
# #每行打印一个列表中的六个值
# # print(force_x[i], force_y[i], force_z[i], torque_x[i], torque_y[i], torque_z[i])

# x.append((force_x[i]*h-torque_y[i])/force_z[i])
# y.append((torque_x[i]+force_y[i]*h)/force_z[i])

# sns.distplot(x, kde=True)
# # plt.xlim(-0.02, 0.02)
# plt.xlabel('x')
# plt.show()
# sns.distplot(y, kde=True)
# # plt.xlim(-0.02, 0.02)
# plt.xlabel('y')
# plt.show()

My_fx = []
Mx_fy = []
scale_x = 400
scale_y = 400
bias_x = 1
bias_y = 0.5
for i in range(len(x)):
x[i] = x[i]/scale_x-bias_x
y[i] = y[i]/scale_y-bias_y
Mx_fy.append(torque_x[i] - force_z[i]*y[i])
My_fx.append(torque_y[i] + force_z[i]*x[i])
sns.jointplot(x=Mx_fy, y=force_y, kind='kde')
plt.show()
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
g = sns.jointplot(x=force_x, y=force_y, kind='kde', color='purple')
g.plot_joint(sns.kdeplot,fill=True)
plt.show()


# 绘制分布直方图,范围为-0.02到0.02,分为100个子区间
# plt.hist(x, bins=100,range=(-0.02,0.02))
# plt.title("x")
# plt.show()
# plt.hist(y, bins=100)
# plt.title("y")
# plt.show()
# 绘制两者的散点图,范围-0.02到0.02
# plt.scatter (force_z, x, s=0.1, color='blue')
# plt.show()




## seaborn

# 绘制六个单变量核密度图
# sns.distplot(force_x, kde=True)
# plt.xlabel('force_x')
# plt.show()
# sns.distplot(force_y, kde=True)
# plt.xlabel('force_y')
# plt.show()
# sns.distplot(force_z, kde=True)
# plt.xlabel('force_z')
# plt.show()
# sns.distplot(torque_x, kde=True)
# plt.xlabel('torque_x')
# plt.show()
# sns.distplot(torque_y, kde=True)
# plt.xlabel('torque_y')
# plt.show()
# sns.distplot(torque_z, kde=True)
# plt.xlabel('torque_z')
# plt.show()

# 绘制六个双变量核密度图
# sns.jointplot(x=force_x, y=force_y, kind='kde')
# plt.show()
# sns.set(style="whitegrid")
# tips = sns.load_dataset("tips")
# g = sns.jointplot(x=force_x, y=force_y, kind='kde', color='purple')
# g.plot_joint(sns.kdeplot,fill=True)
# plt.show()

需要注意的一点是matplotlib的版本,建议更新到最新版。我一开始下载的旧版结果一直报错,后来才发现是库的bug

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt

img_list = []
tresh_list = []
center_list = []
# 读取./cliber/geometry所有子文件夹下所有图片并转换为灰度图像
for subfolder in os.listdir("./cliber/geometry"):
subfolder_path = os.path.join("./cliber/geometry", subfolder)
for file in os.listdir(subfolder_path):
file_path = os.path.join(subfolder_path, file)
img = cv2.imread(file_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化灰度图像,阈值可以根据实际情况调整
ret, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
# 寻找白色区域的轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
filted_contours = []
centroids = []
areas = []
#遍历轮廓列表
for contour in contours:
#剔除面积等于0的轮廓
area = cv2.contourArea(contour)
if area > 0:
filted_contours.append(contour)
M = cv2.moments(contour)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
centroids.append([cx, cy])
areas.append(area)
#如果areas列表为空,则说明没有找到白色区域,跳过此次循环
if len(areas) == 0:
continue

centroids = np.array(centroids)
areas = np.array(areas)
Cx = np.sum(centroids[:,0]*areas)/np.sum(areas)
Cy = np.sum(centroids[:,1]*areas)/np.sum(areas)
#转换为整数
Cx = int(Cx)
Cy = int(Cy)
#将形心坐标添加到列表中
center_list.append([Cx, Cy])

# 打印图像名称和形心坐标
# print(file, Cx, Cy)
# 在原图上绘制形心点和轮廓
# cv2.circle(img, (Cx, Cy), 5, (0, 0, 255), -1)
# cv2.drawContours(img, filted_contours, -1, (0, 255, 0), 2)
# 将修改后的图像保存到./cliber/mark_result文件夹下
# cv2.imwrite("./cliber/mark_result/"+file, img)
# 将center_list保存到./cliber/geometry/center.npy文件中
np.save("./cliber/geometry/center.npy", center_list)





# # 显示结果
# cv2.imshow("Result", img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


# 创建一个窗口,设置标题和大小
#plt.figure("Thresholding", figsize=(10, 5))

# # 在窗口中绘制两个子图,左边是原图,右边是二值化后的图像
# plt.subplot(121), plt.imshow(img, cmap="gray"), plt.title("Original")
# plt.subplot(122), plt.imshow(thresh, cmap="gray"), plt.title("Thresholded")

# # 显示窗口
# plt.show()