【问题标题】:Using NumPy Arrays that represent images to create a Tensorflow Machine Learning Model使用表示图像的 NumPy 数组创建 TensorFlow 机器学习模型
【发布时间】:2020-06-27 12:13:32
【问题描述】:

我目前正在开发人脸检测软件,作为人脸识别项目开发的一部分。

我遇到了一个不知道如何解决的问题。 本质上,我将图像转换为 250x250 分辨率,然后将图像转换为扁平 NumPy 数组。

数组导出为 CSV 文件。

img = PIL.Image.open('tmp/images/train/cropped/image (' + str(convert_count) + ').jpg').convert('L')
width, height = img.size

img_size = 25, 25
img = img.resize(img_size)
imgarr = np.array(img)

pixels = list(img.getdata())
width, height = img.size
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]

pixels = np.concatenate(pixels).ravel().tolist()

with open('tmp/csv/train/train (' + str(convert_count) +').csv', 'w') as csvfile:
    fieldnames = ['array']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'array': pixels})

我会假设数组中的元素数量都相同,因为它们是从 25x250 图像转换而来的。然而,这种情况并非如此。相反,我的前 2 个数组(图像)包含 74898 和 73682 个元素。

我想知道,为什么会这样? 因为当输入大小不同时,Tensorflow 不会让我训练模型。 代码如下:

import numpy as np
import tensorflow as tf
from tensorflow import keras
import csv


count = 1
remaining_images = 3
number_images = 3
image_array = {}
image_array[1] = {}
image_array[2] = {}

while remaining_images > count:
    with open('tmp/csv/train/train (' + str(count) + ').csv', 'r') as csvfile:
        reader = csv.reader(csvfile)
        row = [r for r in reader]
    image_array[count] = row[2]
    #print(image_array[count])
    count = count + 1

image_array[1] = str(image_array[1])
image_array[2] = str(image_array[2])

features = np.array([image_array[1], image_array[2]
])


labels = np.array([1, 0])

#Example of the number of Elements in Arrays
array_size = len(features[0])
print(array_size)
array_size = len(features[1])
print(array_size)

batch_size = 2

dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(batch_size)

model = keras.Sequential([
    keras.layers.Dense(5, activation=tf.nn.relu, input_shape=((array_size),)),
    keras.layers.Dense(3, activation=tf.nn.softmax)
])
model.compile(
    optimizer=keras.optimizers.Adam(),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

model.fit(dataset, epochs=100, batch_size=batch_size, verbose=1)

【问题讨论】:

  • 问题可能出在这里:image_array[1] = str(image_array[1]) image_array[2] = str(image_array[2]) 因为将二进制数据转换为字符串可能会由于字符串编码而改变实际大小。
  • @NikosM。你会建议我如何解决这个问题?我对 Python 很陌生,所以我努力想出一个更好的解决方案:)
  • 也许base64编码和解码可以解决这个问题。 stackabuse.com/encoding-and-decoding-base64-strings-in-python

标签: python numpy tensorflow2.0


【解决方案1】:

我很好奇问题是否出在您如何保存到 csv 以及如何从 csv 中获取。

在您的 while 循环(第二个代码块)中,如果您直接使用 PIL 打开图像文件,调整大小,然后使用生成的图像数组(就像您在第一个代码块中所做的那样),这是否解决了大小问题?

此外,由于您将大小调整为 25 x 25 = 625 像素,我认为每个图像数组中应该只有 625 个元素(而不是 74898 和 73682 个元素)。

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 2020-12-02
    • 2019-04-04
    • 2020-07-19
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 2019-08-06
    • 2019-06-22
    相关资源
    最近更新 更多