从文件夹中选择随机图像以添加到子图| Python
我有一个包含多个图像的文件夹,我想随机选择一个,并将其添加到子图中(例如使用offsetbox)从文件夹中选择随机图像以添加到子图| Python,python,image,plot,Python,Image,Plot,我有一个包含多个图像的文件夹,我想随机选择一个,并将其添加到子图中(例如使用offsetbox) 如何执行此操作?您可以使用random.choice(imgs)其中imgs是文件夹中的图像列表 首先,只需指定文件夹名称的绝对路径: >>> folder = '/Users/path/to/images/' 然后,您可以通过以下方式获得图像: 最后,随机选择其中一个并将其附加到文件夹的路径: >>> img = os.path.join(folder, ra
如何执行此操作?您可以使用
random.choice(imgs)
其中imgs
是文件夹中的图像列表
首先,只需指定文件夹名称的绝对路径:
>>> folder = '/Users/path/to/images/'
然后,您可以通过以下方式获得图像:
最后,随机选择其中一个并将其附加到文件夹的路径:
>>> img = os.path.join(folder, random.choice(imgs))
>>> img
'/Users/path/to/images/img1.png'
我在项目中使用以下代码:
plt.figure(1 , figsize = (15 , 9))
n = 0
for i in range(49):
n += 1
r = np.random.randint(0 , data.shape[0] , 1)
plt.subplot(7 , 7 , n)
plt.subplots_adjust(hspace = 0.5 , wspace = 0.5)
plt.imshow(data[r[0]])
plt.title('{} : {}'.format('Label1' if labels[r[0]]==1 else 'Label2', labels[r[0]]))
plt.xticks([]) , plt.yticks([])
plt.show()
plt.figure(1 , figsize = (15 , 9))
n = 0
for i in range(49):
n += 1
r = np.random.randint(0 , data.shape[0] , 1)
plt.subplot(7 , 7 , n)
plt.subplots_adjust(hspace = 0.5 , wspace = 0.5)
plt.imshow(data[r[0]])
plt.title('{} : {}'.format('Label1' if labels[r[0]]==1 else 'Label2', labels[r[0]]))
plt.xticks([]) , plt.yticks([])
plt.show()