0

我正在使用Python和Numpy來獲取同一像素尺寸的多個圖像並創建一個二維數組,因此數組的每一行代表一個圖像,每一列代表像素某個位置。連接numpy數組中的圖像

爲了實現這一點,我已經閱讀了圖像文件並嘗試使用numpy.concatenate。該代碼是

#url of picture data 
X_p = data.link 
#list for storing the picture data 
X= [] 

#read in the image from the url, and skip poster with 404 error 
for url in X_p: 
    try: 
     loadimg = urllib.request.urlopen(url) 
     image_file = io.BytesIO(loadimg.read()) 
     img = Image.open(image_file) 

     #Concatenate to linearize 
     X.append(np.concatenate(np.array(img))) 

    #404 error 
    except urllib.error.HTTPError as err: 
     if err.code == 404: 
      continue 
     else: 
      raise 

#cast the list into numpy array  
X = np.array(X) 
#test to see if X is in correct dimension 
print(X.shape) 

我跑這個代碼和X的形狀出來,在這種格式每一次

(圖像的數量,高度X寬度,3)

,例如,如果我加載的200x200像素12頁圖像的URL,結果是

(12,40000,3)

我需要的是在最後擺脫3的,這是很難的時候,不甚至瞭解3從哪裏來。

我假設我遇到的問題是在錯誤的地方追加或連接。當我刪除np.concatenate時,它只是顯示(12,200,200,3)。

我在網上搜索numpy圖像處理和連接,但我沒有跑過任何可以解釋和解決發生的事情。

任何和所有的幫助表示讚賞。預先感謝您花時間閱讀這篇文章並回答..

回答

0

我想通了這個問題。我對數組的維度很好奇,所以我搜索了一些問題,要求增加或減少1維。我跑過一個解釋3代表什麼的帖子。

How can I save 3D array results to a 4D array in Python/numpy?

Image.open().convert("L") 

並沒有爲我工作,所以我只好用一招

with Image.open().convert("L") as img 

我加了這一行後的for循環,尺寸問題得到了解決。