首页 > 解决方案 > 为什么 Tensorflow tf.image.decode_jpeg() 将某些图像旋转 90 度?

问题描述

当我使用 Tensorflow tf.image.decode_jpeg() 读取数据管道中的图像时,我有许多旋转 90 度的图像。当我在我的计算机上查看这些图像时,它们看起来方向正确,当我使用 cv2 读取图像时,它们也看起来方向正确。但是,当我使用 Tensorflow tf.image.decode_jpeg() 读取它们时,它们最终旋转了 90 度。任何人都知道为什么或如何解决此问题,以便他们以正确的方向阅读(并非所有图像都会发生这种情况,但很多图像都会发生这种情况)?

为了说明我的意思,这是我的计算机上的示例图像或者当我使用 open-cv 阅读它时的样子。

在此处输入图像描述

但是,当我在管道中使用 Tensorflow (tensorflow 2.4.0) 读取它时,许多图像旋转 90 度,例如,相同的图像最终看起来像这样。

在此处输入图像描述

要使用 cv2 阅读和查看图像,我会这样做

import cv2
import matplotlib.pyplot as plt
import tensorflow as tf

%matplotlib inline

plt.imshow(cv2.imread(image_file_path)[:, :, ::-1]))

使用 Tensorflow 阅读和查看许多旋转图像

def decode_images(dataset_file_paths):
    '''
    tf_read_converted_file_path = tf.io.read_file(dataset_file_paths) 
    return tf.image.decode_jpeg(tf_read_converted_file_path)

def check_processed_images(files_path_dataset, processing_function):
'''Plots images to see what the processing looks like when it is mapped in from a dataset. 
This can be used to, for example, look see how the augmentation of images look.

Arguments:
    files_path_dataset: TF TensorSliceDataset of filenames.
    processing_function: function which is used to map each element in the dataset.
    
Return:
    plot of images'''

augmentation_dataset = files_path_dataset.map(processing_function).shuffle(50).batch(16)

plt.figure(figsize=(13, 13))
for images, labels in augmentation_dataset.take(1):
    for i in range(16):
        ax = plt.subplot(4, 4, i + 1)
        plt.imshow(images[i].numpy())
        
####################
####################
# Look at a sample of images
# Take a directory of jpg images and create a TensorFlow dataset of filepaths
dirPath = type_in_a_directory_here
fileNames = tf.io.gfile.glob(f'{dirPath}/**/*.jpg')
fileNames = tf.random.shuffle(fileNames)
filenamesDs = tf.data.Dataset.from_tensor_slices(fileNames)

check_processed_images(filenamesDs, decode_images)

上面的代码将生成一个图像网格,以便您查看。例如,我计算机上的所有这些图像都有鱼饵,因此它们是水平的,但是当我使用 TensorFlow 处理我的图像时,由于某种原因,许多图像都旋转了 90 度。

在此处输入图像描述

Tensorflow 旋转了我的许多图像,我做错了什么吗?

标签: image-processingcomputer-visiontensorflow2.0

解决方案


它不是旋转图像,它是 pyplot 以格式[W, H, D](宽度、高度、深度)表示图像,而 TensorFlow 和 OpenCV 使用格式[H,W,D]

如果你想用 pyplot 可视化图像而不旋转,你应该使用tf.transpose


推荐阅读