keras 如何显示tf.image.crop_and_resize中的图像

gr8qqesn  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(146)

我必须在我的图片上应用tf.image.crop_and_resize,并希望从每个图片生成5个框。我已经写了下面的代码,工作正常

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import numpy as np

# Load the pre-trained Xception model to be used as the base encoder.
xception = keras.applications.Xception(
    include_top=False, weights="imagenet", pooling="avg"
)
# Set the trainability of the base encoder.
for layer in xception.layers:
  layer.trainable = False
# Receive the images as inputs.
inputs = layers.Input(shape=(299, 299, 3), name="image_input")

input ='/content/1.png'

input = tf.keras.preprocessing.image.load_img(input,target_size=(299,299,3))
image = tf.expand_dims(np.asarray(input)/255, axis=0)
BATCH_SIZE = 1
NUM_BOXES = 5
IMAGE_HEIGHT = 256
IMAGE_WIDTH = 256
CHANNELS = 3
CROP_SIZE = (24, 24)

boxes = tf.random.uniform(shape=(NUM_BOXES, 4))
box_indices = tf.random.uniform(shape=(NUM_BOXES,), minval=0, maxval=BATCH_SIZE, dtype=tf.int32)

output = tf.image.crop_and_resize(image, boxes, box_indices, CROP_SIZE)
xception_input = tf.keras.applications.xception.preprocess_input(output)

上面的代码工作正常,但是当我想显示这些框时,我运行下面的代码

for i in range(5):

  # define subplot
  plt.subplot(330 + 1 + i)

  # generate batch of images
  batch = xception_input.next()

  # convert to unsigned integers for viewing
  image = batch[0].astype('uint8')

  image = np.reshape(24,24,3)

  # plot raw pixel data
  plt.imshow(image)

#show the figure
plt.show()

但它会产生这个错误AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'next'

xjreopfe

xjreopfe1#

您必须使用[i]而不是.next()
将其转换为uint8也有问题(但不需要转换为reshape

for i in range(5):

  plt.subplot(331 + i)

  tensor = xception_input[i]
  #print(tensor)

  tensor = tensor*255
  image = np.array(tensor, dtype=np.uint8)
  #print(image)

  plt.imshow(image)

或使用for获取项目

for i, tensor in enumerate(xception_input):
  #print(tensor)

  plt.subplot(331 + i)

  tensor = tensor*255
  image = np.array(tensor, dtype=np.uint8)
  #print(image)

  plt.imshow(image)

我不知道你的代码应该做什么,但这给了我空的图像,因为tensor有像-0.9这样的值,它会将其全部转换为0

相关问题