【发布时间】: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