Skip to main content
 首页 » 编程设计

python之我在 Tensorflow (python 3.7) 中加载我的数据集时遇到问题

2024年08月14日26Renyi-Fan

我正在尝试将图像数据集加载到 tensorflow 中,但我在正确加载它时遇到了问题。实际上,我在C盘中有一个名为PetImages的文件夹,其中包含两个名为cat和dog的文件夹。每个文件夹包含更多 12450 图片,因此总共有 24500 图片。我正在使用以下代码加载它们:

import numpy as np 
import matplotlib.pyplot as plt 
import os 
import cv2 
DATADIR = "C:\Datasets\PetImages" 
CATEGORIES = ["Dog","Cat"] 
for the category in CATEGORIES: 
path = os.path.join(DATADIR, category) 
 
for img in os.listdir(path): 
    img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE) 
    plt.imshow(img_array, cmap="gray") 
    plt.show() 
    break 
break 

代码的结果看起来非常好,它显示了文件夹的第一张图片。 然后我使用以下代码将整个阵列的形状转换为所需的像素率:

IMG_SIZE=50 
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) 
plt.imshow(new_array, cmap = "gray") 
plt.show() 

这部分也很好,但我想混合(洗牌)图像,这样我就可以迷惑系统并以这种方式检查准确性,但问题是它只显示 12450 图像 resut在这段代码之后:

training_data = [] 
def create_training_data(): 
for category in CATEGORIES: 
    path = os.path.join(DATADIR, category) 
    class_num = CATEGORIES.index(category) 
for img in os.listdir(path): 
    try: 
        img_array = cv2.imread(os.path.join(path,img),  
cv2.IMREAD_GRAYSCALE) 
        new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) 
        training_data.append([new_array, class_num]) 
    except Exception as e: 
        pass        
create_training_data() 
print(len(training_data) 

然后使用随机我没有成功地随机播放两个文件夹中的图像,它只显示一个文件夹的值。

import random    
random.shuffle(training_data) 
for the sample in training_data[:10]:   
print(sample[1]) 

但我的结果是 1 1 1 1 1 而不是像 0 1 0 1 0 0 0 1 1 这样随机生成的 这种风格我的意思是无法预测下一个将是 1 或 0。

您的帮助对我很有值(value)。提前致谢

请您参考如下方法:

在我看来像是一个缩进错误。您的第二个 for 循环位于您的第一个 for 循环之外,这导致第一个循环完全终止并在进入第二个循环之前将 class_num 设置为 1。你可能想要嵌套它们。尝试:

def create_training_data(): 
    for category in CATEGORIES: 
        path = os.path.join(DATADIR, category) 
        class_num = CATEGORIES.index(category) 
        for img in os.listdir(path): 
            try: 
                img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE) 
                new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) 
                training_data.append([new_array, class_num]) 
            except Exception as e: 
                pass        
create_training_data() 
print(len(training_data)