簡體   English   中英

使用代表圖像的 NumPy Arrays 創建 Tensorflow 機器學習 ZA559B8706892159EEC05084ECE54

[英]Using NumPy Arrays that represent images to create a Tensorflow Machine Learning Model

我目前正在開發人臉檢測軟件,作為人臉識別項目開發的一部分。

我遇到了一個我不知道如何解決的問題。 本質上,我將圖像轉換為 250x250 分辨率,然后將圖像轉換為扁平 NumPy 陣列。

Arrays 導出到 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})

我假設 arrays 中的元素數量都相同,因為它們是從 25x250 圖像轉換而來的。 然而,這種情況並非如此。 相反,我的前 2 個 arrays(圖像)包含 74898 和 73682 個元素。

我想知道,為什么會這樣? 當輸入大小不同時,Tensorflow 不會讓我訓練 model。 下面的代碼:

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)

我很好奇問題是否來自您如何保存到 csv 和從中獲取。

在您的 while 循環(第二個代碼塊)中,如果您直接使用 PIL 打開圖像文件,調整大小,然后使用生成的圖像數組(就像您在第一個代碼塊中所做的那樣),這是否解決了大小問題?

此外,由於您將大小調整為 25 x 25 = 625 像素,我認為每個圖像數組中應該只有 625 個元素(而不是 74898 和 73682 個元素)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM