[英]How to open an image from a list of jpeg image files in text file - variable formation
我有一個文本文件,其中包含要導入腳本的 jpeg 圖像的路徑。 我正在使用 Udemy 課程提供的示例代碼:“使用 Python 進行深度學習 - 從新手到專業!” 檢測圖像中的微笑。 我遇到問題的功能是將圖像轉換為矩陣/二維數組:
def img2array(f, detection=False, ii_size=(64, 64)):
"""
Convert images into matrixes/two-dimensional arrays.
detection - if True we will resize an image to fit the
shape of a data that our first convolutional
layer is accepting which is 32x32 array,
used only on detection.
ii_size - this is the size that our input images have.
"""
rf=None
if detection:
rf=f.rsplit('.')
rf=rf[0]+'-resampled.'+rf[1]
im = Image.open(f)
# Create a smaller scalled down thumbnail
# of our image.
im.thumbnail(ii_size)
# Our thumbnail might not be of a perfect
# dimensions, so we need to create a new
# image and paste the thumbnail in.
newi = Image.new('L', ii_size)
newi.paste(im, (0,0))
newi.save(rf, "JPEG")
f=rf
# Turn images into an array.
data=imread(f, as_gray=True)
# Downsample it from 64x64 to 32x32
# (that's what we need to feed into our first convolutional layer).
data=block_reduce(data, block_size=(2, 2), func=np.mean)
if rf:
remove(rf)
return data
該函數在另一個腳本中調用:
img_data=prep_array(img2array(filename, detection=True), detection=True)
我不確定要命名“文件名”以便此代碼正確運行。 當我給它文本文件路徑時,我收到一條錯誤消息:
UnidentifiedImageError: 無法識別圖像文件 'filepath\\imagelist.txt
我是 Python 的新手,我需要幫助導入正確的“文件名”變量以使此函數工作。
從錯誤消息的外觀來看,您將文本文件的文件路徑(包含圖像路徑)作為filename
傳遞
解析文本文件以獲取圖像的文件路徑並將其傳遞到您的函數中。
with open("path/to/imagelist.txt", "r") as fp:
filepaths = fp.read().splitlines()
for filename in filepaths:
img_data=prep_array(img2array(filename, detection=True), detection=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.