python - 在 Python 中将图像序列转换为 4D 张量/.npy
问题描述
我有一系列 2D 图像(它是如何通过每个时间步传播的)描绘了一个模拟。假设我有 1000 组模拟,每组包含 10 个时间帧图像。这不是一个监督学习问题,因为没有类标签。模型必须学习如何随着时间的推移进行仿真。(每个模拟都有一个单独的文件夹,每个文件夹包含 10 个时间帧图像)。
任何人都可以帮助我以 [no_frames_in_each_sample, total_samples, image_height, image_width) 的形式(在我们的示例中为 [10, 1000, 64, 64])创建一个合适的 4D 张量/ .npy。
稍后我可以使用它来将其拆分为训练和验证。
任何帮助将非常感激!谢谢你。
解决方案
将图像转换为 4 维数组的示例代码
import tarfile
my_tar = tarfile.open('images.tar.gz')
my_tar.extractall() # specify which folder to extract to
my_tar.close()
import pathlib
data_dir = pathlib.Path('/content/images/')
import tensorflow as tf
batch_size = 32
img_height = 224
img_width = 224
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
class_names = train_ds.class_names
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
val_batches = tf.data.experimental.cardinality(val_ds)
test_dataset = val_ds.take(val_batches // 5)
输出
Found 8 files belonging to 2 classes.
Using 7 files for training.
Found 8 files belonging to 2 classes.
Using 1 files for validation.
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
输出
(7, 224, 224, 3)
(7,)
推荐阅读
- linux - How to send a compiled file to sama5d27 board and execute it?
- excel - VBA 相当于在文本框或形状内按“制表符”?
- php - PHP 多种函数返回类型 String|int
- python - 将日期对象从用户输入传递到数据库(sqlalchemy)
- javafx - 当我已经在方法中抛出错误时出现未处理的异常错误
- html - `margin: 0 auto;` 和 `width:50%` 组合不会使我的 div 居中
- swift - Float32(Float 的别名)和 Float64(Double 的别名)有什么用?
- java - Maven插件的多个配置标签
- pagespeed - PageSpeed Insights 无法识别 WebP。格式
- laravel - 在 Eloquent 中使用第一个请求作为 where 子句的嵌套请求