将多张图像一次性转换为张量。

huangapple go评论103阅读模式
英文:

Converting multiple images into tensor at once

问题

以下是翻译好的部分:

我有大约10张图片。这些图片大小各不相同。我正在使用OpenCV读取它们并将它们全部转换为(54, 54, 3)的格式。我知道可以将它们每个都转换为张量。有没有一种方法可以将它们一起转换为张量?最终的张量将具有形状(10, 54, 54, 3)。

我正在尝试使用以下代码进行单张图片的转换。

import cv2, glob
import tensorflow as tf
lst = glob.glob("images/*jpg")

im1 = cv2.imread(lst[1])
im1_tensor = tf.convert_to_tensor(im1, dtype=tf.int64)
英文:

I have ~10 images. They images are different in size. I am reading them in OpenCV and converting all of them to (54, 54, 3). I know that I can convert each one of them to a tensor. Is there any way of converting them to tensors altogether? Final tensor will have a shape of (10, 54, 54, 3)

I am trying to use the following codes for single image conversion.

import cv2, glob
import tensorflow as tf
lst = glob.glob("images/*jpg")

im1 = cv2.imread(lst[1])
im1_tensor = tf.convert_to_tensor(im1, dtype=tf.int64)

答案1

得分: 1

尝试以下代码以进行批处理处理。我已经使用了tf.data API。

def parse_image(filepath):
    # 在这个函数中编写您自己的解析逻辑
    image = tf.io.read_file(filepath)
    image = tf.io.decode_jpeg(image)
    image = tf.io.encode_jpeg(image)
    return image

batch_size = 10
pred_files_ds = tf.data.Dataset.list_files(str(IMAGE_PATH/'*'))
pred_imgs_ds = pred_files_ds.map(lambda x: parse_image(x))
for img_batch in pred_imgs_ds.batch(batch_size):
    print(img_batch.shape)
英文:

Try the following code to do batch processing. I have used tf.data API.

def parse_image(filepath):
    # Write your own parsing logic in this function
    image = tf.io.read_file(filepath)
    image = tf.io.decode_jpeg(image)
    image = tf.io.encode_jpeg(image)
    return image

batch_size = 10
pred_files_ds = tf.data.Dataset.list_files(str(IMAGE_PATH/"*"))
pred_imgs_ds = pred_files_ds.map(lambda x: parse_image(x))
for img_batch in pred_imgs_ds.batch(batch_size):
    print(img_batch.shape)

huangapple
  • 本文由 发表于 2023年6月12日 08:45:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定